import { useParams, useNavigate } from "react-router-dom"; import { useState, useEffect } from "react"; import { usePerson, usePersonTmdbFilmography, useUpdatePerson, useTmdbPersonPreview, useFetchPersonByTmdbId, } from "@/hooks/usePeople"; import { useLibrary } from "@/hooks/useEntries"; import { useLibraryStore } from "@/stores/useLibraryStore"; import { Skeleton } from "@/components/ui/skeleton"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Separator } from "@/components/ui/separator"; import { Button } from "@/components/ui/button"; import { Tooltip, TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip"; import { EntryCard } from "@/components/entries/EntryCard"; import { getTmdbImageUrl } from "@/lib/api"; import { formatDate, calculateAge } from "@/lib/media-utils"; import { ChevronLeft, ChevronRight, Heart, Plus, Loader2, ExternalLink, } from "lucide-react"; import type { TmdbEntry } from "@/types"; import type { TmdbFilmographyItem, TmdbFilmographyResponse, } from "@/api/people"; /** Person data normalized from either the local DB or a TMDB preview. */ interface PersonProfile { name: string; biography: string | null; birthday: string | null; deathday: string | null; place_of_birth: string | null; profile_path: string | null; known_for_department: string | null; tmdb_id: number | null; favorite: boolean; } /** * Person page for both sources: * - `/people/:id`: the person is in the local DB, so details come from there * and the filmography from TMDB via the local id. * - `/people/tmdb/:tmdbId`: the person is not in the local DB, so everything * comes from the TMDB preview. If the preview reports a local id, redirect. */ export function PersonDetailsPage() { const { id, tmdbId } = useParams<{ id?: string; tmdbId?: string }>(); const navigate = useNavigate(); const localId = id ? parseInt(id, 10) : 0; const isLocal = !!localId; const tmdbIdNum = !isLocal && tmdbId ? parseInt(tmdbId, 10) : 0; // Queries are disabled when their id is 0, so only one source is fetched. const localPerson = usePerson(localId); const localFilmography = usePersonTmdbFilmography(localId); const tmdbPreview = useTmdbPersonPreview(tmdbIdNum); const updatePerson = useUpdatePerson(); const fetchPerson = useFetchPersonByTmdbId(); useLibrary(); const libraryMap = useLibraryStore((s) => s.entries); const libraryLoaded = useLibraryStore((s) => s.isLoaded); const existingLocalId = tmdbPreview.data?.local_id; useEffect(() => { if (existingLocalId) { navigate(`/people/${existingLocalId}`, { replace: true }); } }, [existingLocalId, navigate]); const isError = isLocal ? localPerson.isError : tmdbPreview.isError; if (isError) { return (

Person not found

{isLocal ? "This person could not be loaded. They may not exist in the database." : "Could not load person data from TMDB."}

); } let person: PersonProfile | null = null; let filmography: TmdbFilmographyResponse | undefined; let filmographyLoading = false; if (isLocal && localPerson.data) { const p = localPerson.data; person = { name: p.name, biography: p.biography ?? null, birthday: p.birthday ?? null, deathday: p.deathday ?? null, place_of_birth: p.place_of_birth ?? null, profile_path: p.profile_path ?? null, known_for_department: p.known_for_department ?? null, tmdb_id: p.tmdb_id ?? null, favorite: !!p.favorite, }; filmography = localFilmography.data; filmographyLoading = localFilmography.isLoading; } else if (!isLocal && tmdbPreview.data && !existingLocalId) { const p = tmdbPreview.data; person = { ...p, favorite: false }; filmography = p.filmography; } // Still loading, or about to redirect to the local page. if (!person) { return ; } const isFavorite = person.favorite; const toggleFavorite = () => { updatePerson.mutate({ id: localId, data: { favorite: !isFavorite } }); }; const addToLibrary = () => { fetchPerson.mutate(tmdbIdNum, { onSuccess: (added) => { navigate(`/people/${added.id}`, { replace: true }); }, }); }; return (
{person.name .split(" ") .map((n: string) => n[0]) .join("")}

{person.name}

{isLocal ? ( ) : ( )}
{person.biography && (

{person.biography}

)}
); } /* ─── Shared components ─── */ function PersonMeta({ known_for_department, birthday, deathday, place_of_birth, tmdb_id, }: { known_for_department?: string | null; birthday?: string | null; deathday?: string | null; place_of_birth?: string | null; tmdb_id?: number | null; }) { return (
{known_for_department && {known_for_department}} {birthday && ( <> • }> Born: {formatDate(birthday)} Age: {calculateAge(birthday, deathday)} )} {deathday && ( <> • Died: {formatDate(deathday)} )} {place_of_birth && ( <> • {place_of_birth} )} {tmdb_id && ( <> • TMDB )}
); } function PersonSkeleton() { return (
); } /* ─── Filmography ─── */ interface FilmographySectionProps { libraryMap: Map; libraryLoaded: boolean; tmdbFilmography?: { cast: TmdbFilmographyItem[]; crew: TmdbFilmographyItem[]; }; tmdbLoading: boolean; } function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLoading, }: FilmographySectionProps) { const [libraryPage, setLibraryPage] = useState(0); const [otherPage, setOtherPage] = useState(0); const PAGE_SIZE = 6; // 6 cols × 1 row const GRID = "grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6"; if (tmdbLoading || !libraryLoaded) { return (

Filmography

{Array.from({ length: 6 }).map((_, i) => ( ))}
); } const allTmdbCredits = [ ...(tmdbFilmography?.cast ?? []), ...(tmdbFilmography?.crew?.filter( (c) => c.job === "Director" || c.department === "Directing", ) ?? []), ]; const seenTmdbIds = new Set(); const dedupedCredits = allTmdbCredits.filter((c) => { if (seenTmdbIds.has(c.id)) return false; seenTmdbIds.add(c.id); return true; }); const tmdbIdToLibraryEntry = new Map(); for (const entry of libraryMap.values()) { if (entry.entryIds?.tmdb_id != null) { tmdbIdToLibraryEntry.set(Number(entry.entryIds.tmdb_id), entry); } } // Sort by popularity descending const sorted = [...dedupedCredits].sort( (a, b) => (b.popularity ?? 0) - (a.popularity ?? 0), ); const libraryCredits = sorted.filter((c) => tmdbIdToLibraryEntry.has(c.id)); // "Not in library": sort by release date (new→old), push "self" roles to the end const isSelfRole = (character?: string) => { if (!character) return false; const lower = character.toLowerCase().trim(); return ( lower === "self" || lower.startsWith("self -") || lower.startsWith("self (") || lower === "themselves" || lower === "himself" || lower === "herself" ); }; const otherCreditsSorted = sorted .filter((c) => !tmdbIdToLibraryEntry.has(c.id)) .sort((a, b) => { const aSelf = isSelfRole(a.character) ? 1 : 0; const bSelf = isSelfRole(b.character) ? 1 : 0; if (aSelf !== bSelf) return aSelf - bSelf; // Both same self status → sort by date descending (new first) const dateA = new Date( a.release_date || a.first_air_date || "1900", ).getTime(); const dateB = new Date( b.release_date || b.first_air_date || "1900", ).getTime(); return dateB - dateA; }); const otherCredits = otherCreditsSorted; if (sorted.length === 0) { return (

Filmography

No filmography found.

); } const librarySlice = libraryCredits.slice( libraryPage * PAGE_SIZE, (libraryPage + 1) * PAGE_SIZE, ); const otherSlice = otherCredits.slice( otherPage * PAGE_SIZE, (otherPage + 1) * PAGE_SIZE, ); const libraryTotalPages = Math.ceil(libraryCredits.length / PAGE_SIZE); const otherTotalPages = Math.ceil(otherCredits.length / PAGE_SIZE); return (

Filmography

{libraryCredits.length > 0 && (

In Your Library ({libraryCredits.length})

{libraryTotalPages > 1 && (
{libraryPage + 1}/{libraryTotalPages}
)}
{librarySlice.map((credit) => { const entry = tmdbIdToLibraryEntry.get(credit.id)!; return (
{credit.character && (

{credit.character}

)}
); })}
)} {otherCredits.length > 0 && (

Not in Library ({otherCredits.length})

{otherTotalPages > 1 && (
{otherPage + 1}/{otherTotalPages}
)}
{otherSlice.map((credit) => { const tmdbEntry: TmdbEntry = { id: credit.id, title: credit.title, name: credit.name, poster_path: credit.poster_path, backdrop_path: null, release_date: credit.release_date, first_air_date: credit.first_air_date, media_type: credit.media_type, overview: "", vote_average: 0, vote_count: 0, genre_ids: [], popularity: credit.popularity ?? 0, }; return (
{credit.character && (

{credit.character}

)}
); })}
)}
); }