import { useState, useEffect, type ReactNode } from "react"; import { useParams, Link, useNavigate } from "react-router-dom"; import { useEntry, useEntrySeasons, useRefreshEntry, useEntryCredits, useTmdbPreview, useCreateEntry, } from "@/hooks/useEntries"; import { useEntrySeenByEntry, useDeleteEntrySeen } from "@/hooks/useEntrySeen"; import { useCollections } from "@/hooks/useCollections"; import { useLibraryStore } from "@/stores/useLibraryStore"; import { useCommandPaletteStore } from "@/stores/useCommandPaletteStore"; import { Button } from "@/components/ui/button"; import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Heart, MoreHorizontal, Eye, EyeOff, RefreshCw, FolderPlus, ImageIcon, Settings, Star, History, Trash2, ExternalLink, Play, BookmarkCheck, Film, Tv, Clock, CalendarDays, Globe, Languages, Building2, DollarSign, ListVideo, CircleDot, Plus, Loader2, } from "lucide-react"; import { Tooltip, TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip"; import { CastList } from "@/components/entries/CastList"; import { SeasonsContainer } from "@/components/entries/SeasonsContainer"; import { StreamingSection } from "@/components/streaming/StreamingSection"; import { WatchProvidersCard } from "@/components/entries/WatchProvidersCard"; import { TrailerDialog } from "@/components/entries/TrailerDialog"; import { RecommendationsSection } from "@/components/entries/RecommendationsSection"; import { ArtworkSection } from "@/components/entries/ArtworkSection"; import { EntrySettingsDialog } from "@/components/dialogs/EntrySettingsDialog"; import { EntrySeenDialog } from "@/components/dialogs/EntrySeenDialog"; import { EntryMediaDialog } from "@/components/dialogs/EntryMediaDialog"; import { AddEntryToCollectionDialog } from "@/components/dialogs/AddEntryToCollectionDialog"; import { RatingDialog } from "@/components/dialogs/RatingDialog"; import { MovieWatchHistoryDialog } from "@/components/dialogs/MovieWatchHistoryDialog"; import { ConfirmDialog } from "@/components/dialogs/ConfirmDialog"; import { Dialog, DialogContent, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { EntryDetailsSkeleton } from "@/components/skeletons/PageSkeletons"; import { getTmdbImageUrl } from "@/lib/api"; import { getPosterUrl, getFullPosterUrl, getBackdropUrl, getCollectionBackdropUrl, getYear, formatRuntime, formatDate, } from "@/lib/media-utils"; import { useUpdateEntry, useDeleteEntry } from "@/hooks/useEntries"; import type { Collection, Credit, Entry, EntrySeen, TmdbPreviewSeason, } from "@/types"; const WATCH_STATUSES = [ { value: "plan_to_watch", label: "Plan to Watch", color: "bg-slate-500/15 border-slate-500/30 text-slate-600 dark:text-slate-300", }, { value: "watching", label: "Watching", color: "bg-blue-500/15 border-blue-500/30 text-blue-600 dark:text-blue-300", }, { value: "completed", label: "Completed", color: "bg-green-500/15 border-green-500/30 text-green-600 dark:text-green-300", }, { value: "on_hold", label: "On Hold", color: "bg-amber-500/15 border-amber-500/30 text-amber-600 dark:text-amber-300", }, { value: "dropped", label: "Dropped", color: "bg-red-500/15 border-red-500/30 text-red-600 dark:text-red-300", }, ]; function getWatchStatusInfo(value: string | null | undefined) { return WATCH_STATUSES.find((s) => s.value === value); } const formatMoney = (value: number) => new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", notation: "compact", maximumFractionDigits: 1, }).format(value); const formatCount = (value: number) => new Intl.NumberFormat("en-US", { notation: "compact" }).format(value); const languageName = (() => { try { const names = new Intl.DisplayNames(["en"], { type: "language" }); return (code: string) => names.of(code) ?? code; } catch { return (code: string) => code; } })(); /** * Entry details for both sources: * - `/entry/:id`: a library entry, loaded from the local DB. * - `/entry/tmdb/:type/:tmdbId`: not in the library; everything comes from * the TMDB preview (same shape), and library-only actions are hidden. If * the title is already in the library, redirect to its page. */ export function EntryDetailsPage() { const { id, type, tmdbId } = useParams<{ id?: string; type?: string; tmdbId?: string; }>(); const entryId = id ? parseInt(id, 10) : 0; const isLibrary = !!entryId; const previewTmdbId = !isLibrary && tmdbId ? parseInt(tmdbId, 10) : 0; const previewType = type === "tv" ? "tv" : "movie"; const navigate = useNavigate(); // Library queries are disabled when entryId is 0, the preview when tmdbId is 0 const { data: entry, isLoading } = useEntry(entryId); const { data: seasons } = useEntrySeasons(entryId); const { data: allCredits = [] } = useEntryCredits(entryId); const { data: watchHistory = [] } = useEntrySeenByEntry(entryId); const { data: preview, isLoading: previewLoading, isError: previewError, } = useTmdbPreview(previewTmdbId, previewType); const updateEntry = useUpdateEntry(); const refreshEntry = useRefreshEntry(); const deleteEntrySeen = useDeleteEntrySeen(); const deleteEntry = useDeleteEntry(); const createEntry = useCreateEntry(); // Merge library entry with detail entry so we get both library flags AND full details (credits, etc.) const libraryEntry = useLibraryStore((s) => s.entries.get(entryId)); const libraryMatch = useLibraryStore((s) => { if (!previewTmdbId) return null; for (const le of s.entries.values()) { if (le.entryIds?.tmdb_id === previewTmdbId) return le; } return null; }); const displayEntry: Entry | undefined = isLibrary ? libraryEntry && entry ? { ...libraryEntry, ...entry, isInLibrary: true } : entry || libraryEntry : preview?.entry; // Already in the library: show the library page instead of the preview useEffect(() => { if (libraryMatch) navigate(`/entry/${libraryMatch.id}`, { replace: true }); }, [libraryMatch, navigate]); const [showSettings, setShowSettings] = useState(false); const [showSeenDialog, setShowSeenDialog] = useState(false); const [showMediaDialog, setShowMediaDialog] = useState(false); const [showCollectionDialog, setShowCollectionDialog] = useState(false); const [showRatingDialog, setShowRatingDialog] = useState(false); const [showWatchHistoryDialog, setShowWatchHistoryDialog] = useState(false); const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); const [showStatusDialog, setShowStatusDialog] = useState(false); const [showPosterDialog, setShowPosterDialog] = useState(false); const [showTrailer, setShowTrailer] = useState(false); const [editSeenRecord, setEditSeenRecord] = useState(null); // Track recently viewed for command palette const addRecentlyViewed = useCommandPaletteStore((s) => s.addRecentlyViewed); useEffect(() => { if (displayEntry) { addRecentlyViewed({ id: isLibrary ? `lib-${entryId}` : `tmdb-${previewTmdbId}`, title: displayEntry.title, type: displayEntry.is_tvseries ? "tv" : "movie", poster_path: displayEntry.poster_path, libraryId: isLibrary ? entryId : undefined, tmdbId: displayEntry.entryIds?.tmdb_id ?? undefined, }); } }, [entryId, previewTmdbId, displayEntry?.title]); if (!isLibrary && previewError) { return (

Could not load entry from TMDB.

); } if ( (isLibrary ? isLoading : previewLoading) || !displayEntry || libraryMatch ) { return ; } const e = displayEntry; // Library: useEntryCredits (allCredits) includes both cast AND crew (director); // e.credits from useEntry is a limited preview (10 items). // Preview: the TMDB preview's cast + directors, linked by TMDB id. const credits: Credit[] = isLibrary ? allCredits.length > 0 ? allCredits : e.credits || [] : ((preview?.credits ?? []) as unknown as Credit[]); const previewSeasons = isLibrary ? [] : (preview?.seasons ?? []); const seasonCount = isLibrary ? (seasons?.length ?? 0) : previewSeasons.length; const tmdbType = e.is_tvseries ? "tv" : "movie"; const addToLibrary = () => { createEntry.mutate( { tmdb_id: previewTmdbId, is_tvserie: e.is_tvseries }, { onSuccess: (newEntry) => navigate(`/entry/${newEntry.id}`, { replace: true }), }, ); }; const backdrop = getBackdropUrl(e); const poster = getPosterUrl(e); const director = credits.find( (c) => c.cast_type === "crew" && c.job === "Director", ); const watchStatus = e.is_tvseries ? getWatchStatusInfo(e.watch_status) : undefined; const userRating = e.entryRatings?.user_rating ?? 0; const videos = e.tmdb_videos ?? []; const nextEpisode = e.is_tvseries ? e.next_episode_to_air : null; const socialLinks = [ e.homepage && { label: "Website", href: e.homepage }, e.entryIds?.wikidata_id && { label: "Wikidata", href: `https://www.wikidata.org/wiki/${e.entryIds.wikidata_id}`, }, e.entryIds?.instagram_id && { label: "Instagram", href: `https://www.instagram.com/${e.entryIds.instagram_id}`, }, e.entryIds?.twitter_id && { label: "X", href: `https://x.com/${e.entryIds.twitter_id}`, }, e.entryIds?.facebook_id && { label: "Facebook", href: `https://www.facebook.com/${e.entryIds.facebook_id}`, }, ].filter(Boolean) as { label: string; href: string }[]; const lastSeen = watchHistory .map((wh) => wh.date_seen) .filter(Boolean) .sort() .at(-1) ?? null; const toggleFavorite = () => { updateEntry.mutate({ id: e.id, data: { favorit: !e.favorit } }); }; return (
{/* ── Hero ── */}
{backdrop ? ( ) : (
)} {/* Fade into the page at the bottom and behind the text on the left */}
{/* Eyebrow: type + status */}
{e.is_tvseries ? ( ) : ( )} {e.is_tvseries ? "TV Series" : "Movie"} {e.certification && ( {e.certification} )} {e.is_tvseries && e.status && ( {e.status} )} {e.is_tvseries && isLibrary && ( )}

{e.title}

{e.tagline && (

{e.tagline}

)} {e.original_title && e.original_title !== e.title && (

{e.original_title}

)}
{/* Meta */}
{e.release_date && ( } > {getYear(e.release_date)} {formatDate(e.release_date)} )} {e.runtime && !e.is_tvseries && ( {formatRuntime(e.runtime)} )} {e.is_tvseries && seasonCount > 0 && ( {seasonCount} {seasonCount === 1 ? "season" : "seasons"} )} {e.is_tvseries && e.created_by && e.created_by.length > 0 && ( Created by{" "} {e.created_by.map((c, i) => ( {i > 0 && ", "} {c.name} ))} )} {director?.people?.name && ( Directed by{" "} {director.people.name} )}
{/* Genres */} {e.genres && e.genres.length > 0 && (
{e.genres.map((g) => ( {g.name} ))}
)} {/* Actions */}
{isLibrary ? ( ) : ( )} {videos.length > 0 ? ( ) : ( Trailer )} {isLibrary && (
setShowSeenDialog(true)} > 0 ? "Change rating" : "Rate this"} onClick={() => setShowRatingDialog(true)} active={userRating > 0} > 0 ? "fill-yellow-400 text-yellow-400" : ""}`} /> setShowCollectionDialog(true)} > } > {e.is_tvseries ? ( setShowStatusDialog(true)} > Set status ) : ( setShowWatchHistoryDialog(true)} > Watch history )} updateEntry.mutate({ id: e.id, data: { hidden: !e.hidden }, }) } > {e.hidden ? "Unhide" : "Hide"} refreshEntry.mutate(e.id)} disabled={refreshEntry.isPending} > {refreshEntry.isPending ? "Refreshing..." : "Refresh details"} setShowMediaDialog(true)} > Manage media setShowSettings(true)}> Settings setShowDeleteConfirm(true)} > Delete entry
)}
{/* ── Body ── */}
{e.storyline && (

{e.storyline}

)} {e.keywords && e.keywords.length > 0 && (
{e.keywords.map((k) => ( {k} ))}
)} {credits.length > 0 && ( )} {isLibrary && e.is_tvseries && seasons && seasons.length > 0 && ( )} {!isLibrary && e.is_tvseries && previewSeasons.length > 0 && ( )} {isLibrary && }
{/* ── Sidebar ── */}
{/* Dialogs */} {showSettings && ( )} {showSeenDialog && ( )} {showMediaDialog && ( )} {showCollectionDialog && ( )} {showRatingDialog && ( )} {showWatchHistoryDialog && ( deleteEntrySeen.mutate({ id: seenId, entryId: e.id }) } onEdit={(record) => { setEditSeenRecord(record); setShowWatchHistoryDialog(false); }} /> )} {editSeenRecord && ( { if (!open) setEditSeenRecord(null); }} entry={e} seasons={seasons} mode="edit" editRecord={editSeenRecord} /> )} { deleteEntry.mutate(e.id, { onSuccess: () => navigate("/library"), }); setShowDeleteConfirm(false); }} /> {showTrailer && videos.length > 0 && ( )} {e.title} poster {e.title} Set Watch Status
{WATCH_STATUSES.map((s) => ( ))}
); } /* ---------- Small building blocks ---------- */ function MetaItem({ children }: { children: ReactNode }) { return ( {children} ); } function IconAction({ label, onClick, disabled, active, children, }: { label: string; onClick: () => void; disabled?: boolean; active?: boolean; children: ReactNode; }) { return ( } > {children} {label} ); } function Section({ title, children }: { title: string; children: ReactNode }) { return (

{title}

{children}
); } function RatingTile({ label, value, accent, emptyLabel = "—", sub, onClick, }: { label: string; value: string | null; accent: string; emptyLabel?: string; sub?: string; onClick?: () => void; }) { const content = ( <> {label} {value ? ( {value} /10 ) : ( {emptyLabel} )} {sub && ( {sub} )} ); const className = "flex flex-col items-center gap-1 rounded-xl border border-border/60 bg-card/50 px-2 py-3"; return onClick ? ( ) : (
{content}
); } function DetailRow({ icon, label, children, }: { icon: ReactNode; label: string; children: ReactNode; }) { return (
{icon} {label}
{children}
); } function ExternalChip({ href, children, }: { href: string; children: ReactNode; }) { return ( {children} ); } /* ---------- TMDB seasons (entries not in the library) ---------- */ function TmdbSeasonsStrip({ seasons }: { seasons: TmdbPreviewSeason[] }) { return (
{seasons.map((s) => (
{s.poster_path && ( {s.name} )}

{s.name}

{s.episode_count} eps {s.air_date && ` · ${getYear(s.air_date)}`}

))}
); } /* ---------- Collections section ---------- */ function EntryCollectionsSection({ entryId }: { entryId: number }) { const { data: allCollections = [], isLoading } = useCollections(); const collections = allCollections.filter((col: Collection) => col.entries?.some((e: Entry) => e.id === entryId), ); if (isLoading || collections.length === 0) return null; return (
{collections.map((col: Collection) => (
{col.name}

{col.name}

{col.entries && (

{col.entries.length}{" "} {col.entries.length === 1 ? "title" : "titles"}

)}
))}
); }