import { useState, useEffect, type ReactNode } from "react"; import { useParams, Link, useNavigate } from "react-router-dom"; import { useEntry, useEntrySeasons, useRefreshEntry, useEntryCredits, } 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, } 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 { 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, Entry, EntrySeen } 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; } })(); export function EntryDetailsPage() { const { id } = useParams<{ id: string }>(); const entryId = parseInt(id!, 10); const navigate = useNavigate(); const { data: entry, isLoading } = useEntry(entryId); const { data: seasons } = useEntrySeasons(entryId); const { data: allCredits = [] } = useEntryCredits(entryId); const { data: watchHistory = [] } = useEntrySeenByEntry(entryId); const updateEntry = useUpdateEntry(); const refreshEntry = useRefreshEntry(); const deleteEntrySeen = useDeleteEntrySeen(); const deleteEntry = useDeleteEntry(); // 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 displayEntry = libraryEntry && entry ? { ...libraryEntry, ...entry, isInLibrary: true } : entry || libraryEntry; 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: `lib-${entryId}`, title: displayEntry.title, type: displayEntry.is_tvseries ? "tv" : "movie", poster_path: displayEntry.poster_path, libraryId: entryId, tmdbId: displayEntry.entryIds?.tmdb_id ?? undefined, }); } }, [entryId, displayEntry?.title]); if (isLoading || !displayEntry) { return ; } const e = displayEntry; // Use useEntryCredits (allCredits) which includes both cast AND crew (director). // e.credits from useEntry is a limited preview (10 items). const credits = allCredits.length > 0 ? allCredits : e.credits || []; 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 && ( )}

{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 && seasons && seasons.length > 0 && ( {seasons.length}{" "} {seasons.length === 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 */}
{videos.length > 0 ? ( ) : ( Trailer )}
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 && ( )} {e.is_tvseries && seasons && seasons.length > 0 && ( )}
{/* ── 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} ); } /* ---------- 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"}

)}
))}
); }