"use client"; import { useState, useEffect, useRef, useCallback } from "react"; import Link from "next/link"; import Image from "next/image"; import { ReviewPlayer, type ReviewPlayerRef } from "@/components/player/ReviewPlayer"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, } from "@/components/ui/dialog"; import { Avatar, AvatarFallback } from "@/components/ui/avatar"; import { ScrollArea } from "@/components/ui/scroll-area"; import { useToast } from "@/components/ui/use-toast"; import { cn, frameToTimecode, getInitials } from "@/lib/utils"; import { Film, ArrowLeft, CheckCircle2, XCircle, AlertCircle, MessageSquare, Send, Clock, ChevronLeft, ChevronRight, ChevronDown, ChevronUp, Copy, Check, Download, Pencil, Trash2, } from "lucide-react"; import { useReviewStore } from "@/hooks/use-review-player"; import { ReviewPasswordGate } from "@/components/clients/ReviewPasswordGate"; import { HandleBadge } from "@/components/player/HandleBadge"; interface Comment { id: string; frameNumber: number; timestamp: number; text: string; isResolved: boolean; createdAt: string; /** This reviewer wrote it, so they can change or remove it. Set by the API. */ canEdit?: boolean; author: { id: string; name: string | null; image: string | null; email: string }; replies: { id: string; text: string; createdAt: string; author: { name: string | null } }[]; } interface Version { id: string; versionNumber: number; fileUrl: string; fps: number; duration: number | null; frameCount?: number | null; /** High quality review MP4 — the player's quality switch. */ hqFileUrl?: string | null; /** Where the High Res download comes from: this version's ProRes, or the shot's legacy file. */ highResSource?: "version" | "shot" | null; handleHead?: number | null; handleTail?: number | null; pictureStartFrame?: number | null; approvalStatus: string; notes: string | null; // Top-level high-res flags (normalised from either shot or task.shot) hasHighRes?: boolean; highResShotId?: string | null; highResFilename?: string | null; shot?: { id: string; shotCode: string; hasHighRes?: boolean; highResFilename?: string | null; project: { id: string; name: string; code: string }; } | null; task?: { id: string; title: string; type: string; project: { id: string; name: string; code: string }; shot?: { id: string; shotCode: string } | null; asset?: { assetCode: string; name: string } | null; } | null; } const APPROVAL_STATUS_STYLES: 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 QUEUE_KEY = 'client-portal-queue'; export default function ClientReviewPage({ params, }: { params: Promise<{ token: string; versionId: string }>; }) { const [token, setToken] = useState(""); const [version, setVersion] = useState(null); const [comments, setComments] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [requiresPassword, setRequiresPassword] = useState(false); const [versionId, setVersionId] = useState(""); const currentFrame = useReviewStore((s) => s.currentFrame); // Comment form state const [commentText, setCommentText] = useState(""); const [commentFrame, setCommentFrame] = useState(null); const [submittingComment, setSubmittingComment] = useState(false); // Editing / deleting one's own notes const [editingCommentId, setEditingCommentId] = useState(null); const [editingText, setEditingText] = useState(""); const [savingEdit, setSavingEdit] = useState(false); const [deletingComment, setDeletingComment] = useState(null); const [deleting, setDeleting] = useState(false); // Approval dialog const [approvalDialog, setApprovalDialog] = useState<{ open: boolean; status: "APPROVED" | "REJECTED" | "NEEDS_CHANGES" | null; }>({ open: false, status: null }); const [approvalNotes, setApprovalNotes] = useState(""); const [submittingApproval, setSubmittingApproval] = useState(false); const [currentApprovalStatus, setCurrentApprovalStatus] = useState("PENDING_REVIEW"); const [nextReview, setNextReview] = useState<{ versionId: string; label: string } | null>(null); const [prevReview, setPrevReview] = useState<{ versionId: string; label: string } | null>(null); const [copiedTaskName, setCopiedTaskName] = useState(false); const [downloadingHighRes, setDownloadingHighRes] = useState(false); const [commentsOpen, setCommentsOpen] = useState(true); const playerRef = useRef(null); const { toast } = useToast(); useEffect(() => { params.then(({ token: t, versionId: vId }) => { setToken(t); setVersionId(vId); loadVersion(t, vId); }); }, [params]); useEffect(() => { if (!versionId) return; try { const queueJson = sessionStorage.getItem(QUEUE_KEY); if (!queueJson) { setNextReview(null); setPrevReview(null); return; } const queue: Array<{ versionId: string; label: string }> = JSON.parse(queueJson); const idx = queue.findIndex((item) => item.versionId === versionId); setNextReview(idx >= 0 && idx < queue.length - 1 ? queue[idx + 1] : null); setPrevReview(idx > 0 ? queue[idx - 1] : null); } catch { setNextReview(null); setPrevReview(null); } }, [versionId]); const loadVersion = (t: string, vId: string) => { setLoading(true); setError(null); fetch(`/api/client/${t}/versions/${vId}`) .then(async (r) => { if (r.status === 401) { const data = await r.json().catch(() => ({})); if (data.requiresPassword) { setRequiresPassword(true); return null; } } if (!r.ok) throw new Error("Invalid or expired review link"); return r.json(); }) .then((data) => { if (!data) return; setVersion(data.version); setComments(data.comments); setCurrentApprovalStatus(data.version.approvalStatus); setRequiresPassword(false); }) .catch((e) => setError(e.message)) .finally(() => setLoading(false)); }; const refreshComments = useCallback(async (t: string, vId: string) => { const res = await fetch(`/api/client/${t}/versions/${vId}`); if (res.ok) { const data = await res.json(); setComments(data.comments); } }, []); const handlePlayerAddComment = useCallback((frameNumber: number, _timestamp: number) => { playerRef.current?.pause(); setCommentFrame(frameNumber); }, []); const handleSubmitComment = async () => { if (!commentText.trim() || commentFrame === null || !version) return; setSubmittingComment(true); try { const res = await fetch(`/api/client/${token}/comment`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ versionId: version.id, frameNumber: commentFrame, timestamp: commentFrame / version.fps, text: commentText.trim(), }), }); if (!res.ok) throw new Error("Failed to post comment"); setCommentText(""); setCommentFrame(null); await refreshComments(token, version.id); toast({ title: "Comment added" }); } catch { toast({ title: "Failed to add comment", variant: "destructive" }); } finally { setSubmittingComment(false); } }; const beginEditComment = (comment: Comment) => { setEditingCommentId(comment.id); setEditingText(comment.text); }; const cancelEditComment = () => { setEditingCommentId(null); setEditingText(""); }; const handleSaveEditedComment = async () => { const trimmed = editingText.trim(); if (!editingCommentId || !trimmed || !version) return; setSavingEdit(true); try { const res = await fetch(`/api/client/${token}/comment/${editingCommentId}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text: trimmed }), }); if (!res.ok) throw new Error("Failed to save note"); cancelEditComment(); await refreshComments(token, version.id); toast({ title: "Note updated" }); } catch { toast({ title: "Failed to update note", variant: "destructive" }); } finally { setSavingEdit(false); } }; const handleDeleteComment = async () => { if (!deletingComment || !version) return; setDeleting(true); try { const res = await fetch(`/api/client/${token}/comment/${deletingComment.id}`, { method: "DELETE", }); if (!res.ok) throw new Error("Failed to delete note"); setDeletingComment(null); // Deleting a drawing note also removes its strokes server-side, and those // live in the canvas's own state — a full reload remounts the player so // the frame does not keep showing marks that no longer exist. loadVersion(token, version.id); toast({ title: "Note deleted" }); } catch { toast({ title: "Failed to delete note", variant: "destructive" }); } finally { setDeleting(false); } }; const handleDownloadHighRes = async () => { const shotId = version?.highResShotId ?? version?.shot?.id; if (!version || !token) return; const endpoint = version.highResSource === "version" ? `/api/client/${token}/versions/${version.id}/highres/download` : shotId ? `/api/client/${token}/shots/${shotId}/highres/download` : null; if (!endpoint) return; setDownloadingHighRes(true); try { const res = await fetch(endpoint); if (!res.ok) throw new Error("Could not get download link"); const { url } = await res.json(); // Open the presigned URL — the Content-Disposition header forces a download window.open(url, "_blank", "noopener,noreferrer"); } catch { toast({ title: "Download failed", variant: "destructive" }); } finally { setDownloadingHighRes(false); } }; const handleSubmitApproval = async () => { if (!approvalDialog.status || !version) return; setSubmittingApproval(true); try { const res = await fetch(`/api/client/${token}/approve`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ versionId: version.id, status: approvalDialog.status, notes: approvalNotes, }), }); if (!res.ok) throw new Error("Failed to submit decision"); setCurrentApprovalStatus(approvalDialog.status); setApprovalDialog({ open: false, status: null }); setApprovalNotes(""); toast({ title: approvalDialog.status === "APPROVED" ? "Shot approved!" : approvalDialog.status === "REJECTED" ? "Version rejected" : "Changes requested", description: approvalDialog.status === "APPROVED" ? "The shot has been marked as client approved." : undefined, }); } catch { toast({ title: "Failed to submit decision", variant: "destructive" }); } finally { setSubmittingApproval(false); } }; if (loading) { return (
); } if (requiresPassword) { return ( loadVersion(token, versionId)} /> ); } if (error || !version) { return (

Version unavailable

{error}

); } const approvalStyle = APPROVAL_STATUS_STYLES[currentApprovalStatus] ?? ""; return (
{/* Header */} {/* Phones: back + shot + prev/next on the first row, status and decision buttons on a second full-width row. From md: the three-column grid. */}
{/* Left: back + shot path */}
All Shots
Logo
{(() => { const project = version.shot?.project ?? version.task?.project; const contextCode = version.shot?.shotCode ?? version.task?.shot?.shotCode ?? version.task?.asset?.assetCode ?? null; const taskName = version.task?.title ?? null; return ( <> {project?.code} / {contextCode && ( {contextCode} )} {taskName && ( <> / {taskName} )} ); })()}
{/* Center: status badge + decision buttons (their own row on phones) */}
{currentApprovalStatus === "PENDING_REVIEW" ? ( ) : currentApprovalStatus === "APPROVED" ? ( ) : currentApprovalStatus === "NEEDS_CHANGES" ? ( ) : ( )} {currentApprovalStatus.replace(/_/g, " ")} {(version.hasHighRes || version.shot?.hasHighRes) && ( )}
{/* Right: Prev / Next navigation */}
{prevReview ? ( Prev {prevReview.label} ) : ( )} {(prevReview || nextReview) &&
} {nextReview ? ( {nextReview.label} Next ) : ( )}
{/* Main: player + comments — stacked on mobile, side-by-side on md+ */}
{/* Player */}
{ const res = await fetch(`/api/client/${token}/annotation`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data), }); if (!res.ok) throw new Error("Failed to save annotation"); }} addCommentFn={async (data) => { const res = await fetch(`/api/client/${token}/comment`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data), }); if (!res.ok) throw new Error("Failed to post comment"); await refreshComments(token, version.id); }} />
{/* Comment panel — collapsible */}
{/* Collapse toggle */} {commentsOpen && (

Notes

{comments.length > 0 && ( ({comments.length}) )}
)} {commentsOpen && {comments.length === 0 ? (

No notes yet.

Pause the video and add a note at any frame.

) : (
{comments.map((comment) => (
{editingCommentId === comment.id ? ( // Editing replaces the note in place, so it stays in the // list at its own frame rather than jumping to a dialog.
Editing note {frameToTimecode(comment.frameNumber, version.fps)}