import { useEffect, useMemo, useState, type ReactNode } from 'react'; import * as api from '../plex/api'; import type { Item } from '../plex/types'; import { useChildren, useItem, useRelated, useServerQuery } from '../app/queries'; import { useServer } from '../app/session'; import { useSettings } from '../app/settings'; import { goBack, navigate, useRouter } from '../app/router'; import { canManage, itemMenu, openDialog, openItem, playItem, playWithVersion, setWatched, shuffleItem } from '../app/actions'; import { bitrate, channelLabel, date, duration, episodeLabel, extraLabel, fileSize, isWatched, remaining, resolutionLabel, technicalLine } from '../app/format'; import { Backdrop } from '../ui/Backdrop'; import { Facts, HubShelf, LandscapeCard, PersonCard, PosterCard, Shelf, TitleArt } from '../ui/media'; import { Artwork, Button, EmptyState, ErrorState, IconButton, PageLoader, Select } from '../ui/primitives'; import { Icon } from '../ui/Icon'; import { openMenu } from '../ui/overlays'; import { useDownloads } from '../downloads/store'; import { playThemeMusic, stopThemeMusic } from '../player/theme'; export function ItemScreen({ id }: { id: string }) { const q = useItem(id); const item = q.data; useEffect(() => { if (item?.theme && item.type !== 'collection') playThemeMusic(item.theme); }, [item?.theme]); useEffect(() => () => stopThemeMusic(), []); if (q.isError) return
q.refetch()} />
; if (!item) return ; switch (item.type) { case 'show': return ; case 'season': return ; case 'episode': return ; case 'collection': return ; default: return ; } } // —— Shared pieces ———————————————————————————————————————————————— /** Long descriptions open in place when clicked, and close again the same way. */ function Synopsis({ text }: { item: Item; text: string }) { const [clamped, setClamped] = useState(false); const [open, setOpen] = useState(false); useEffect(() => setOpen(false), [text]); if (!text) return null; const toggle = () => (clamped || open) && setOpen(!open); return (

(e.key === 'Enter' || e.key === ' ') && (e.preventDefault(), toggle())} ref={(el) => { if (el && !open) setClamped(el.scrollHeight > el.clientHeight + 2); }} > {text}

); } function WatchedButton({ item }: { item: Item }) { const percent = useSettings((s) => s.watchedPercent); const watched = isWatched(item, percent); return ( ); } function DownloadButton({ item }: { item: Item }) { const downloads = useDownloads(); const isSeries = item.type === 'show' || item.type === 'season'; const dl = downloads.items.find((d) => d.id === downloads.idFor(item.id)); if (isSeries) return downloads.startAll(item)} />; if (dl?.status === 'completed') return navigate({ name: 'downloads' })} />; if (dl) { const pct = dl.total ? Math.round((dl.received / dl.total) * 100) : 0; return ( ); } return downloads.start(item)} />; } function MoreButton({ item, onDeleted }: { item: Item; onDeleted?: () => void }) { return openMenu(itemMenu(item, { detail: true, onDeleted }), e.currentTarget)} />; } function TrailerButton({ item }: { item: Item }) { const trailer = item.extras.find((e) => e.subtype === 'trailer' && e.media.length); if (!trailer) return null; return ( ); } function DetailHero({ item, backdropItem, children, title, below }: { item: Item; backdropItem?: Item; children: ReactNode; title?: ReactNode; below?: ReactNode }) { return ( <>
{title ?? } {children}
{below}
); } function CastRow({ item, title = 'Cast & Crew' }: { item: Item; title?: string }) { const people = [ ...item.roles.map((r) => ({ id: r.id, name: r.tag, role: r.role, thumb: r.thumb })), ...item.directors.map((d) => ({ id: d.id, name: d.tag, role: 'Director', thumb: (d as any).thumb ?? item.raw?.Director?.find((x: any) => x.tag === d.tag)?.thumb })), ...item.writers.slice(0, 3).map((d) => ({ id: d.id, name: d.tag, role: 'Writer', thumb: item.raw?.Writer?.find((x: any) => x.tag === d.tag)?.thumb })), ]; if (!people.length) return null; return ( {people.map((p, i) => ( navigate({ name: 'person', id: p.id, title: p.name, thumb: p.thumb }) : undefined} /> ))} ); } function ExtrasRow({ item }: { item: Item }) { const extras = item.extras.filter((e) => e.media.length); if (!extras.length) return null; return ( {extras.map((e) => (
playItem(e, { resume: false })} onKeyDown={(ev) => ev.key === 'Enter' && playItem(e, { resume: false })}>
{e.title}
{[extraLabel(e), duration(e.duration)].filter(Boolean).join(' · ')}
))}
); } function ExtraCover({ item }: { item: Item }) { const server = useServer(); return (
); } function RelatedRows({ item }: { item: Item }) { const related = useRelated(item.id); const hubs = (related.data ?? []).map((h) => ({ ...h, items: h.items.filter((i) => i.id !== item.id && ['movie', 'show'].includes(i.type)) })).filter((h) => h.items.length); return ( <> {hubs.slice(0, 3).map((h) => ( ))} ); } function AboutPanel({ item }: { item: Item }) { const m = item.media[0]; const rows: [string, ReactNode][] = []; const tags = (list: { tag: string; id: string }[], filter: string, limit = 3) => list.slice(0, limit).map((t, i) => ( {i > 0 && ', '} {filter === 'person' ? ( ) : ( t.tag )} )); if (item.directors.length) rows.push([item.directors.length > 1 ? 'Directors' : 'Director', tags(item.directors, 'person')]); if (item.writers.length) rows.push(['Writers', tags(item.writers, 'person')]); if (item.studio) rows.push([item.type === 'show' || item.type === 'episode' ? 'Network' : 'Studio', item.studio]); if (item.originallyAvailableAt) rows.push([item.type === 'show' ? 'Premiered' : 'Released', date(item.originallyAvailableAt)]); if (item.genres.length) rows.push(['Genres', item.genres.map((g) => g.tag).join(', ')]); if (item.countries.length) rows.push(['Country', item.countries.map((c) => c.tag).join(', ')]); if (item.contentRating) rows.push(['Rated', item.contentRating]); if (item.duration && item.type !== 'show') rows.push(['Runtime', duration(item.duration)]); for (const s of item.scores) rows.push([`${s.source}${s.kind === 'critic' ? ' critics' : ''}`, s.source === 'Rotten Tomatoes' ? `${Math.round(s.value * 10)}%` : `${s.value.toFixed(1)} / 10`]); if (item.collections.length) rows.push(['Collections', item.collections.map((c) => c.tag).join(', ')]); if (item.labels.length) rows.push(['Labels', item.labels.map((c) => c.tag).join(', ')]); if (item.editionTitle) rows.push(['Edition', item.editionTitle]); if (m) { rows.push(['Video', [resolutionLabel(m), m.dynamicRange, m.videoCodec.toUpperCase(), m.videoFrameRate].filter(Boolean).join(' · ')]); rows.push(['Audio', [m.audioCodec.toUpperCase(), channelLabel(m.audioChannels), m.atmos ? 'Atmos' : ''].filter(Boolean).join(' · ')]); if (m.bitrate) rows.push(['Bitrate', bitrate(m.bitrate)]); const size = m.parts.reduce((a, p) => a + p.size, 0); if (size) rows.push(['File size', fileSize(size)]); if (item.media.length > 1) rows.push(['Versions', `${item.media.length} available`]); } if (item.addedAt) rows.push(['Added', date(item.addedAt)]); return ( ); } // —— Movie —————————————————————————————————————————————————————————— function MovieDetail({ item }: { item: Item }) { const resume = item.viewOffset > 0 && !isWatched(item); return (
{resume && ( )}
{resume && (
)}
{technicalLine(item.media[0])}
); } // —— Shows and seasons ———————————————————————————————————————————— function EpisodeRow({ ep }: { ep: Item }) { const server = useServer(); const percent = useSettings((s) => s.watchedPercent); const watched = isWatched(ep, percent); const p = ep.viewOffset && ep.duration ? ep.viewOffset / ep.duration : 0; return (
openItem(ep)} onKeyDown={(e) => e.key === 'Enter' && openItem(ep)} onContextMenu={(e) => { e.preventDefault(); openMenu(itemMenu(ep), { x: e.clientX, y: e.clientY }); }} >
{ep.index || '–'}
{p > 0 && !watched && ( )}

{ep.title} {watched && }

{[duration(ep.duration), ep.originallyAvailableAt ? date(ep.originallyAvailableAt) : '', ep.viewOffset && !watched ? remaining(ep) : ''].filter(Boolean).join(' · ')}
{ep.summary &&

{ep.summary}

}
); } function Episodes({ seasons, initialSeason, showPicker = true }: { seasons: Item[]; initialSeason?: string; showPicker?: boolean }) { const saved = useRouter((s) => s.current.state.season as string | undefined); const [seasonId, setSeasonId] = useState(saved ?? initialSeason ?? seasons[0]?.id); useEffect(() => { if (!seasonId && seasons[0]) setSeasonId(initialSeason ?? seasons[0].id); }, [seasons, initialSeason]); const episodes = useChildren(seasonId); const season = seasons.find((s) => s.id === seasonId); if (!seasons.length) return null; return (

Episodes

{showPicker && seasons.length > 1 && (