"use client"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { clipBenchHref, createHref, ingredientHref, playHref, projectHref } from "@/lib/hrefs"; import { researchCasePipelineHref, researchHref } from "@/lib/research/hrefs"; import type { CheckedStage, ClockStage, DownloadedStage, FoundStage, Ingredient, Pill, PublishedStage, RenderedStage, TranscribedStage, UsedStage, WindowsStage, } from "@/lib/ingredients"; // THE INGREDIENT RAIL (lane L5): one recording's nine stages across the top, the selected stage's panel below. // Each pill is ✓, a count, ! or —; each panel reads its stage's files (lib/ingredients/stages.mjs) and offers // its one action, which says what it costs and which queue it lands on before it runs. const GLYPH = (p: Pill) => (p.kind === "ok" ? "✓" : p.kind === "count" ? String(p.n ?? "") : p.kind === "warn" ? "!" : "—"); const PILL_CLASS: Record = { ok: "border-seam-2 text-kept", count: "border-seam-2 text-meter", warn: "border-doubt text-doubt", none: "border-seam text-muted-2", }; const hms = (sec: number | null | undefined) => { if (sec === null || sec === undefined || !Number.isFinite(sec)) return "?"; const t = Math.max(0, Math.floor(sec)); const h = Math.floor(t / 3600); const m = Math.floor((t % 3600) / 60); const s = String(t % 60).padStart(2, "0"); return h ? `${h}:${String(m).padStart(2, "0")}:${s}` : `${m}:${s}`; }; const span = (a: number | null | undefined, b: number | null | undefined) => `${hms(a)}–${hms(b)}`; const mb = (n: number | null | undefined) => (n === null || n === undefined ? "?" : n >= 1e9 ? `${(n / 1e9).toFixed(1)} GB` : `${(n / 1e6).toFixed(1)} MB`); const day = (iso: string | null | undefined) => (iso ? iso.slice(0, 16).replace("T", " ") : "—"); export default function IngredientRail({ data, initialStage, editorUrl }: { data: Ingredient; initialStage: string; editorUrl: string | null }) { const [sel, setSel] = useState(initialStage); const choose = (key: string) => { setSel(key); try { const u = new URL(window.location.href); u.searchParams.set("stage", key); window.history.replaceState(null, "", u.toString()); } catch { // The address is a convenience. } }; const [found, downloaded, transcribed, clock, windows, used, checked, rendered, published] = data.stages; const stage = data.stages.find((s) => s.key === sel) ?? data.stages[0]; const ingredient = { ch: data.ch, id: data.dirId }; return (
{data.ch}/{data.dirId} {data.siteId && ( archive id {data.siteId} )} {data.platform && {data.platform}} {data.duration !== null && {hms(data.duration)}} {data.uploadDate && {data.uploadDate.replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3")}} {data.webpageUrl && ( its page ↗ )} {editorUrl && data.exists && ( in the editor ↗ )} make a video from it
{data.notes.map((n) => (

{n}

))} {data.focus && (

Window {data.focus.name} {data.focus.found ? "" : " — no such window on disk"} · the stages after Windows show the clips it plays the whole recording

)}
    {data.stages.map((s, i) => (
  1. {i > 0 &&
  2. ))}

{stage.label}

{stage.line}

{stage.key === "found" && } {stage.key === "downloaded" && } {stage.key === "transcribed" && } {stage.key === "clock" && } {stage.key === "windows" && } {stage.key === "used" && } {stage.key === "checked" && } {stage.key === "rendered" && } {stage.key === "published" && }
); } // ── the action: plan, confirm, start ───────────────────────────────────────── type Plan = { action: string; what: string; cost: "network" | "gpu" | "disk" | null; queue: string; unreachable?: string; start: { route: string; body: Record } | null }; const COST: Record = { network: "costs network", gpu: "costs GPU", disk: "deletes a cached file" }; function Action({ label, body, testid }: { label: string; body: Record; testid: string }) { const router = useRouter(); const [plan, setPlan] = useState(null); const [busy, setBusy] = useState(false); const [result, setResult] = useState(null); const [error, setError] = useState(null); const post = async (route: string, b: Record) => { const res = await fetch(route, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(b) }); const j = await res.json().catch(() => ({})); if (!res.ok || j?.error) throw new Error(String(j?.error ?? `HTTP ${res.status}`)); return j; }; const ask = async () => { setBusy(true); setError(null); setResult(null); try { setPlan((await post("/api/ingredients/action", { ...body, step: "plan" })) as Plan); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); } }; const start = async () => { if (!plan?.start) return; setBusy(true); setError(null); try { const j = await post(plan.start.route, plan.start.body); setResult(String(j?.message ?? (j?.ok ? "done" : "started")) + (j?.fixed?.length ? ` — ${j.fixed.length} link(s) fixed` : "")); setPlan(null); router.refresh(); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); } }; return (
{plan && (

{plan.what}

{!plan.unreachable && (

{plan.cost && {COST[plan.cost]}} lands on {plan.queue}

)}
{plan.start && ( )}
)} {result && (

{result}

)} {error && (

{error}

)}
); } // ── the panels ─────────────────────────────────────────────────────────────── const Empty = ({ children }: { children: React.ReactNode }) =>

{children}

; const Rows = ({ children, ...p }: React.ComponentProps<"ul">) => (
    {children}
); const Facts = ({ rows }: { rows: [string, React.ReactNode][] }) => (
{rows.map(([k, v]) => (
{k}
{v}
))}
); function FoundPanel({ s, ch }: { s: FoundStage; ch: string }) { return (
{!s.findClips && !s.marks.length && !s.candidates.length && No search mark, case window or clip-finder run names it.} {s.findClips && (
  • The clip finder ({day(s.findClips.at)}): {s.findClips.segments} segment{s.findClips.segments === 1 ? "" : "s"} —{" "} {s.findClips.project}
  • )} {s.marks.map((m) => (
  • Research: {m.state} in “{m.query ?? m.session}” ({day(m.at)}) —{" "} open in Research
  • ))} {s.candidates.map((c) => (
  • Case {c.case}: window {span(c.from, c.to)} ({c.hits} hit{c.hits === 1 ? "" : "s"}) —{" "} its candidates
  • ))}
    Find in Research
    ); } function DownloadedPanel({ s, ingredient, platform }: { s: DownloadedStage; ingredient: { ch: string; id: string }; platform: string | null }) { return (

    Media

    {s.media.length ? ( {s.media.map((m) => (
  • {m.name} {mb(m.bytes)} {m.link ? (m.reachable ? " → media tier" : " → media tier, NOT ANSWERING") : ""}
  • ))}
    ) : ( No audio or source video in the video dir. )}
    ); } function TranscribedPanel({ s, ingredient, exists }: { s: TranscribedStage; ingredient: { ch: string; id: string }; exists: boolean }) { return (
    {exists && (
    )}
    ); } function ClockPanel({ s }: { s: ClockStage }) { if (!s.clock) return A Rumble recording gets one when its whole recording is saved and a window is cut from it.; return ( ); } function WindowsPanel({ s, ingredient, ch, id }: { s: WindowsStage; ingredient: { ch: string; id: string }; ch: string; id: string }) { const byProject = new Map(); for (const u of s.uncovered) byProject.set(u.project, [...(byProject.get(u.project) ?? []), u.clipId]); return (
    {s.windows.length === 0 && !s.uncovered.length && No windows cut yet.} {s.windows.length > 0 && ( {s.windows.map((w) => (
  • {span(w.from, w.to)} {mb(w.bytes)} {w.desynced && set aside: its picture runs off its sound} {w.sidecar && ( for {w.sidecar.clipId ?? "?"} ({w.sidecar.requestedBy ?? "?"}){w.sidecar.source ? `, from the ${w.sidecar.source}` : ""} {w.sidecar.clock ? `, through clock ${w.sidecar.clock.id}${w.sidecar.clock.certain ? "" : " (NOT certain)"}` : ""} {w.sidecar.syncOk === false ? ", sync NOT ok" : ""} )} {w.serves.length ? `cuts ${w.serves.map((x) => `${x.project.split("/").pop()} ${x.clipId}`).join(", ")}` : w.orphan ? "no project uses it now" : "cuts no clip"}
  • ))}
    )} {s.uncovered.length > 0 && (

    Not fetched: {s.uncovered.map((u) => `${u.project} ${u.clipId} (${span(u.from, u.to)})`).join(", ")}

    {[...byProject.entries()].map(([project, clips]) => ( ))}
    )}
    ); } function UsedPanel({ s }: { s: UsedStage }) { if (!s.rows.length) return No project cuts from it.; return ( {s.rows.map((r) => (
  • {r.project} {r.clipId} {span(r.start, r.end)} {r.cutStart !== null || r.cutEnd !== null ? ` (cut ${span(r.cutStart ?? r.start, r.cutEnd ?? r.end)})` : ""} {[r.inDraft ? "draft" : null, ...r.versions.map((v) => v.id)].filter(Boolean).join(", ")} {r.quote && “{r.quote}”}
  • ))}
    ); } function CheckedPanel({ s, ingredient }: { s: CheckedStage; ingredient: { ch: string; id: string } }) { if (!s.clips.length) return No clip uses it, so there is no quote to check.; const byProject = new Map(); for (const c of s.clips) if (c.hasQuote) byProject.set(c.project, [...(byProject.get(c.project) ?? []), c.clipId]); return (
    {s.clips.map((c) => (
  • {c.project} {c.clipId} {!c.hasQuote ? "no quote" : c.status ? `${c.status}${c.offset !== null && c.status !== "ok" ? ` (${c.offset > 0 ? "+" : ""}${c.offset.toFixed(1)} s)` : ""}${c.current ? "" : " — stale: the cut changed since"}` : "not checked"}
  • ))}
    {[...byProject.entries()].map(([project, clips]) => ( ))}
    ); } function RenderedPanel({ s }: { s: RenderedStage }) { if (!s.renders.length) return Not in any saved version yet.; return ( {s.renders.map((r) => (
  • {r.project} {r.clipId} {r.version ? `version ${r.version}${r.label ? ` (${r.label})` : ""}` : "the draft's segment"}: {r.state ?? "not rendered"} {r.seconds !== null ? `, ${hms(r.seconds)}` : ""} {r.cut ? `, cut ${span(r.cut.from, r.cut.to)}` : ""} play it at this clip
  • ))}
    ); } function PublishedPanel({ s, ingredient }: { s: PublishedStage; ingredient: { ch: string; id: string } }) { if (!s.links.length) return Not in any cut, so nothing links to it.; const projects = [...new Set(s.links.map((l) => l.project))]; return (
    {s.links.map((l) => (
  • {l.project} {l.clipId} {l.state ?? "never checked"} {l.url && ( {l.url} )} {l.fix && fix: {l.fix}}
  • ))}
    {projects.map((p) => ( ))} {projects .filter((p) => s.links.some((l) => l.project === p && l.state === "dead" && l.fix)) .map((p) => ( ))}
    ); }