import { useEffect, useRef, useState, type CSSProperties } from 'react'; import type { Item } from '../plex/types'; import { useServer } from '../app/session'; import { useSettings } from '../app/settings'; import { art, washColors } from '../app/format'; interface Layer { key: number; src: string; blur: Item['ultraBlur']; ready: boolean; } /** How long an outgoing layer lingers: its fade (with delay) plus a margin. */ const LEAVE_MS = 700; /** * Artwork-led page background. The image sits top-right and fades into the * page toward its left and bottom edges; the UltraBlur colour wash tints the * page beneath it and carries on down behind the rows. Artwork crossfades * once the new image has decoded, and the wash's colours blend into the new * title's at the same moment (registered custom properties, app.css). */ export function Backdrop({ item, className = '', width = 1600, height = 900, wash: forceWash }: { item: Item | null | undefined; className?: string; width?: number; height?: number; wash?: Item['ultraBlur'] }) { const server = useServer(); const colorWash = useSettings((s) => s.colorWash); const [layers, setLayers] = useState([]); const counter = useRef(0); const path = item ? art.backdrop(item) : ''; const src = path ? server.image(path, width, height) : ''; const blur = forceWash ?? item?.ultraBlur ?? null; const blurKey = blur ? `${blur.topLeft}${blur.topRight}${blur.bottomRight}${blur.bottomLeft}` : ''; useEffect(() => { if (!src && !blur) return; setLayers((prev) => { const last = prev[prev.length - 1]; // Same art, maybe new colours: the wash blends to them in place. if (last && last.src === src) return prev.map((l) => (l === last ? { ...l, blur } : l)); // Keep only what is on screen (the newest layer that has shown) under the new one. const shown = prev.filter((l) => l.ready).slice(-1); return [...shown, { key: ++counter.current, src, blur, ready: !src }]; }); }, [src, blurKey]); const onReady = (key: number) => setLayers((prev) => (prev.some((l) => l.key === key && !l.ready) ? prev.map((l) => (l.key === key ? { ...l, ready: true } : l)) : prev)); // Once the newest layer is in, the ones beneath fade out and then go. const newest = layers[layers.length - 1]; useEffect(() => { if (!newest?.ready || layers.length < 2) return; const t = setTimeout(() => setLayers((p) => (p[p.length - 1]?.key === newest.key ? p.slice(-1) : p)), LEAVE_MS); return () => clearTimeout(t); }, [newest?.key, newest?.ready, layers.length]); let top = -1; layers.forEach((l, i) => l.ready && (top = i)); const colors = top >= 0 ? washColors(layers[top].blur) : null; const washStyle = { '--wash-tr': colors?.topRight ?? 'transparent', '--wash-tl': colors?.topLeft ?? 'transparent', '--wash-br': colors?.bottomRight ?? 'transparent', '--wash-bl': colors?.bottomLeft ?? 'transparent', } as CSSProperties; return ( <> {colorWash && (