import { useEffect, useMemo, useState, type ReactNode } from 'react';
import * as api from '../plex/api';
import type { Item } from '../plex/types';
import { PROGRESS, 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 (
setWatched(item, !watched)} className={watched ? 'is-on' : ''}>
{watched ? 'Watched' : 'Mark watched'}
);
}
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 (
navigate({ name: 'downloads' })}>
);
}
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 (
playItem(trailer, { resume: false })}>
Trailer
);
}
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.id && navigate({ name: 'person', id: t.id, title: t.tag })}>
{t.tag}
) : (
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 (
About
{item.tagline && “{item.tagline}”
}
{rows.map(([k, v]) => (
{k}
{v}
))}
{(m || canManage()) && (
{m && (
openDialog({ kind: 'info', item })}>
Media info
)}
{canManage() && (
openDialog({ kind: 'edit', item })}>
Edit
)}
)}
);
}
// —— Movie ——————————————————————————————————————————————————————————
function MovieDetail({ item }: { item: Item }) {
const resume = item.viewOffset > 0 && !isWatched(item);
return (
playWithVersion(item)}>
{resume ? `Resume · ${remaining(item)}` : 'Play'}
{resume && (
playWithVersion(item, { offsetMs: 0, resume: false })}>
From beginning
)}
{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 || '–'}
{
e.stopPropagation();
playWithVersion(ep);
}}
>
{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}
}
{
e.stopPropagation();
openMenu(itemMenu(ep), e.currentTarget);
}}
>
);
}
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 && (
({ value: s.id, label: s.title, hint: s.leafCount ? `${s.leafCount} ep` : undefined }))}
onChange={(v) => {
setSeasonId(v);
useRouter.getState().setState({ season: v });
}}
/>
)}
{season && (
{season.leafCount} episodes{season.year ? ` · ${season.year}` : ''}
)}
{season?.summary && {season.summary}
}
{episodes.isLoading &&
}
{episodes.data?.map((ep) =>
)}
{episodes.data && !episodes.data.length &&
}
);
}
function ShowDetail({ item }: { item: Item }) {
const seasons = useChildren(item.id);
const server = useServer();
const next = useServerQuery(['onDeck', item.id], (s) => api.onDeckFor(s, item), PROGRESS);
const nextEp = next.data;
const seasonList = (seasons.data ?? []).filter((s) => s.type === 'season');
const percent = useSettings((s) => s.watchedPercent);
const playLabel = nextEp ? (nextEp.viewOffset ? `Resume ${episodeLabel(nextEp)}` : isWatched(item, percent) ? 'Play' : item.viewedLeafCount ? `Watch ${episodeLabel(nextEp)}` : 'Play') : 'Play';
void server;
return (
(nextEp ? playWithVersion(nextEp) : playItem(item))}>
{playLabel}
shuffleItem(item)}>
Shuffle
{nextEp && (
Up next: {episodeLabel(nextEp)} · {nextEp.title}
)}
{seasonList.length > 1 && (
{seasonList.map((s) => (
))}
)}
{seasons.isLoading ?
:
}
);
}
function SeasonDetail({ item }: { item: Item }) {
const show = useItem(item.parentId);
const siblings = useChildren(item.parentId);
const seasonList = (siblings.data ?? []).filter((s) => s.type === 'season');
const episodes = useChildren(item.id);
const percent = useSettings((s) => s.watchedPercent);
const next = (episodes.data ?? []).find((e) => !isWatched(e, percent)) ?? episodes.data?.[0];
const showItem = show.data;
return (
{showItem ? (
navigate({ name: 'item', id: showItem.id })}>
) : (
{item.parentTitle}
)}
{item.title}
>
}
>
next && playWithVersion(next)}>
{next ? (next.viewOffset ? `Resume ${episodeLabel(next)}` : `Play ${episodeLabel(next)}`) : 'Play'}
);
}
function EpisodeDetail({ item }: { item: Item }) {
const show = useItem(item.grandparentId);
const siblings = useChildren(item.parentId);
const resume = item.viewOffset > 0 && !isWatched(item);
const showItem = show.data;
const others = (siblings.data ?? []).filter((e) => e.id !== item.id);
const startIndex = Math.max(0, (siblings.data ?? []).findIndex((e) => e.id === item.id));
const ordered = useMemo(() => [...others.slice(startIndex), ...others.slice(0, startIndex)], [siblings.data, item.id]);
return (
{showItem ? (
navigate({ name: 'item', id: showItem.id })}>
) : (
{item.grandparentTitle}
)}
{item.title}
>
}
>
playWithVersion(item)}>
{resume ? `Resume · ${remaining(item)}` : 'Play'}
{resume && (
playWithVersion(item, { offsetMs: 0, resume: false })}>
From beginning
)}
{technicalLine(item.media[0])}
{ordered.length > 0 && (
navigate({ name: 'item', id: item.parentId })}>
{ordered.map((e) => (
))}
)}
);
}
// —— Collections ——————————————————————————————————————————————————
function CollectionDetail({ item }: { item: Item }) {
const members = useServerQuery(['collectionItems', item.id], (s) => api.collectionItems(s, item.id));
const list = members.data ?? [];
const backdropItem = item.art ? item : list.find((m) => m.art);
return (
{item.title}}>
{list.length ? `${list.length} titles` : 'Collection'}
{item.contentRating && {item.contentRating} }
list[0] && playWithVersion(list.find((m) => !isWatched(m)) ?? list[0])}>
Play
);
}