"use client"; import { useState, useTransition, useCallback, useEffect, useRef } from "react"; import { useRouter } from "next/navigation"; import Image from "next/image"; import Link from "next/link"; import { useScrollMemory } from "@/hooks/use-scroll-memory"; import { Select, SelectContent, SelectItem, SelectSeparator, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, } from "@/components/ui/dialog"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { cn, getInitials } from "@/lib/utils"; import { updateShotNotes, bulkUpdateDueDates, bulkAssignArtist, bulkDeleteShots, toggleKeyShot, toggleScaledShot } from "@/actions/shots"; import { previewMovReview, buildMovReview } from "@/actions/deliveries"; import { useToast } from "@/components/ui/use-toast"; import { Film, Clock, CheckCircle2, AlertCircle, Calendar, CalendarDays, ChevronDown, ChevronRight, Loader2, X, ShieldCheck, Eye, Star, Trash2, ChevronsUpDown, Clapperboard, Scaling, UserPlus, } from "lucide-react"; import { format } from "date-fns"; import { shotThumbnail } from "@/lib/shot-thumbnail"; type ShotRow = { id: string; shotCode: string; scene: string; episode: string | null; shotNumber: number; status: string; priority: string; dueDate: Date | string | null; thumbnailUrl: string | null; generatedThumbnailUrl: string | null; notes: string | null; description: string | null; isKeyShot: boolean; isScaled: boolean; shotVersion: string | null; artist: { id: string; name: string | null; image: string | null; email: string } | null; shotGroup: { id: string; name: string } | null; }; interface Artist { id: string; name: string | null; email: string; image: string | null; } interface Project { id: string; name: string; code: string; projectType: string; } interface ShotStatusClientProps { projects: Project[]; selectedProjectId: string | null; selectedProject: Project | null; shots: ShotRow[]; episodeDueDates: { episode: string; dueDate: Date | string }[]; artists: Artist[]; canManage: boolean; } function readStored(key: string): string | null { try { return localStorage.getItem(key); } catch { return null; } } /** A saved list of open sections, or null when none was saved (or it is unreadable). */ function readStoredList(key: string): string[] | null { const raw = readStored(key); if (!raw) return null; try { const parsed = JSON.parse(raw); return Array.isArray(parsed) ? parsed.filter((v): v is string => typeof v === "string") : null; } catch { return null; } } const STATUS_CONFIG: Record = { WAITING: { label: "Waiting", color: "bg-zinc-500/10 text-zinc-400 border-zinc-500/20", icon: Clock }, IN_PROGRESS: { label: "In Progress", color: "bg-blue-500/10 text-blue-400 border-blue-500/20", icon: Film }, INTERNAL_REVIEW: { label: "Internal Review", color: "bg-purple-500/10 text-purple-400 border-purple-500/20", icon: AlertCircle }, READY_FOR_CLIENT: { label: "Ready for Client", color: "bg-sky-500/10 text-sky-400 border-sky-500/20", icon: ShieldCheck }, CLIENT_REVIEW: { label: "Client Review", color: "bg-indigo-500/10 text-indigo-400 border-indigo-500/20", icon: Eye }, REVISIONS: { label: "Revisions", color: "bg-orange-500/10 text-orange-400 border-orange-500/20", icon: AlertCircle }, COMPLETE: { label: "Complete", color: "bg-emerald-500/10 text-emerald-400 border-emerald-500/20", icon: CheckCircle2 }, }; // ── IndeterminateCheckbox ────────────────────────────────────────────────────── function IndeterminateCheckbox({ checked, indeterminate, onChange, className, }: { checked: boolean; indeterminate?: boolean; onChange: (e: React.ChangeEvent) => void; className?: string; }) { const ref = useRef(null); useEffect(() => { if (ref.current) ref.current.indeterminate = !!indeterminate; }, [indeterminate]); return ( ); } // ── BulkDueDateDialog ───────────────────────────────────────────────────────── function BulkDueDateDialog({ open, onClose, onApply, count, }: { open: boolean; onClose: () => void; onApply: (date: string, includeTasks: boolean) => Promise; count: number; }) { const [date, setDate] = useState(""); const [includeTasks, setIncludeTasks] = useState(false); const [isPending, startTransition] = useTransition(); useEffect(() => { if (open) { setDate(""); setIncludeTasks(false); } }, [open]); const handleApply = () => { if (!date) return; startTransition(async () => { await onApply(date, includeTasks); }); }; return ( { if (!o && !isPending) onClose(); }}> Change Due Date

Applying to {count}{" "} shot{count !== 1 ? "s" : ""}

setDate(e.target.value)} className="w-full rounded-md border border-zinc-700 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 [color-scheme:dark] focus:border-zinc-500 focus:outline-none focus:ring-1 focus:ring-zinc-500" />
); } // ── BulkAssignArtistDialog ──────────────────────────────────────────────────── const UNASSIGN = "__unassign__"; /** * Hand a selection of shots to one artist, or clear the assignment. * * Unassigning is offered as an explicit choice rather than a separate menu * entry — reassignment and hand-back are the same production move, and the * confirm button changes wording so nobody clears a batch by accident. */ function BulkAssignArtistDialog({ open, onClose, onApply, artists, count, }: { open: boolean; onClose: () => void; onApply: (artistId: string | null) => Promise; artists: Artist[]; count: number; }) { const [value, setValue] = useState(""); const [isPending, startTransition] = useTransition(); useEffect(() => { if (open) setValue(""); }, [open]); const handleApply = () => { if (!value) return; startTransition(async () => { await onApply(value === UNASSIGN ? null : value); }); }; const unassigning = value === UNASSIGN; return ( { if (!o && !isPending) onClose(); }}> Assign Artist

Applying to {count}{" "} shot{count !== 1 ? "s" : ""}

This replaces whoever is currently on {count === 1 ? "the shot" : "these shots"}.

); } function BulkDeleteDialog({ open, onClose, onConfirm, count, }: { open: boolean; onClose: () => void; onConfirm: () => Promise; count: number; }) { const [isPending, startTransition] = useTransition(); const handleConfirm = () => { startTransition(async () => { await onConfirm(); }); }; return ( { if (!o && !isPending) onClose(); }}> Delete {count} shot{count !== 1 ? "s" : ""}?

This will permanently delete {count}{" "} shot{count !== 1 ? "s" : ""}, including all tasks, versions, footage, and annotations. This cannot be undone.

A shot with renders or deliveries already on record is protected and will be skipped rather than deleted — you'll see which ones and why.

); } // ── MovReviewDialog ─────────────────────────────────────────────────────────── type ReviewPreview = Awaited>; /** * Confirm what a MOV review package would contain before building it * (RenderPipeline2 §11.6). * * The version each shot resolves to is the newest one that actually has a * preview MOV, which is not always the newest one full stop — so the dialog * names the version per shot rather than making anyone guess, and lists the * shots with no MOV at all instead of quietly building a smaller folder. */ function MovReviewDialog({ open, onClose, onBuilt, shotIds, }: { open: boolean; onClose: () => void; onBuilt: () => void; shotIds: string[]; }) { const { toast } = useToast(); const [preview, setPreview] = useState(null); const [loading, setLoading] = useState(false); const [isPending, startTransition] = useTransition(); useEffect(() => { if (!open) { setPreview(null); return; } let cancelled = false; setLoading(true); previewMovReview(shotIds) .then((result) => { if (!cancelled) setPreview(result); }) .finally(() => { if (!cancelled) setLoading(false); }); return () => { cancelled = true; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [open]); const ready = preview?.ok ? preview.candidates : []; const skipped = preview?.ok ? preview.skipped : []; const handleBuild = () => { startTransition(async () => { const result = await buildMovReview(shotIds); if (!result.ok) { toast({ title: "Could not build review package", description: result.error, variant: "destructive" }); return; } toast({ title: `${result.package.name} queued`, description: `${result.package.itemCount} MOV${result.package.itemCount !== 1 ? "s" : ""} → ${result.package.rootPath}`, }); onBuilt(); }); }; return ( { if (!o && !isPending) onClose(); }}> Build MOV review package {loading && (

Working out what each shot would contribute…

)} {!loading && preview && !preview.ok && (

{preview.error}

)} {!loading && preview?.ok && (
Folder
{preview.packageName}
{preview.packageDir}
{ready.length > 0 && (
{ready.length} MOV{ready.length !== 1 ? "s" : ""}
{ready.map((c) => (
{c.shotCode} {c.versionString} {c.deliveredName}
))}
)} {skipped.length > 0 && (
{skipped.length} shot{skipped.length !== 1 ? "s" : ""} left out
{skipped.map((sk) => (
{sk.shotCode} {sk.reason}
))}
)}

A render machine builds the folder. Nothing about these shots changes — a review is not a delivery, so the versions stay exactly where they are in the pipeline.

)}
); } // ── NotesCell ───────────────────────────────────────────────────────────────── function NotesCell({ shot, canManage, }: { shot: ShotRow; canManage: boolean; }) { const [value, setValue] = useState(shot.notes ?? ""); const [saved, setSaved] = useState(true); const [isPending, startTransition] = useTransition(); const { toast } = useToast(); const handleBlur = useCallback(() => { if (value === (shot.notes ?? "")) return; startTransition(async () => { try { await updateShotNotes(shot.id, value); setSaved(true); toast({ title: "Notes saved" }); } catch { toast({ title: "Failed to save notes", variant: "destructive" }); } }); }, [value, shot.id, shot.notes, toast]); if (!canManage) { return ( {shot.notes ?? —} ); } return (