"use client";
import { useMemo, useRef, useState } from "react";
import { SCREEN_KINDS, lineOfText, screenFromRead, screenReadLines, screenWarnings, shapeSpans, validateScreens, withoutLines } from "umtool-report-to-video/post-screens";
import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration";
import { ownPictureOnly } from "umtool-report-to-video/post-item";
import { lineTakeWarnings, lineTakesOf, partRoles, threadReadErrors } from "umtool-report-to-video/post-thread";
import { postFileUrl } from "./review/PostItemPlayer";
import { ScreenLineVoice, lineReadings, useScreenVoice, type LineTakeOption, type ScreenVoice, type VoiceEntry } from "./ScreenLineVoice";
// ---------------------------------------------------------------------------
// A POST's SCREENS ON THE BENCH (report-to-video/post-screens.mjs; docs/report-video.md, "Screens"; operator, 12 Nov:
// "The 'read text screenshots as posts' ability in different variations should be first class"): the text screenshots
// the post carries -- each the attachment it is in (and, in a video, the seconds it is visible), what it is (DMs, an
// email, a post, text), its lines transcribed by hand (pasted as `who: words | time`), who says each and on which side,
// which lines are read (a line's excerpt trimmed to the words read), and whether a person checked the transcription.
// No model: everything here is typed. The bench's Save writes it (updatePostItem's `screens`); the read is made with
// `umtool posts screen
read` (the line shown here, and its button). A read line may be RECORDED in the
// operator's voice (ScreenLineVoice: `posts screen … record`) and that take CHOSEN for it (`lineTakes`).
// ---------------------------------------------------------------------------
type Line = { who?: string; side?: "left" | "right"; text: string; time?: string; redact?: true };
type Read = "all" | "none" | Array<{ line: number; text?: string }>;
type Screen = { id: string; media: number; at?: [number, number]; kind: string; title?: string; source?: string; checked?: { by: string; at: string }; ref?: string; unread?: "omit" | "dim"; lines: Line[]; read: Read; saidAs?: Record; lineTakes?: Record };
type LineRecs = Array<{ role: string; screen: string; n: number; takes: Array<{ n: number; id: string; take: { steps?: Array<{ op: string; voice?: string }>; engine?: string; screenLine?: { heard?: unknown } }; current: boolean; chosen: boolean }> }>;
/** A recording's step as the select says it: recorded, cleaned, converted to its voice. */
const stepOf = (t: { steps?: Array<{ op: string; voice?: string }>; engine?: string }) => {
const st = t.steps?.[0];
return st?.op === "convert" ? `converted to ${String(st.voice ?? "a stock voice").split(":").pop()}` : st?.op === "enhance" ? "cleaned" : "recorded";
};
type Media = { src: string; kind: string; seconds?: number };
type Entry = Record & { id: string; media?: Media[]; screens?: Screen[] };
const r2 = (v: number) => Math.round(v * 100) / 100;
/** The read as a list of `{ line, text? }` (all: every line not redacted; none: none). */
const readList = (sc: Screen): Array<{ line: number; text?: string }> => (sc.read === "all" ? sc.lines.map((l, i) => (l.redact ? null : { line: i })).filter((x): x is { line: number } => !!x) : sc.read === "none" ? [] : sc.read);
export default function PostScreensPanel({ project, entry, saved, setEntry, onEntry }: { project: string; entry: Entry; saved: Entry; setEntry: (f: (e: Entry) => Entry) => void; onEntry: (e: Entry, token: string | null) => void }) {
const screens = useMemo(() => (Array.isArray(entry.screens) ? entry.screens : []), [entry.screens]);
// THE OPERATOR's VOICE for a line: one mic, one job; a line is recorded as SAVED (the draft differing: Save first).
const dirty = JSON.stringify(entry) !== JSON.stringify(saved);
const dirtyNow = useRef(dirty);
dirtyNow.current = dirty;
const voice = useScreenVoice({ project, id: entry.id, onEntry: onEntry as (e: VoiceEntry, t: string | null) => void, unsaved: () => dirtyNow.current });
const recs = useMemo(() => lineTakesOf(entry) as LineRecs, [entry]);
const lineWarnings = useMemo(() => lineTakeWarnings(entry) as string[], [entry]);
const media = Array.isArray(entry.media) ? entry.media : [];
const errors = useMemo(() => validateScreens(entry) as string[], [entry]);
// The build's guard on the read as it is (post-thread.mjs): a line edited, removed or moved under a read is refused
// until the read is made again -- Save keeps the screens; the build will not play the old read.
const refused = useMemo(() => (isNarrated(entry) ? (threadReadErrors(entry, {}) as string[]).filter((x) => /screen [a-z0-9-]+/.test(x)) : []), [entry]);
const warnings = useMemo(() => screenWarnings(entry, { narrated: isNarrated(entry), takeRoles: pickedTake(entry) ? (partRoles(entry) as Array<{ role: string | null }>).map((r) => r.role) : [] }) as string[], [entry]);
const [paste, setPaste] = useState>({});
const setScreens = (f: (list: Screen[]) => Screen[]) =>
setEntry((e) => {
const next = f(Array.isArray(e.screens) ? (e.screens as Screen[]) : []);
const out = { ...e };
if (next.length) out.screens = next;
else delete out.screens;
return out;
});
const setScreen = (id: string, f: (s: Screen) => Screen) => setScreens((list) => list.map((s) => (s.id === id ? f(s) : s)));
// Lines or words changed: the check was for the words before.
const setLines = (id: string, f: (lines: Line[]) => Line[]) => setScreen(id, (s) => {
const { checked: _c, ...rest } = s;
void _c;
return { ...rest, lines: f(s.lines) };
});
const nextId = () => {
const have = new Set(screens.map((s) => s.id));
let n = 1;
while (have.has(`s${n}`)) n += 1;
return `s${n}`;
};
// A PICTURE-ONLY post's read made its screen (post-screens.mjs screenFromRead: `posts screen … add --from-read`).
const pictureOnly = ownPictureOnly(entry) as boolean;
const script = typeof (entry.narration as { script?: unknown } | undefined)?.script === "string" ? String((entry.narration as { script: string }).script) : "";
const [fromReadError, setFromReadError] = useState(null);
const addFromRead = () => {
const made = screenFromRead(entry, { pictureOnly, id: nextId() }) as { screen?: Screen; error?: string };
setFromReadError(made.error ?? null);
if (made.screen) setScreens((list) => [...list, made.screen as Screen]);
};
const add = () => {
const m = media[0];
const sc: Screen = { id: nextId(), media: 0, kind: "dm", source: "transcribed", lines: [], read: "all", ...(m && (m.kind === "video" || m.kind === "gif") ? { at: [0, r2(Math.min(5, m.seconds ?? 5))] as [number, number] } : {}) };
setScreens((list) => [...list, sc]);
};
if (!media.length) return null;
return (
screens
text screenshots in its attachments, transcribed, drawn on the card and read after its words
{pictureOnly && script.trim() && (
)}
{
setLine(n, { redact: e.target.checked ? true : undefined });
// A redacted line is never read: its said-as goes with it (review 1, finding 7).
if (e.target.checked) setSaidAs(n, "");
}} data-post-screen-redact={n} aria-label={`redact line ${n}`} />