import { memo, useEffect, useRef, useState, type ReactNode } from 'react';
import type { Item } from '../plex/types';
import { useServer } from '../app/session';
import { useSettings } from '../app/settings';
import { art, displayTitle, duration, episodeLabel, formatBadges, isWatched, progress, remaining, remainingEpisodes } from '../app/format';
import { itemMenu, openItem, playWithVersion } from '../app/actions';
import { Artwork } from './primitives';
import { Icon } from './Icon';
import { openMenu } from './overlays';
import { previewHandlers } from './HoverPreview';
import rtHot from '../assets/rt-hot.svg';
import rtStale from '../assets/rt-stale.svg';
import imdb from '../assets/imdb.svg';
// —— Ratings and facts ————————————————————————————————————————————
export function Ratings({ item, compact }: { item: Item; compact?: boolean }) {
const audience = item.scores.filter((s) => s.kind === 'audience');
const rt = audience.find((s) => s.source === 'Rotten Tomatoes');
const im = audience.find((s) => s.source === 'IMDb');
const fallback = !rt && !im ? audience.find((s) => s.source === 'TVDB' || s.source === 'TMDB') : null;
if (!rt && !im && !fallback) return null;
return (
{rt && (
= 6 ? rtHot : rtStale} alt="Rotten Tomatoes" />
{Math.round(rt.value * 10)}%
)}
{im && (
{im.value.toFixed(1)}
)}
{fallback && (
{fallback.value.toFixed(1)}
)}
);
}
export function FormatBadges({ item }: { item: Item }) {
const badges = formatBadges(item);
if (!badges.length) return null;
return (
{badges.map((b) => (
{b}
))}
);
}
/** "TV-MA · 2014 · Drama / Mystery · 1h 58m · [RT] [IMDb] · 4K HDR" */
export function Facts({ item, withFormats = true, episode = true, children }: { item: Item; withFormats?: boolean; episode?: boolean; children?: ReactNode }) {
const parts: ReactNode[] = [];
if (item.type === 'episode') {
if (episode) parts.push({episodeLabel(item)});
if (item.originallyAvailableAt) parts.push({new Date(item.originallyAvailableAt).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })});
} else if (item.year) parts.push({item.year});
if (item.genres.length && item.type !== 'episode') parts.push({item.genres.slice(0, 2).map((g) => g.tag).join(' / ')});
if (item.type === 'show') {
if (item.childCount) parts.push({item.childCount} season{item.childCount === 1 ? '' : 's'});
} else if (item.type === 'season') {
if (item.leafCount) parts.push({item.leafCount} episodes);
} else if (item.viewOffset && item.duration) parts.push({remaining(item)});
else if (item.duration) parts.push({duration(item.duration)});
return (
{item.contentRating && {item.contentRating.replace(/^gb\//, '')}}
{parts.map((p, i) => (
{i > 0 && ·}
{p}
))}
{withFormats && }
{children}
);
}
/** Original clear-logo artwork, falling back to the title in type. */
export function TitleArt({ item, logo, className = '', maxWidth = 420, maxHeight = 130, as: As = 'h1' }: { item: Item; logo?: string; className?: string; maxWidth?: number; maxHeight?: number; as?: 'h1' | 'h2' }) {
const server = useServer();
const path = logo ?? item.logo;
const [failed, setFailed] = useState(false);
const [ready, setReady] = useState(false);
useEffect(() => {
setFailed(false);
setReady(false);
}, [path]);
const title = item.type === 'episode' ? item.grandparentTitle : item.type === 'season' ? item.parentTitle || item.title : item.title;
if (!path || failed)
return (
{title}
);
return (
setReady(true)}
onError={() => setFailed(true)}
style={{ maxWidth, maxHeight }}
/>
);
}
// —— Card decorations —————————————————————————————————————————————
function WatchBadge({ item }: { item: Item }) {
const percent = useSettings((s) => s.watchedPercent);
if (isWatched(item, percent))
return (
);
if ((item.type === 'show' || item.type === 'season') && item.leafCount && item.viewedLeafCount > 0)
return (
{remainingEpisodes(item)}
);
if ((item.type === 'show' || item.type === 'season') && item.leafCount && item.viewedLeafCount === 0) return null;
return null;
}
function ProgressLine({ item }: { item: Item }) {
const p = progress(item);
if (!p || p > 0.995) return null;
return (
);
}
function useCardHandlers(item: Item, ctx: { continueWatching?: boolean } = {}) {
return {
onClick: () => openItem(item),
onContextMenu: (e: React.MouseEvent) => {
e.preventDefault();
openMenu(itemMenu(item, ctx), { x: e.clientX, y: e.clientY });
},
onKeyDown: (e: React.KeyboardEvent) => {
if (e.key === 'Enter') openItem(item);
if (e.key === ' ') {
e.preventDefault();
playWithVersion(item);
}
},
};
}
function CardActions({ item, ctx }: { item: Item; ctx?: { continueWatching?: boolean } }) {
const playable = ['movie', 'episode', 'show', 'season', 'clip'].includes(item.type);
return (
{playable && (
)}
);
}
// —— Cards ——————————————————————————————————————————————————————————
export const PosterCard = memo(function PosterCard({ item, caption = 'year', className = '' }: { item: Item; caption?: 'year' | 'none' | 'episodes' | 'role'; className?: string }) {
const server = useServer();
const handlers = useCardHandlers(item);
const path = art.poster(item);
let meta: ReactNode = null;
if (caption === 'year') meta = item.type === 'episode' ? episodeLabel(item) : item.type === 'season' ? (item.leafCount ? `${item.leafCount} episodes` : '') : item.type === 'collection' ? (item.childCount ? `${item.childCount} titles` : 'Collection') : item.year || '';
if (caption === 'episodes') meta = item.leafCount ? `${item.leafCount} episodes` : '';
if (caption === 'role') meta = (item as any).roleName ?? item.year;
return (
{caption !== 'none' && (
{item.type === 'season' ? item.title : displayTitle(item)}
{meta ?
{meta}
: null}
)}
);
});
export const LandscapeCard = memo(function LandscapeCard({ item, continueWatching, showTitle = true, episodeStyle = false }: { item: Item; continueWatching?: boolean; showTitle?: boolean; episodeStyle?: boolean }) {
const server = useServer();
const handlers = useCardHandlers(item, { continueWatching });
const isEp = item.type === 'episode';
const path = isEp ? item.thumb || item.grandparentArt : art.landscape(item);
const title = episodeStyle && isEp ? `${item.index}. ${item.title}` : displayTitle(item);
const meta = isEp
? episodeStyle
? [duration(item.duration), item.viewOffset ? remaining(item) : ''].filter(Boolean).join(' · ')
: `${episodeLabel(item)} ${item.title}`
: item.viewOffset
? remaining(item)
: [item.year, duration(item.duration)].filter(Boolean).join(' · ');
return (
{title}} />
{!isEp && item.logo && continueWatching && (
)}
{episodeStyle && }
{showTitle && (
)}
);
});
export function PersonCard({ name, role, thumb, onClick }: { name: string; role?: string; thumb?: string; onClick?: () => void }) {
const server = useServer();
const initials = name
.split(/\s+/)
.map((x) => x[0])
.slice(0, 2)
.join('');
return (
);
}
// —— Shelf ——————————————————————————————————————————————————————————
export function Shelf({ title, subtitle, onViewAll, children, className = '', kind = 'poster' }: { title: ReactNode; subtitle?: ReactNode; onViewAll?: () => void; children: ReactNode; className?: string; kind?: 'poster' | 'landscape' | 'people' | 'wide' }) {
const row = useRef(null);
const [edges, setEdges] = useState({ start: true, end: false });
const update = () => {
const el = row.current;
if (!el) return;
const start = el.scrollLeft < 8;
const end = el.scrollLeft + el.clientWidth >= el.scrollWidth - 8;
// Runs on every scroll event; re-render only when an edge changes.
setEdges((prev) => (prev.start === start && prev.end === end ? prev : { start, end }));
};
useEffect(() => {
update();
const el = row.current;
if (!el) return;
const ro = new ResizeObserver(update);
ro.observe(el);
return () => ro.disconnect();
}, [children]);
const page = (dir: number) => {
const el = row.current;
if (!el) return;
el.scrollBy({ left: dir * (el.clientWidth - 120), behavior: 'smooth' });
};
return (
{onViewAll ? (
) : (
title
)}
{subtitle && {subtitle}}
{children}
);
}
/** A hub shelf with the right card style for its contents. */
export function HubShelf({ title, items, onViewAll, continueWatching, landscape }: { title: string; items: Item[]; onViewAll?: () => void; continueWatching?: boolean; landscape?: boolean }) {
if (!items.length) return null;
const wide = landscape ?? (continueWatching || items.every((i) => i.type === 'episode' || i.type === 'clip'));
return (
{items.map((i) => (wide ? : ))}
);
}