"use client"; import { useCallback, useEffect, useImperativeHandle, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { REJECT_REASONS, rejectPatch, rejectReasonOf } from "@/lib/report/rejectReasons.mjs"; import { cn } from "@/lib/utils"; import { announceManifestChanged, refusalOf, timelineOp } from "../timelineApi"; // --------------------------------------------------------------------------- // REJECT ▾: the walk's "this clip comes out", with the reason it comes out // (operator, 2026-10-30: "non-matching being one reason among others"). // lib/report/rejectReasons.mjs is the vocabulary: doesn't match and wrong // speaker are FACT errors (verdict incorrect, a correction for the report); // irrelevant, repeats, weak, privacy and other are CUT reasons (verdict // rejected -- the report is right, the clip just does not belong here). // // `x` (when `hotkey`) opens the reasons, a digit picks one; Wrong speaker // keeps its one-click button (the same flow, its reason preset). Asked in the // page, never window.confirm: the reason, a note (required for doesn't match // and other), then // Remove one structural write (POST /api/report/timeline // `reject`, manifest.mjs rejectClip): marked, taken out // of the cut, on record in removed.json; Undo is the // structural undo (the clip back where it was). // Reject, keep in place the verdict only (the clip writer), for removal // later; Undo writes the verdict back as it was. // A take's walk (`take`) only keeps in place: a take's timeline is a patch. // --------------------------------------------------------------------------- export type RejectClipTarget = { id: string; video?: string | null; channel?: string | null; start?: number | null; end?: number | null; /** The verdict fields as they are now: prefill the note, and what a keep-in-place Undo writes back. */ verdict?: string | null; reason?: string | null; correction?: string | null; rejectNote?: string | null; }; /** * The page's handle on the reasons: `open` them (its own `x`), and whether they * are up (`isOpen`) -- while they are, Escape is theirs to close, so a page's * own Escape (the bench's: drop the gap selection) leaves it alone. The Escape * that closes them is preventDefault()ed, so a page listener that runs after * this one (by then `isOpen` is already false) can tell it was taken. */ export type RejectClipControl = { open: () => void; isOpen: () => boolean }; type Patch = Record; type Phase = | { k: "idle" } | { k: "menu" } | { k: "asking"; reason: string } | { k: "busy"; reason: string; removing: boolean } | { k: "removed"; reason: string; notes: string[] } | { k: "kept"; reason: string; prev: Patch } | { k: "undone"; what: "removed" | "kept" }; const secs = (n: number | null | undefined) => (typeof n === "number" && Number.isFinite(n) ? `${n.toFixed(2)} s` : "?"); const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']"; /** The clip writer's default: the clip's token, then PUT /api/report/window (a take's patch with `take`). */ async function writeClip(project: string, clip: string, take: string | null, patch: Patch): Promise { const tq = take ? `&take=${encodeURIComponent(take)}` : ""; const r = await fetch(`/api/report/clip?project=${encodeURIComponent(project)}&clip=${encodeURIComponent(clip)}${tq}`, { cache: "no-store" }); if (!r.ok) return `could not read ${clip}: HTTP ${r.status}`; const token = ((await r.json()) as { token?: string }).token ?? null; const w = await fetch("/api/report/window", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, clip, ...(take ? { take } : {}), token, ...patch }), }); if (w.ok) return null; const j = (await w.json().catch(() => ({}))) as { error?: string; stale?: boolean }; return j.stale ? "the manifest changed since — reload and try again" : String(j.error ?? `HTTP ${w.status}`); } export default function RejectClip({ project, clip, take = null, hotkey = false, initialOpen = false, control, write, onRemoved, onUndone, onKept, after, className, }: { project: string; /** The clip on screen; null (a card, nothing) shows only a removal still to undo. */ clip: RejectClipTarget | null; /** A take's walk: the verdict goes into the take's patch, and nothing is removed. */ take?: string | null; /** `x` opens the reasons, a digit picks one, Escape closes. "digits": the page's own `x` opens them (control). */ hotkey?: boolean | "digits"; /** Arrive with the reasons open (the phone's sheet). */ initialOpen?: boolean; /** For a page's own button (the verdict bar's) to open the reasons. */ control?: React.Ref; /** The page's own clip writer (the bench's save: its token, its state); resolves true when it landed. */ write?: (patch: Patch) => Promise; /** After the removal landed (the page re-reads what it plays). */ onRemoved?: (id: string) => void; /** After an undo landed (a removal's or a keep's). */ onUndone?: (id: string) => void; /** After a keep-in-place landed. */ onKept?: (id: string) => void; /** What follows the "removed" line (the bench's Next clip link). */ after?: React.ReactNode; className?: string; }) { const [phase, setPhase] = useState(() => (initialOpen && clip ? { k: "menu" } : { k: "idle" })); const [note, setNote] = useState(""); const [error, setError] = useState(null); const [doneId, setDoneId] = useState(null); const noteBox = useRef(null); const root = useRef(null); // A different clip on screen: whatever was being asked about the last one is dropped // (a removal or a keep stays, with its Undo). const clipId = clip?.id ?? null; const lastClip = useRef(clipId); useEffect(() => { if (lastClip.current === clipId) return; lastClip.current = clipId; setPhase((p) => (p.k === "menu" || p.k === "asking" ? { k: "idle" } : p)); setError(null); }, [clipId]); const open = useCallback(() => { if (!clip) return; setError(null); // A new rejection supersedes the last one's Undo line. setDoneId(null); setPhase({ k: "menu" }); root.current?.scrollIntoView?.({ block: "nearest" }); }, [clip]); useImperativeHandle( control, () => ({ open, isOpen: () => phaseRef.current.k === "menu" || phaseRef.current.k === "asking" }), [open], ); const pick = useCallback( (reason: string) => { if (!clip) return; const r = rejectReasonOf(reason); // A fact reason's note is the correction; prefill what is already written. setNote(r?.fact ? (clip.correction ?? "") : clip.verdict === "rejected" && clip.reason === reason ? (clip.rejectNote ?? "") : ""); setError(null); setDoneId(null); setPhase({ k: "asking", reason }); }, [clip], ); useEffect(() => { if (phase.k === "asking") noteBox.current?.focus(); }, [phase]); const remove = async (reason: string) => { if (!clip) return; setPhase({ k: "busy", reason, removing: true }); setError(null); const res = await timelineOp(project, null, "reject", { id: clip.id, reason, ...(note.trim() ? { note: note.trim() } : {}) }); if (!res.ok) { setError(refusalOf(res)); setPhase({ k: "asking", reason }); return; } setDoneId(clip.id); setNote(""); setPhase({ k: "removed", reason, notes: Array.isArray(res.json.reanchored) ? (res.json.reanchored as string[]) : [] }); announceManifestChanged(project); onRemoved?.(clip.id); }; const patchClip = async (id: string, patch: Patch): Promise => { if (write) return (await write(patch)) ? null : "not saved"; const err = await writeClip(project, id, take, patch); if (!err) announceManifestChanged(project); return err; }; const keep = async (reason: string) => { if (!clip) return; let patch: Patch; try { patch = rejectPatch(reason, note); } catch (e) { setError(e instanceof Error ? e.message : String(e)); return; } // What a keep's Undo writes back: the verdict fields as they were. const prev: Patch = { verdict: clip.verdict ?? "", reason: clip.reason ?? "", rejectNote: clip.rejectNote ?? "", correction: clip.correction ?? "" }; setPhase({ k: "busy", reason, removing: false }); setError(null); const err = await patchClip(clip.id, patch); if (err) { setError(err); setPhase({ k: "asking", reason }); return; } setDoneId(clip.id); setNote(""); setPhase({ k: "kept", reason, prev }); onKept?.(clip.id); }; const undo = async () => { const id = doneId ?? clip?.id ?? ""; const was = phase; if (was.k !== "removed" && was.k !== "kept") return; setPhase({ k: "busy", reason: was.reason, removing: was.k === "removed" }); setError(null); if (was.k === "removed") { const res = await timelineOp(project, null, "undo"); if (!res.ok) { setError(refusalOf(res)); setPhase(was); return; } announceManifestChanged(project); } else { // The previous verdict's own fields only: a rejectNote goes with `rejected` alone. const back: Patch = { ...was.prev }; if (back.verdict !== "rejected") delete back.rejectNote; const err = await patchClip(id, back); if (err) { setError(`could not undo: ${err}`); setPhase(was); return; } } setDoneId(null); setPhase({ k: "undone", what: was.k }); onUndone?.(id); }; // ---- the keys: x opens, a digit picks, Escape closes ---- const phaseRef = useRef(phase); phaseRef.current = phase; useEffect(() => { if (!hotkey) return; const onKey = (ev: KeyboardEvent) => { const tgt = ev.target as HTMLElement | null; if (ev.metaKey || ev.ctrlKey || ev.altKey) return; const p = phaseRef.current; if (ev.key === "Escape" && (p.k === "menu" || p.k === "asking")) { setPhase({ k: "idle" }); ev.preventDefault(); return; } if (tgt?.closest(TYPING)) return; if (hotkey === true && (ev.key === "x" || ev.key === "X") && clip && p.k !== "busy") { if (p.k === "menu") setPhase({ k: "idle" }); else open(); ev.preventDefault(); ev.stopImmediatePropagation(); return; } if (p.k === "menu" && /^[1-9]$/.test(ev.key)) { const r = REJECT_REASONS[Number(ev.key) - 1]; if (!r) return; pick(r.id); ev.preventDefault(); ev.stopImmediatePropagation(); } }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [hotkey, clip, open, pick]); const shown = doneId ?? clip?.id ?? ""; const asking = phase.k === "asking" || (phase.k === "busy" && !doneId) ? phase.reason : null; const r = asking ? rejectReasonOf(asking) : null; const doneReason = phase.k === "removed" || phase.k === "kept" || (phase.k === "busy" && doneId) ? rejectReasonOf(phase.reason) : null; if (!clip && !doneId && phase.k !== "undone") return null; const needNote = r?.note === "required" && !note.trim(); return (
{(phase.k === "idle" || phase.k === "undone" || phase.k === "menu") && (
{clip && ( )} {clip && ( )} {phase.k === "undone" && ( {phase.what === "removed" ? "Undone: the clip is back in the cut." : "Undone: the verdict is as it was."} )}
)} {clip && phase.k === "menu" && (
{REJECT_REASONS.map((x, i) => ( ))}
)} {clip && asking && r && (

Reject {clip.id} {clip.video ? ( <> {" "} ({clip.channel ? `${clip.channel}/` : ""} {clip.video} {secs(clip.start)}–{secs(clip.end)}) ) : null}{" "} as {r.label}?{" "} {r.fact ? `${r.hint}: marked incorrect, read by the next report pass.` : `${r.hint[0].toUpperCase()}${r.hint.slice(1)} — the report is right; nothing here is a correction.`}

setNote(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter" && !needNote) { e.preventDefault(); void (take ? keep(asking) : remove(asking)); } }} placeholder={r.placeholder} aria-label={r.fact ? `what the report got wrong (${r.label})` : `why it comes out (${r.label})`} maxLength={300} className={cn( "w-full rounded border bg-ground px-1.5 py-1 text-[12px] text-text outline-none focus:border-signal", needNote ? "border-[var(--color-dirty)]" : "border-seam-2", )} />
{!take && ( )}
)} {doneId && doneReason && (phase.k === "removed" || phase.k === "kept" || phase.k === "busy") && (
{phase.k === "kept" || (phase.k === "busy" && !phase.removing) ? ( <> Rejected {shown} ({doneReason.label}), still in the cut. ) : ( <> Removed {shown} from the cut ({doneReason.label}). )} {after}
{phase.k === "removed" && phase.notes.length > 0 && (
    {phase.notes.map((n) => (
  • {n}
  • ))}
)}
)} {error && (

{error}

)}
); }