"use client"; import { useState, useEffect, useRef, useCallback, useMemo, startTransition } from "react"; import Image from "next/image"; import Link from "next/link"; import { ReviewPlayer, type ReviewPlayerRef } from "@/components/player/ReviewPlayer"; import { SequencePlayer, type SequenceClip } from "@/components/player/SequencePlayer"; import { useReviewStore } from "@/hooks/use-review-player"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Badge } from "@/components/ui/badge"; import { cn } from "@/lib/utils"; import { Button } from "@/components/ui/button"; import { internallyApproveShot, shareWithClient } from "@/actions/shots"; import { useToast } from "@/components/ui/use-toast"; import { Film, Loader2, CheckCircle2, AlertCircle, Clock, ExternalLink, ShieldCheck, Send, ListVideo, X, } from "lucide-react"; interface Project { id: string; name: string; code: string; projectType: string; } interface PlaylistVersion { id: string; versionNumber: number; fileUrl: string; thumbnailUrl: string | null; posterUrl: string | null; fps: number; duration?: number | null; frameCount?: number | null; hqFileUrl?: string | null; handleHead?: number | null; handleTail?: number | null; pictureStartFrame?: number | null; approvalStatus: string; taskTitle: string; } interface PlaylistShot { id: string; shotCode: string; episode: string | null; status: string; shotApprovalStatus: string; sharedWithClient: boolean; thumbnailUrl: string | null; latestVersion: PlaylistVersion; } interface PlaylistClientProps { projects: Project[]; userRole: string; } const APPROVAL_COLORS: Record = { PENDING_REVIEW: "bg-amber-500/10 text-amber-400 border-amber-500/20", APPROVED: "bg-emerald-500/10 text-emerald-400 border-emerald-500/20", REJECTED: "bg-red-500/10 text-red-400 border-red-500/20", NEEDS_CHANGES: "bg-orange-500/10 text-orange-400 border-orange-500/20", }; const APPROVAL_ICONS: Record = { PENDING_REVIEW: Clock, APPROVED: CheckCircle2, REJECTED: AlertCircle, NEEDS_CHANGES: AlertCircle, }; export function PlaylistClient({ projects, userRole }: PlaylistClientProps) { const playerRef = useRef(null); const reset = useReviewStore((s) => s.reset); const { toast } = useToast(); const [projectId, setProjectId] = useState(null); const [shots, setShots] = useState([]); const [activeShot, setActiveShot] = useState(null); const [isLoading, setIsLoading] = useState(false); const [isActioning, setIsActioning] = useState(false); /** Shots checked for the seamless playlist, by shot id. */ const [selected, setSelected] = useState>(new Set()); const [sequenceMode, setSequenceMode] = useState(false); const lastChecked = useRef(null); const canApprove = ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(userRole); // Restore last project from localStorage on mount useEffect(() => { const saved = localStorage.getItem("playlist:lastProjectId"); if (saved && projects.some((p) => p.id === saved)) { setProjectId(saved); } }, [projects]); // Fetch shots whenever project changes useEffect(() => { if (!projectId) { setShots([]); setActiveShot(null); return; } let cancelled = false; setIsLoading(true); fetch(`/api/playlist?projectId=${projectId}`) .then((r) => r.json()) .then((data) => { if (cancelled) return; const list: PlaylistShot[] = data.shots ?? []; setShots(list); setSelected(loadSelection(projectId, list)); lastChecked.current = null; setSequenceMode(false); // Auto-select the first shot, or keep the current one if it still exists setActiveShot((prev) => { const stillExists = prev && list.some((s) => s.id === prev.id); return stillExists ? prev : (list[0] ?? null); }); }) .catch(() => { if (!cancelled) setShots([]); }) .finally(() => { if (!cancelled) setIsLoading(false); }); return () => { cancelled = true; }; }, [projectId]); const handleProjectChange = (id: string) => { localStorage.setItem("playlist:lastProjectId", id); setProjectId(id); }; const handleSelectShot = useCallback((shot: PlaylistShot) => { reset(); setSequenceMode(false); setActiveShot(shot); }, [reset]); const updateSelection = useCallback( (next: Set) => { setSelected(next); if (projectId) saveSelection(projectId, next); if (next.size === 0) setSequenceMode(false); }, [projectId] ); /** Toggle one shot; shift-click sets every shot between it and the last one checked. */ const toggleChecked = (shot: PlaylistShot, shift: boolean) => { const next = new Set(selected); const on = !selected.has(shot.id); const from = lastChecked.current ? shots.findIndex((s) => s.id === lastChecked.current) : -1; const to = shots.findIndex((s) => s.id === shot.id); const range = shift && from >= 0 ? shots.slice(Math.min(from, to), Math.max(from, to) + 1) : [shot]; for (const s of range) { if (on) next.add(s.id); else next.delete(s.id); } lastChecked.current = shot.id; updateSelection(next); }; const setGroupChecked = (group: PlaylistShot[], on: boolean) => { const next = new Set(selected); for (const s of group) { if (on) next.add(s.id); else next.delete(s.id); } updateSelection(next); }; // The playlist, in edit order. Keyed on the versions it plays so a refresh // (e.g. after approving a shot) doesn't restart playback. const clipKey = shots .filter((s) => selected.has(s.id)) .map((s) => s.latestVersion.id) .join(","); const clips = useMemo( () => shots .filter((s) => selected.has(s.id)) .map((s) => ({ id: s.latestVersion.id, label: s.shotCode, sublabel: `v${String(s.latestVersion.versionNumber).padStart(3, "0")}`, url: s.latestVersion.fileUrl, hqUrl: s.latestVersion.hqFileUrl, fps: s.latestVersion.fps, duration: s.latestVersion.duration, handles: s.latestVersion, })), // eslint-disable-next-line react-hooks/exhaustive-deps [clipKey] ); const handleClipChange = useCallback( (clip: SequenceClip) => { // A transition, so re-rendering the page (shot list and all) yields to // the video: rendered in one go, it dropped the frame after every cut. startTransition(() => { setActiveShot(shots.find((s) => s.latestVersion.id === clip.id) ?? null); }); }, [shots] ); const refreshShots = useCallback(() => { if (!projectId) return; fetch(`/api/playlist?projectId=${projectId}`) .then((r) => r.json()) .then((data) => { const list: PlaylistShot[] = data.shots ?? []; setShots(list); setActiveShot((prev) => prev ? (list.find((s) => s.id === prev.id) ?? prev) : null); }) .catch(() => {}); }, [projectId]); const handleInternallyApprove = async () => { if (!activeShot) return; setIsActioning(true); try { await internallyApproveShot(activeShot.id); toast({ title: "Shot internally approved", description: "Status: Ready for Client" }); refreshShots(); } catch (e) { toast({ title: "Failed", description: (e as Error).message, variant: "destructive" }); } finally { setIsActioning(false); } }; const handleShareWithClient = async () => { if (!activeShot) return; setIsActioning(true); try { await shareWithClient(activeShot.id); toast({ title: "Shared with client", description: "Status: Client Review" }); refreshShots(); } catch (e) { toast({ title: "Failed", description: (e as Error).message, variant: "destructive" }); } finally { setIsActioning(false); } }; // Group shots by episode for episodic projects const selectedProject = projects.find((p) => p.id === projectId); const isEpisodic = selectedProject?.projectType === "EPISODIC"; const episodeGroups: [string, PlaylistShot[]][] = isEpisodic ? (() => { const map = new Map(); for (const shot of shots) { const key = shot.episode ?? "(No Episode)"; if (!map.has(key)) map.set(key, []); map.get(key)!.push(shot); } return Array.from(map.entries()); })() : []; return (
{/* Toolbar */}
Playlist
{selected.size > 0 && ( sequenceMode ? ( ) : ( ) )} {activeShot && (
{activeShot.shotCode} {(() => { const Icon = APPROVAL_ICONS[activeShot.latestVersion.approvalStatus] ?? Clock; return ; })()} {activeShot.latestVersion.approvalStatus.replace(/_/g, " ")} {canApprove && activeShot.shotApprovalStatus === "PENDING" && ( )} {canApprove && activeShot.shotApprovalStatus === "INTERNALLY_APPROVED" && !activeShot.sharedWithClient && ( )}
)}
{/* Body: player + shot panel */}
{/* Player */}
{sequenceMode && clips.length > 0 ? ( ) : activeShot ? ( ) : (

{!projectId ? "Select a project to start" : isLoading ? "" : "No shots with video versions found"}

{isLoading && }
)}
{/* Shot panel */}
Shots {shots.length > 0 && (
{selected.size > 0 ? ( ) : ( )} {selected.size > 0 ? `${selected.size}/${shots.length}` : shots.length}
)}
{isLoading ? (
) : !projectId ? (

Select a project

) : shots.length === 0 ? (

No video versions found

) : isEpisodic ? (
{episodeGroups.map(([episode, episodeShots]) => (
{episodeShots.map((shot) => ( toggleChecked(shot, shift)} onClick={() => handleSelectShot(shot)} /> ))}
))}
) : (
{shots.map((shot) => ( toggleChecked(shot, shift)} onClick={() => handleSelectShot(shot)} /> ))}
)}
); } function ShotThumbnail({ shot, isActive, isChecked, onToggle, onClick, }: { shot: PlaylistShot; isActive: boolean; isChecked: boolean; onToggle: (shift: boolean) => void; onClick: () => void; }) { const thumb = shot.latestVersion.thumbnailUrl ?? shot.latestVersion.posterUrl ?? shot.thumbnailUrl; const ApprovalIcon = APPROVAL_ICONS[shot.latestVersion.approvalStatus] ?? Clock; return (
{ if (e.key === "Enter") onClick(); }} className={cn( "w-full flex items-start gap-2.5 px-3 py-2.5 text-left transition-colors border-b border-zinc-800/60 group cursor-pointer", isActive ? "bg-blue-500/10 border-l-2 border-l-blue-500" : "hover:bg-zinc-800/40 border-l-2 border-l-transparent" )} > {}} onClick={(e) => { e.stopPropagation(); onToggle(e.shiftKey); }} className="mt-3 h-3.5 w-3.5 shrink-0 accent-blue-500 cursor-pointer" title="Add to playlist (shift-click for a range)" /> {/* Thumbnail */}
{thumb ? ( {shot.shotCode} ) : ( )}
{/* Info */}

{shot.shotCode}

{shot.latestVersion.taskTitle}

c.startsWith("text-")) ?? "text-zinc-400" )}> v{String(shot.latestVersion.versionNumber).padStart(3, "0")} {" ยท "} {shot.latestVersion.approvalStatus.replace(/_/g, " ")}
); } const selectionKey = (projectId: string) => `playlist:selection:${projectId}`; /** The checked shots remembered for this project, minus any no longer listed. */ function loadSelection(projectId: string, shots: PlaylistShot[]): Set { try { const ids: unknown = JSON.parse(localStorage.getItem(selectionKey(projectId)) ?? "[]"); if (!Array.isArray(ids)) return new Set(); const listed = new Set(shots.map((s) => s.id)); return new Set(ids.filter((id): id is string => typeof id === "string" && listed.has(id))); } catch { return new Set(); } } function saveSelection(projectId: string, selected: Set) { try { localStorage.setItem(selectionKey(projectId), JSON.stringify([...selected])); } catch { // Storage unavailable: the selection just isn't remembered. } }