Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

49.9 KB
Raw Blame
import { AlertTriangle, Crop, FolderOpen, FolderPlus, Pencil, Plus, Trash2, X } from "lucide-react";
import {
	type KeyboardEvent as ReactKeyboardEvent,
	type ReactNode,
	type PointerEvent as ReactPointerEvent,
	useEffect,
	useRef,
	useState,
} from "react";
import type { CropRegion } from "@/components/video-editor/types";
import { useScopedT } from "@/contexts/I18nContext";
import type { AxcutClip } from "@/lib/ai-edition/schema";
import { formatSeconds } from "@/lib/ai-edition/timeline/format";
import type {
	AiEditionProjectRecordingsResult,
	AiEditionRecordingsDisposal,
} from "@/native/contracts";
import { formatBytes } from "@/utils/formatBytes";
import { getPlatform } from "@/utils/platformUtils";
import { cropDraftFromRegion, cropDraftToPct, previewBoxStyle } from "./cropDraft";
import styles from "./NewEditorShell.module.css";
import { ChoiceRow, Toggle } from "./RightPanes";
import type { VideoSource } from "./VirtualPreview";

interface BaseModalProps {
	open: boolean;
	onClose: () => void;
}

function useEscape(open: boolean, onClose: () => void) {
	useEffect(() => {
		if (!open) return;
		const onKey = (e: KeyboardEvent) => {
			if (e.key === "Escape") onClose();
		};
		document.addEventListener("keydown", onKey);
		return () => document.removeEventListener("keydown", onKey);
	}, [open, onClose]);
}

export function ModalShell({
	open,
	onClose,
	closeOnEscape = true,
	closeOnBackdrop = true,
	title,
	subtitle,
	wide,
	footer,
	children,
}: BaseModalProps & {
	title: string;
	subtitle?: string;
	wide?: boolean;
	/** Off for a dialog that handles Escape itself — two listeners both fire for one
	 *  keypress, and this one's `onClose` wins whatever order they registered in. */
	closeOnEscape?: boolean;
	/** Off while a stray click beside the card would throw away an edit not yet applied.
	 *  Escape, Cancel and the close button still discard it: that is what they mean. */
	closeOnBackdrop?: boolean;
	/** The dialog's actions, kept out of the scrolling body so a short window never hides
	 *  them: a click where an unseen Apply sat used to land on the backdrop. */
	footer?: ReactNode;
	children: ReactNode;
}) {
	const tc = useScopedT("common");
	const dialogRef = useRef<HTMLDivElement | null>(null);
	useEscape(open && closeOnEscape, onClose);
	// Move focus into the dialog as it opens, and hand it back to whatever had it when the
	// dialog goes. The app menu closes without restoring focus to its trigger — right for a
	// pointer user — so otherwise the opener is left on document.body: Tab then walks the
	// editor *behind* the backdrop, and a screen reader is never told a dialog appeared.
	// Closing has the mirror problem: the focused node is the one being unmounted.
	useEffect(() => {
		if (!open) return;
		// Whatever opened this. Often document.body (the app menu unmounts its own row before
		// the dialog mounts), in which case restoring is a no-op; the panel's gear is still
		// there, and gets it back.
		const opener = document.activeElement;
		dialogRef.current?.focus();
		return () => {
			if (opener instanceof HTMLElement && opener.isConnected) opener.focus();
		};
	}, [open]);
	if (!open) return null;
	return (
		<div
			ref={dialogRef}
			tabIndex={-1}
			className={`${styles.modal} ${open ? styles.isOpen : ""}`}
			role="dialog"
			aria-modal="true"
			aria-labelledby="modal-title"
		>
			<div
				className={styles.modalBackdrop}
				aria-hidden
				onClick={closeOnBackdrop ? onClose : undefined}
			/>
			<div className={`${styles.modalCard} ${wide ? styles.wide : ""}`}>
				<header className={styles.modalHead}>
					<div>
						<h2 id="modal-title">{title}</h2>
						{subtitle ? <p>{subtitle}</p> : null}
					</div>
					<button
						type="button"
						className={styles.closeBtn}
						onClick={onClose}
						title={tc("actions.close")}
						aria-label={tc("actions.close")}
					>
						<X size={18} />
					</button>
				</header>
				<div className={styles.modalBody}>{children}</div>
				{footer ? <footer className={styles.modalFoot}>{footer}</footer> : null}
			</div>
		</div>
	);
}

interface ProjectItem {
	id: string;
	title: string;
	updatedAt: string;
}

interface OpenProjectModalProps extends BaseModalProps {
	projects: ProjectItem[];
	activeProjectId: string | null;
	onSelect: (id: string) => void;
	onDelete: (
		id: string,
		recordings: AiEditionRecordingsDisposal,
	) => Promise<{ trashFailed?: boolean } | undefined>;
	/** The recordings deleting `id` could also remove. */
	loadRecordings: (id: string) => Promise<AiEditionProjectRecordingsResult>;
	onBrowse: () => void;
}

export function OpenProjectModal({
	open,
	onClose,
	projects,
	activeProjectId,
	onSelect,
	onDelete,
	loadRecordings,
	onBrowse,
}: OpenProjectModalProps) {
	const t = useScopedT("editor");
	const tc = useScopedT("common");
	const [query, setQuery] = useState("");
	// Deleting a project cannot be undone, so the trash icon arms an inline
	// confirm on its own row instead of deleting on the first click. One row at a
	// time, and closing the dialog disarms it.
	const [confirmId, setConfirmId] = useState<string | null>(null);
	const [recordings, setRecordings] = useState<AiEditionProjectRecordingsResult | null>(null);
	const [trashRecordings, setTrashRecordings] = useState(false);
	const [trashFailed, setTrashFailed] = useState(false);
	const [deleting, setDeleting] = useState(false);
	const armedIdRef = useRef<string | null>(null);
	const arm = (id: string | null) => {
		armedIdRef.current = id;
		setConfirmId(id);
		setRecordings(null);
		setTrashRecordings(false);
		setTrashFailed(false);
		// The open project's take is held by the preview: Windows refuses to move it, after its
		// sidecars are already gone. Its recordings are kept, and the row says so.
		if (!id || id === activeProjectId) return;
		void loadRecordings(id)
			.then((result) => {
				if (armedIdRef.current === id && result.success) setRecordings(result);
			})
			// Without the answer the row offers no toggle, and the delete keeps the recordings.
			.catch(() => undefined);
	};
	// biome-ignore lint/correctness/useExhaustiveDependencies: disarm only when the dialog closes
	useEffect(() => {
		if (!open) arm(null);
	}, [open]);
	const recycleBin = getPlatform() === "win32";
	const confirmDelete = async (id: string) => {
		const disposal: AiEditionRecordingsDisposal = trashFailed
			? "permanent"
			: trashRecordings && recordings && recordings.count > 0
				? "trash"
				: "keep";
		setDeleting(true);
		try {
			const result = await onDelete(id, disposal);
			if (result?.trashFailed) {
				setTrashFailed(true);
				return;
			}
			arm(null);
		} finally {
			setDeleting(false);
		}
	};
	const filtered = projects.filter((p) => p.title.toLowerCase().includes(query.toLowerCase()));
	// The row ↑↓ moved to, or null for the default: the open project, or the first match once a
	// search narrows the list. Enter opens it, as the footer says (#1135).
	const [cursor, setCursor] = useState<number | null>(null);
	// biome-ignore lint/correctness/useExhaustiveDependencies: a new search or a reopened dialog starts back at the default row.
	useEffect(() => setCursor(null), [query, open]);
	const defaultRow = query
		? 0
		: Math.max(
				0,
				filtered.findIndex((p) => p.id === activeProjectId),
			);
	const highlighted = Math.min(cursor ?? defaultRow, filtered.length - 1);
	const highlightedId = filtered[highlighted]?.id;
	const listRef = useRef<HTMLDivElement | null>(null);
	// biome-ignore lint/correctness/useExhaustiveDependencies: scroll each time the highlight moves.
	useEffect(() => {
		listRef.current
			?.querySelector<HTMLElement>('[aria-current="true"]')
			?.scrollIntoView?.({ block: "nearest" });
	}, [highlightedId]);
	useEffect(() => {
		if (!open) return;
		const onKeyDown = (event: KeyboardEvent) => {
			// A focused button (a row, its trash, Browse) answers Enter itself.
			if (confirmId || event.target instanceof HTMLButtonElement) return;
			if (event.key === "ArrowDown" || event.key === "ArrowUp") {
				event.preventDefault();
				const step = event.key === "ArrowDown" ? 1 : -1;
				setCursor(Math.max(0, Math.min(filtered.length - 1, highlighted + step)));
			} else if (event.key === "Enter" && highlightedId) {
				event.preventDefault();
				onSelect(highlightedId);
				onClose();
			}
		};
		document.addEventListener("keydown", onKeyDown);
		return () => document.removeEventListener("keydown", onKeyDown);
	}, [open, confirmId, filtered.length, highlighted, highlightedId, onSelect, onClose]);
	return (
		<ModalShell
			open={open}
			onClose={onClose}
			title={t("openProjectDialog.title")}
			subtitle={t("openProjectDialog.subtitle")}
			wide
		>
			<div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
				<FolderOpen size={14} style={{ color: "var(--muted)" }} />
				<input
					type="search"
					placeholder={t("openProjectDialog.searchPlaceholder")}
					value={query}
					onChange={(e) => setQuery(e.target.value)}
					className={styles.control}
					style={{ flex: 1 }}
				/>
			</div>
			<div
				ref={listRef}
				style={{
					display: "flex",
					flexDirection: "column",
					gap: 2,
					marginBottom: 12,
					// Cap the list so the footer's "Browse files" button stays visible
					// instead of being pushed below the fold when there are many projects;
					// the list scrolls internally.
					maxHeight: "48vh",
					overflowY: "auto",
					scrollbarWidth: "thin",
					scrollbarColor: "var(--border-hi) transparent",
				}}
			>
				{filtered.length === 0 ? (
					<p style={{ color: "var(--muted)", fontSize: 12, padding: 16, textAlign: "center" }}>
						{t("openProjectDialog.noMatches", { query })}
					</p>
				) : (
					filtered.map((p) => {
						const isActive = p.id === activeProjectId;
						const isHighlighted = p.id === highlightedId;
						if (p.id === confirmId) {
							return (
								<div
									key={p.id}
									style={{
										display: "flex",
										alignItems: "center",
										gap: 8,
										padding: "10px 12px",
										borderRadius: "var(--r-md)",
										background: "var(--danger-soft)",
										boxShadow: "inset 0 0 0 1px var(--danger-hatch)",
									}}
								>
									<div style={{ minWidth: 0, flex: 1 }}>
										<div
											style={{
												font: "500 13px/1.3 var(--font-body)",
												overflow: "hidden",
												textOverflow: "ellipsis",
												whiteSpace: "nowrap",
											}}
										>
											{p.title}
										</div>
										<div
											style={{
												font: "400 12px/1.4 var(--font-body)",
												color: "var(--muted)",
												marginTop: 2,
											}}
										>
											{trashFailed
												? t(
														recycleBin
															? "openProjectDialog.recycleFailed"
															: "openProjectDialog.trashFailed",
													)
												: recordings && recordings.count > 0
													? t("openProjectDialog.confirmDeleteProject")
													: t("openProjectDialog.confirmDelete")}
										</div>
										{!trashFailed && recordings && recordings.count > 0 ? (
											<div
												style={{
													display: "flex",
													alignItems: "center",
													gap: 8,
													marginTop: 8,
													font: "400 12px/1.4 var(--font-body)",
												}}
											>
												<Toggle
													checked={trashRecordings}
													onChange={setTrashRecordings}
													ariaLabel={t(
														recycleBin
															? "openProjectDialog.alsoRecycle"
															: "openProjectDialog.alsoTrash",
														{ size: formatBytes(recordings.sizeBytes) },
													)}
												/>
												<span>
													{t(
														recycleBin
															? "openProjectDialog.alsoRecycle"
															: "openProjectDialog.alsoTrash",
														{ size: formatBytes(recordings.sizeBytes) },
													)}
												</span>
											</div>
										) : null}
										{!trashFailed && recordings && recordings.keptFor.length > 0 ? (
											<div
												style={{
													font: "400 12px/1.4 var(--font-body)",
													color: "var(--muted)",
													marginTop: 4,
												}}
											>
												{t("openProjectDialog.recordingsKeptFor", {
													projects: recordings.keptFor.join(", "),
												})}
											</div>
										) : null}
										{!trashFailed && recordings && recordings.unreadable > 0 ? (
											<div
												style={{
													font: "400 12px/1.4 var(--font-body)",
													color: "var(--muted)",
													marginTop: 4,
												}}
											>
												{t("openProjectDialog.recordingsKeptUnreadable")}
											</div>
										) : null}
									</div>
									<button
										type="button"
										className={`${styles.btn} ${styles.btnSecondary}`}
										onClick={() => arm(null)}
									>
										{tc("actions.cancel")}
									</button>
									<button
										type="button"
										className={`${styles.btn} ${styles.dangerBtn}`}
										disabled={deleting}
										onClick={() => void confirmDelete(p.id)}
									>
										<Trash2 size={14} />
										{trashFailed ? t("openProjectDialog.deletePermanently") : tc("actions.delete")}
									</button>
								</div>
							);
						}
						return (
							<div key={p.id} style={{ display: "flex", alignItems: "center", gap: 4 }}>
								<button
									type="button"
									aria-current={isHighlighted ? "true" : undefined}
									onClick={() => {
										onSelect(p.id);
										onClose();
									}}
									style={{
										flex: 1,
										minWidth: 0,
										display: "grid",
										gridTemplateColumns: "36px 1fr auto",
										alignItems: "center",
										gap: 12,
										padding: "10px 12px",
										border: "none",
										borderRadius: "var(--r-md)",
										background: isHighlighted ? "var(--accent-soft)" : "transparent",
										boxShadow: isActive ? "inset 0 0 0 1px var(--accent)" : "none",
										color: "var(--fg)",
										cursor: "pointer",
										textAlign: "left",
										font: "inherit",
									}}
								>
									<div
										style={{
											width: 36,
											height: 36,
											borderRadius: "var(--r-sm)",
											background: "linear-gradient(135deg, var(--brand-lo), var(--brand))",
											display: "grid",
											placeItems: "center",
											color: "var(--accent-on)",
										}}
									>
										<FolderOpen size={18} />
									</div>
									<div style={{ minWidth: 0 }}>
										<div
											style={{
												font: "500 13px/1.3 var(--font-body)",
												overflow: "hidden",
												textOverflow: "ellipsis",
												whiteSpace: "nowrap",
											}}
										>
											{p.title}
										</div>
										<div
											style={{
												font: "400 11px/1.4 var(--font-mono)",
												color: "var(--muted)",
												marginTop: 2,
											}}
										>
											id: {p.id.slice(0, 8)}
										</div>
									</div>
									<span
										style={{
											font: "400 12px/1 var(--font-body)",
											fontVariantNumeric: "tabular-nums",
											color: "var(--muted)",
											whiteSpace: "nowrap",
										}}
									>
										{new Date(p.updatedAt).toLocaleDateString()}
									</span>
								</button>
								<button
									type="button"
									className={styles.iconBtn}
									onClick={() => arm(p.id)}
									title={t("openProjectDialog.deleteProject")}
									aria-label={t("openProjectDialog.deleteProject")}
								>
									<Trash2 size={14} />
								</button>
							</div>
						);
					})
				)}
			</div>
			<div
				style={{
					display: "flex",
					justifyContent: "space-between",
					alignItems: "center",
					paddingTop: 12,
					borderTop: "1px solid var(--border-soft)",
				}}
			>
				<span style={{ fontSize: 12, color: "var(--muted)" }}>
					<kbd
						style={{
							font: "500 11px/1 var(--font-mono)",
							padding: "2px 6px",
							borderRadius: 4,
							background: "var(--surface-2)",
							border: "1px solid var(--border)",
							color: "var(--fg)",
						}}
					>
						↑↓
					</kbd>{" "}
					{t("openProjectDialog.navigateHint")}{" "}
					<kbd
						style={{
							font: "500 11px/1 var(--font-mono)",
							padding: "2px 6px",
							borderRadius: 4,
							background: "var(--surface-2)",
							border: "1px solid var(--border)",
							color: "var(--fg)",
						}}
					>
						Enter
					</kbd>{" "}
					{t("openProjectDialog.openHint")}
				</span>
				<button
					type="button"
					className={`${styles.btn} ${styles.btnSecondary}`}
					onClick={() => {
						onBrowse();
						onClose();
					}}
				>
					<FolderOpen size={14} />
					{t("openProjectDialog.browseFiles")}
				</button>
			</div>
		</ModalShell>
	);
}

/** Where the editor lands once the project exists: the Media or the Rec tab. */
export type StartingPoint = "import" | "screen-recording";

interface NewProjectModalProps extends BaseModalProps {
	onCreate: (title: string, startingPoint: StartingPoint) => void;
}

export function NewProjectModal({ open, onClose, onCreate }: NewProjectModalProps) {
	const t = useScopedT("editor");
	const tc = useScopedT("common");
	const [title, setTitle] = useState(t("newProjectDialog.defaultTitle"));
	const [template, setTemplate] = useState<StartingPoint>("import");
	return (
		<ModalShell
			open={open}
			onClose={onClose}
			title={t("newProjectDialog.title")}
			subtitle={t("newProjectDialog.subtitle")}
		>
			<div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
				<div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
					<label htmlFor="np-name" className={styles.groupLabel} style={{ margin: 0 }}>
						{t("newProjectDialog.nameLabel")}
					</label>
					<input
						id="np-name"
						type="text"
						value={title}
						onChange={(e) => setTitle(e.target.value)}
						className={styles.control}
					/>
				</div>

				<div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
					<label className={styles.groupLabel} style={{ margin: 0 }}>
						{t("newProjectDialog.startingPointLabel")}
					</label>
					<div
						style={{
							display: "grid",
							gridTemplateColumns: "repeat(2, 1fr)",
							gap: 8,
						}}
					>
						<TemplateCell
							icon={<FolderPlus size={18} />}
							title={t("mediaStage.importMedia")}
							desc={t("newProjectDialog.templates.importMediaDesc")}
							active={template === "import"}
							onClick={() => setTemplate("import")}
						/>
						<TemplateCell
							icon={<Crop size={18} />}
							title={t("newProjectDialog.templates.screenRecordingTitle")}
							desc={t("newProjectDialog.templates.screenRecordingDesc")}
							active={template === "screen-recording"}
							onClick={() => setTemplate("screen-recording")}
						/>
					</div>
				</div>

				<div
					style={{
						display: "flex",
						justifyContent: "flex-end",
						gap: 8,
						paddingTop: 12,
						borderTop: "1px solid var(--border-soft)",
					}}
				>
					<button
						type="button"
						className={`${styles.btn} ${styles.btnSecondary}`}
						onClick={onClose}
					>
						{tc("actions.cancel")}
					</button>
					<button
						type="button"
						className={`${styles.btn} ${styles.btnPrimary}`}
						onClick={() => {
							onCreate(title.trim() || t("newProjectDialog.defaultTitle"), template);
							onClose();
						}}
					>
						<Plus size={14} />
						{t("newProjectDialog.create")}
					</button>
				</div>
			</div>
		</ModalShell>
	);
}

function TemplateCell({
	icon,
	title,
	desc,
	active,
	onClick,
}: {
	icon: ReactNode;
	title: string;
	desc: string;
	active: boolean;
	onClick: () => void;
}) {
	return (
		<button
			type="button"
			onClick={onClick}
			style={{
				display: "flex",
				flexDirection: "column",
				alignItems: "flex-start",
				gap: 8,
				padding: 12,
				border: `1px solid ${active ? "var(--accent)" : "transparent"}`,
				borderRadius: 12,
				background: active
					? "var(--accent-soft)"
					: "color-mix(in oklab, var(--fg) 5%, transparent)",
				color: "var(--fg)",
				cursor: "pointer",
				textAlign: "left",
				font: "inherit",
			}}
		>
			<span
				style={{
					width: 36,
					height: 36,
					borderRadius: "var(--r-sm)",
					background: active ? "var(--accent)" : "var(--surface-2)",
					color: active ? "var(--accent-on)" : "var(--muted)",
					display: "grid",
					placeItems: "center",
				}}
			>
				{icon}
			</span>
			<span style={{ font: "500 13px/1.3 var(--font-body)" }}>{title}</span>
			<span style={{ font: "400 12px/1.4 var(--font-body)", color: "var(--muted)" }}>{desc}</span>
		</button>
	);
}

// `ratio` is width/height (matches the label directly: "16:9" → 16/9 means
// a region 16 units wide for every 9 tall).
const CROP_RATIOS: Array<{ value: string; label: string; ratio: number | null }> = [
	{ value: "free", label: "Free", ratio: null },
	{ value: "16:9", label: "16:9", ratio: 16 / 9 },
	{ value: "9:16", label: "9:16", ratio: 9 / 16 },
	{ value: "1:1", label: "1:1", ratio: 1 },
	{ value: "4:3", label: "4:3", ratio: 4 / 3 },
	{ value: "3:4", label: "3:4", ratio: 3 / 4 },
	{ value: "21:9", label: "21:9", ratio: 21 / 9 },
];

// `region.width`/`region.height` are fractions of the source frame, not a
// visual aspect ratio — a region that's 100% wide and 56.25% tall on a 16:9
// source renders as a 16:9 rectangle on screen, not a "1 : 0.5625" one. The
// actual on-screen ratio is the fraction ratio scaled by the source video's
// own pixel aspect ratio, so detecting/applying a preset must go through
// `videoAspectRatio` (source width/height in pixels) in both directions.
function detectRatio(r: CropRegion, videoAspectRatio: number): string {
	const candidates = CROP_RATIOS.filter((c) => c.ratio !== null);
	if (r.height === 0) return "free";
	const visualRatio = (r.width / r.height) * videoAspectRatio;
	for (const c of candidates) {
		if (c.ratio === null) continue;
		if (Math.abs(visualRatio - c.ratio) / c.ratio < 0.02) return c.value;
	}
	return "free";
}

// Largest crop rectangle (percentages of the frame) whose fraction-space ratio
// is `fr` (= width/height, already converted from the visual ratio through the
// source's pixel aspect ratio), centered on whichever axis has slack. One
// dimension fills the frame; the other is derived so the result never overflows.
function centeredFitPct(fr: number): { x: number; y: number; w: number; h: number } {
	if (!(fr > 0)) return { x: 0, y: 0, w: 100, h: 100 };
	if (fr >= 1) {
		const h = 100 / fr;
		return { x: 0, y: (100 - h) / 2, w: 100, h };
	}
	const w = 100 * fr;
	return { x: (100 - w) / 2, y: 0, w, h: 100 };
}

const MIN_PCT = 4;
const clampPct = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));

type ResizeEdges = { left?: boolean; right?: boolean; top?: boolean; bottom?: boolean };
type CropPct = { x: number; y: number; w: number; h: number };

/** `start` with its `edges` moved by (dxPct, dyPct), kept inside the frame. With a locked
 *  fraction-space ratio `fr`, the opposite dimension follows to keep width/height locked. */
function resizeCropPct(
	start: CropPct,
	edges: ResizeEdges,
	dxPct: number,
	dyPct: number,
	fr: number | null,
): CropPct {
	let { x, y, w, h } = start;
	if (edges.left) {
		const nx = clampPct(start.x + dxPct, 0, start.x + start.w - MIN_PCT);
		w = start.w - (nx - start.x);
		x = nx;
	}
	if (edges.right) {
		w = clampPct(start.w + dxPct, MIN_PCT, 100 - start.x);
	}
	if (edges.top) {
		const ny = clampPct(start.y + dyPct, 0, start.y + start.h - MIN_PCT);
		h = start.h - (ny - start.y);
		y = ny;
	}
	if (edges.bottom) {
		h = clampPct(start.h + dyPct, MIN_PCT, 100 - start.y);
	}
	if (fr) {
		// Locked ratio: the crop stays a fixed shape anchored at the corner the
		// user isn't dragging. The dragged size is capped at the largest rect of
		// this ratio that fits from that anchor — so it's simply sized to fit,
		// never placed out of frame. (A crop can't leave the frame, so there is
		// no out-of-bounds state to correct after the fact.)
		const fixedLeft = !edges.left; // the x-edge that stays put
		const fixedTop = !edges.top; // the y-edge that stays put
		const anchorX = fixedLeft ? start.x : start.x + start.w;
		const anchorY = fixedTop ? start.y : start.y + start.h;
		const roomW = fixedLeft ? 100 - anchorX : anchorX;
		const roomH = fixedTop ? 100 - anchorY : anchorY;
		// Which axis the pointer drives; the other is derived from the ratio.
		const drivenByHeight = (edges.top || edges.bottom) && !(edges.left || edges.right);
		let nextW = Math.min(drivenByHeight ? h * fr : w, roomW, roomH * fr);
		nextW = Math.max(MIN_PCT, nextW);
		let nextH = nextW / fr;
		if (nextH < MIN_PCT) {
			nextH = MIN_PCT;
			nextW = nextH * fr;
		}
		w = nextW;
		h = nextH;
		x = fixedLeft ? anchorX : anchorX - w;
		y = fixedTop ? anchorY : anchorY - h;
	}
	return { x, y, w, h };
}

const CROP_CORNERS = ["nw", "ne", "sw", "se"] as const;
const CROP_EDGES = ["n", "s", "w", "e"] as const;

export interface AssetMeta {
	label: string;
	durationSec?: number;
}

const IDENTITY_CROP: CropRegion = { x: 0, y: 0, width: 1, height: 1 };

interface EditClipModalProps extends BaseModalProps {
	clip: AxcutClip | null;
	assetMeta: AssetMeta | null;
	videoSources: VideoSource[];
	/** `cropRegion` is `undefined` when the crop section wasn't touched (Reset
	 * back to the clip's stored value) — the caller can skip the write in that
	 * case — and `null` when the user explicitly reset it to "no crop". */
	onApply: (sourceStartSec: number, sourceEndSec: number, cropRegion?: CropRegion | null) => void;
}

// Mirrors Axcut's ClipEditDialog: an embedded preview of just this clip plus
// a draggable dual-handle range over the asset's full source duration —
// replaces the old numeric-input-only form. Trim range AND crop are both
// per-clip and both edited here (see clipSchema.cropRegion / useTimeline's
// applyClipEdit, which composes the two into one save) — crop used to be a document-wide
// setting behind its own facet-rail button; it's a framing choice for one
// piece of footage, so it belongs with the rest of this clip's edits.
export function EditClipModal({
	open,
	onClose,
	clip,
	assetMeta,
	videoSources,
	onApply,
}: EditClipModalProps) {
	const t = useScopedT("editor");
	const tc = useScopedT("common");
	const ts = useScopedT("settings");
	const trackRef = useRef<HTMLDivElement | null>(null);
	const [draftStart, setDraftStart] = useState(0);
	const [draftEnd, setDraftEnd] = useState(0);
	const [activeEdge, setActiveEdge] = useState<"start" | "end" | null>(null);

	// Crop draft — percentages (0-100), same shape/units CropModal used to
	// keep locally before it was folded in here.
	const [cropXPct, setCropXPct] = useState(0);
	const [cropYPct, setCropYPct] = useState(0);
	const [cropWPct, setCropWPct] = useState(100);
	const [cropHPct, setCropHPct] = useState(100);
	const [cropRatio, setCropRatio] = useState("free");
	const [cropTouched, setCropTouched] = useState(false);
	// Source video's real pixel aspect ratio (width/height) — needed to convert
	// between a preset's visual ratio (e.g. 16/9) and the crop region's
	// fraction-of-frame width/height. 16/9 is just a placeholder until the
	// crop <video>'s real metadata loads (see the effect below).
	const [videoAspectRatio, setVideoAspectRatio] = useState(16 / 9);
	const cropFrameRef = useRef<HTMLDivElement | null>(null);
	const cropVideoRef = useRef<HTMLVideoElement | null>(null);
	// The frame the crop is framed on, on the source clock like the trim. Local to this
	// dialog, and always inside the kept range.
	const [playheadSec, setPlayheadSec] = useState(0);

	// ponytail: sync local drag state to the clip every time the modal opens.
	// `open` is the trigger so external clip changes don't fight the user mid-edit.
	useEffect(() => {
		if (!open || !clip) return;
		setDraftStart(clip.sourceStartSec);
		setDraftEnd(clip.sourceEndSec ?? clip.sourceStartSec);
		setActiveEdge(null);
		setPlayheadSec(clip.sourceStartSec);
		const region = clip.cropRegion ?? IDENTITY_CROP;
		const pct = cropDraftToPct(cropDraftFromRegion(region));
		setCropXPct(pct.x);
		setCropYPct(pct.y);
		setCropWPct(pct.w);
		setCropHPct(pct.h);
		setCropTouched(false);
	}, [open, clip]);

	// The picture follows the playhead: every seek of the preview is this one, including the
	// first, and a scrub before the metadata lands is not lost.
	useEffect(() => {
		const v = cropVideoRef.current;
		if (!open || !v) return;
		const seek = () => {
			v.currentTime = playheadSec;
		};
		if (v.readyState >= 1) seek();
		else v.addEventListener("loadedmetadata", seek, { once: true });
		return () => v.removeEventListener("loadedmetadata", seek);
	}, [open, playheadSec]);

	// Re-detect the active ratio preset whenever the stored region or the
	// video's real aspect ratio changes — the latter only becomes accurate
	// once the crop <video>'s metadata loads (see the effect below), so this
	// re-runs a beat after the sync-on-open effect above with the real value.
	// Skipped once the user starts touching the crop so it doesn't fight
	// their own free-form edits.
	useEffect(() => {
		if (!open || !clip || cropTouched) return;
		const region = clip.cropRegion ?? IDENTITY_CROP;
		setCropRatio(detectRatio(region, videoAspectRatio));
	}, [open, clip, videoAspectRatio, cropTouched]);

	// Crop preview: a paused still frame is enough to judge a crop (mirrors
	// the standalone CropModal this replaced). The playhead effect above seeks
	// it; this one reads the frame's aspect ratio.
	useEffect(() => {
		if (!open || !clip) return;
		// A clip switch must not leave the previous clip's dimensions live: an
		// immediate preset or typed edit would quantize against the wrong
		// resolution and `cropTouched` would lock the wrong aspect in. Reset to
		// the same defaults a fresh dialog starts with; the metadata handler
		// below refills them (immediately, when this clip's metadata is already
		// loaded).
		setVideoAspectRatio(16 / 9);
		const v = cropVideoRef.current;
		if (!v) return;
		const onMetadata = () => {
			v.pause();
			if (v.videoWidth > 0 && v.videoHeight > 0) {
				setVideoAspectRatio(v.videoWidth / v.videoHeight);
			}
		};
		if (v.readyState >= 1) onMetadata();
		else v.addEventListener("loadedmetadata", onMetadata, { once: true });
		return () => v.removeEventListener("loadedmetadata", onMetadata);
	}, [open, clip]);

	if (!clip) return null;

	// The asset's own length, or null when the document never carried one
	// (`durationSec` is optional in the schema, and an unprobed import has none).
	// Only this may be shown as the original duration.
	const assetDurationSec =
		assetMeta?.durationSec && assetMeta.durationSec > 0 ? assetMeta.durationSec : null;
	// What the track is drawn against. It has to hold the selection whatever the
	// metadata says, so it falls back to the out-point — which is why it cannot
	// double as the original-duration readout: with no asset duration it would
	// report the current trim end as the source length.
	const sourceDurationSec = Math.max(assetDurationSec ?? 0, clip.sourceEndSec ?? 0, 0.001);
	// What the trim keeps, on the raw ruler — the same clock the timeline, the
	// transport readout and the clip cards all run on. A speed region does change
	// how long that span PLAYS (`outputDurationOfRawSpan` integrates 1/speed for
	// the export and audio paths), but nothing in the editor's own chrome reports
	// playback time, so scaling it here alone would disagree with the ruler
	// directly above this dialog.
	const durationSec = Math.max(0.001, draftEnd - draftStart);
	const hasTrimChanges =
		Math.abs(draftStart - clip.sourceStartSec) > 0.001 ||
		Math.abs(draftEnd - (clip.sourceEndSec ?? 0)) > 0.001;
	const hasChanges = hasTrimChanges || cropTouched;
	const clipSources = videoSources.filter((s) => s.id === clip.assetId);
	const cropPreviewSource = clipSources[0] ?? null;

	const startDrag = (edge: "start" | "end", event: ReactPointerEvent<HTMLButtonElement>) => {
		const track = trackRef.current;
		if (!track) return;
		event.preventDefault();
		event.stopPropagation();
		const widthPx = Math.max(1, track.clientWidth);
		const startClientX = event.clientX;
		const startDraftStart = draftStart;
		const startDraftEnd = draftEnd;
		setActiveEdge(edge);
		const move = (moveEvent: PointerEvent) => {
			const deltaSec = ((moveEvent.clientX - startClientX) / widthPx) * sourceDurationSec;
			// A trim that crosses the playhead pushes it along, so it never leaves the kept range.
			if (edge === "start") {
				const next = Math.min(Math.max(startDraftStart + deltaSec, 0), startDraftEnd - 0.05);
				setDraftStart(next);
				setPlayheadSec((p) => Math.max(p, next));
			} else {
				const next = Math.max(
					Math.min(startDraftEnd + deltaSec, sourceDurationSec),
					startDraftStart + 0.05,
				);
				setDraftEnd(next);
				setPlayheadSec((p) => Math.min(p, next));
			}
		};
		const end = () => {
			window.removeEventListener("pointermove", move);
			window.removeEventListener("pointerup", end);
			setActiveEdge(null);
		};
		window.addEventListener("pointermove", move);
		window.addEventListener("pointerup", end, { once: true });
	};

	// Click or drag the track to put the playhead on the frame to crop on, held inside the
	// kept range. The grips stop their own pointerdown, so grabbing one trims instead.
	const startScrub = (event: ReactPointerEvent<HTMLDivElement>) => {
		const track = trackRef.current;
		if (!track) return;
		event.preventDefault();
		const left = track.getBoundingClientRect().left;
		const widthPx = Math.max(1, track.clientWidth);
		const seekAt = (clientX: number) => {
			const sec = ((clientX - left) / widthPx) * sourceDurationSec;
			setPlayheadSec(Math.min(Math.max(sec, draftStart), draftEnd));
		};
		seekAt(event.clientX);
		const move = (moveEvent: PointerEvent) => seekAt(moveEvent.clientX);
		const end = () => {
			window.removeEventListener("pointermove", move);
			window.removeEventListener("pointerup", end);
		};
		window.addEventListener("pointermove", move);
		window.addEventListener("pointerup", end, { once: true });
	};

	const handleCropRatioChange = (next: string) => {
		setCropTouched(true);
		setCropRatio(next);
		const candidate = CROP_RATIOS.find((c) => c.value === next);
		// "Free" keeps whatever the user currently has; a preset snaps the crop to
		// the largest centered rectangle of that exact ratio (and, via the locked
		// field/handle logic below, keeps every later edit at that ratio).
		if (!candidate?.ratio) return;
		const fit = centeredFitPct(candidate.ratio / videoAspectRatio);
		setCropXPct(fit.x);
		setCropYPct(fit.y);
		setCropWPct(fit.w);
		setCropHPct(fit.h);
	};

	// Fraction-space width/height ratio the crop is locked to while a preset is
	// active (null for "Free"). The resize handles honor it, so the user can
	// move/scale the crop but never change its aspect ratio.
	const activePresetRatio = CROP_RATIOS.find((c) => c.value === cropRatio)?.ratio ?? null;
	const lockedFractionRatio = activePresetRatio ? activePresetRatio / videoAspectRatio : null;

	// Drag the whole crop region (keeps size, moves x/y).
	const startCropMove = (e: ReactPointerEvent) => {
		e.preventDefault();
		e.stopPropagation();
		const el = cropFrameRef.current;
		if (!el) return;
		const r = el.getBoundingClientRect();
		const startX = e.clientX;
		const startY = e.clientY;
		const start = { x: cropXPct, y: cropYPct, w: cropWPct, h: cropHPct };
		setCropTouched(true);
		const move = (ev: PointerEvent) => {
			const dxPct = ((ev.clientX - startX) / r.width) * 100;
			const dyPct = ((ev.clientY - startY) / r.height) * 100;
			setCropXPct(clampPct(start.x + dxPct, 0, 100 - start.w));
			setCropYPct(clampPct(start.y + dyPct, 0, 100 - start.h));
		};
		const up = () => {
			window.removeEventListener("pointermove", move);
			window.removeEventListener("pointerup", up);
		};
		window.addEventListener("pointermove", move);
		window.addEventListener("pointerup", up);
	};

	const setCrop = (next: CropPct) => {
		setCropXPct(next.x);
		setCropYPct(next.y);
		setCropWPct(next.w);
		setCropHPct(next.h);
	};

	// The keyboard's way to the same two gestures: the arrows move the crop, Shift + the
	// arrows resize it from its bottom-right corner, a locked ratio held as the handles hold it.
	const onCropKeyDown = (e: ReactKeyboardEvent) => {
		const dx = e.key === "ArrowLeft" ? -1 : e.key === "ArrowRight" ? 1 : 0;
		const dy = e.key === "ArrowUp" ? -1 : e.key === "ArrowDown" ? 1 : 0;
		if (dx === 0 && dy === 0) return;
		// The editor shell seeks on the arrows, from WINDOW: keep them here.
		e.preventDefault();
		e.nativeEvent.stopPropagation();
		setCropTouched(true);
		const start = { x: cropXPct, y: cropYPct, w: cropWPct, h: cropHPct };
		if (e.shiftKey) {
			const edges = { right: dx !== 0, bottom: dy !== 0 };
			setCrop(resizeCropPct(start, edges, dx, dy, lockedFractionRatio));
			return;
		}
		setCropXPct(clampPct(start.x + dx, 0, 100 - start.w));
		setCropYPct(clampPct(start.y + dy, 0, 100 - start.h));
	};

	// Drag one of the 8 edge/corner handles to resize. When a fixed ratio is
	// active, the opposite dimension follows to keep width/height locked.
	const startCropResize = (edges: ResizeEdges) => (e: ReactPointerEvent) => {
		e.preventDefault();
		e.stopPropagation();
		const el = cropFrameRef.current;
		if (!el) return;
		const r = el.getBoundingClientRect();
		const startX = e.clientX;
		const startY = e.clientY;
		const start = { x: cropXPct, y: cropYPct, w: cropWPct, h: cropHPct };
		// Fraction-space ratio the resize is locked to (null for "Free").
		const fr = lockedFractionRatio;
		setCropTouched(true);
		const move = (ev: PointerEvent) => {
			const dxPct = ((ev.clientX - startX) / r.width) * 100;
			const dyPct = ((ev.clientY - startY) / r.height) * 100;
			setCrop(resizeCropPct(start, edges, dxPct, dyPct, fr));
		};
		const up = () => {
			window.removeEventListener("pointermove", move);
			window.removeEventListener("pointerup", up);
		};
		window.addEventListener("pointermove", move);
		window.addEventListener("pointerup", up);
	};

	const handleReset = () => {
		const end = clip.sourceEndSec ?? clip.sourceStartSec;
		setDraftStart(clip.sourceStartSec);
		setDraftEnd(end);
		setPlayheadSec((p) => Math.min(Math.max(p, clip.sourceStartSec), end));
		const region = clip.cropRegion ?? IDENTITY_CROP;
		const pct = cropDraftToPct(cropDraftFromRegion(region));
		setCropXPct(pct.x);
		setCropYPct(pct.y);
		setCropWPct(pct.w);
		setCropHPct(pct.h);
		setCropRatio(detectRatio(region, videoAspectRatio));
		setCropTouched(false);
	};
	const handleApply = () => {
		const nextCrop: CropRegion = {
			x: Math.max(0, Math.min(1, cropXPct / 100)),
			y: Math.max(0, Math.min(1, cropYPct / 100)),
			width: Math.max(0.01, Math.min(1, cropWPct / 100)),
			height: Math.max(0.01, Math.min(1, cropHPct / 100)),
		};
		const isIdentity =
			nextCrop.x === 0 && nextCrop.y === 0 && nextCrop.width === 1 && nextCrop.height === 1;
		onApply(draftStart, draftEnd, cropTouched ? (isIdentity ? null : nextCrop) : undefined);
		onClose();
	};

	return (
		<ModalShell
			open={open}
			onClose={onClose}
			closeOnBackdrop={!hasChanges}
			title={t("editClipDialog.title")}
			subtitle={assetMeta?.label ?? undefined}
			wide
			footer={
				<div
					style={{
						display: "flex",
						justifyContent: "space-between",
						alignItems: "center",
						paddingTop: 10,
						borderTop: "1px solid var(--border-soft)",
					}}
				>
					<button
						type="button"
						className={`${styles.btn} ${styles.btnSecondary}`}
						onClick={handleReset}
						disabled={!hasChanges}
					>
						{t("editClipDialog.reset")}
					</button>
					<div style={{ display: "flex", gap: 8 }}>
						<button
							type="button"
							className={`${styles.btn} ${styles.btnSecondary}`}
							onClick={onClose}
						>
							{tc("actions.cancel")}
						</button>
						<button
							type="button"
							className={`${styles.btn} ${styles.btnPrimary}`}
							onClick={handleApply}
							disabled={!hasChanges}
						>
							<Pencil size={14} />
							{t("editClipDialog.apply")}
						</button>
					</div>
				</div>
			}
		>
			<div ref={cropFrameRef} style={previewBoxStyle(videoAspectRatio)}>
				{cropPreviewSource ? (
					<video
						ref={cropVideoRef}
						src={cropPreviewSource.src}
						muted
						playsInline
						style={{
							position: "absolute",
							inset: 0,
							width: "100%",
							height: "100%",
							objectFit: "contain",
							background: "#000",
						}}
					/>
				) : null}
				<div
					className={styles.cropRegion}
					role="slider"
					aria-label={ts("crop.title")}
					aria-valuemin={0}
					aria-valuemax={100}
					aria-valuenow={Math.round(cropWPct)}
					aria-valuetext={`${Math.round(cropXPct)}%, ${Math.round(cropYPct)}%, ${Math.round(cropWPct)}% × ${Math.round(cropHPct)}%`}
					aria-keyshortcuts="Shift+ArrowLeft Shift+ArrowRight Shift+ArrowUp Shift+ArrowDown"
					tabIndex={0}
					onKeyDown={onCropKeyDown}
					style={{
						position: "absolute",
						left: `${cropXPct}%`,
						top: `${cropYPct}%`,
						width: `${cropWPct}%`,
						height: `${cropHPct}%`,
						// White on any footage, like the brackets: `--fg` went dark in the light theme.
						border: "1.5px solid rgb(255 255 255 / 0.9)",
						borderRadius: 4,
						boxShadow: "0 0 0 9999px var(--overlay-dark)",
						cursor: "move",
						touchAction: "none",
						// Bigger brackets for a bigger picture than the webcam thumbnail's.
						...({ "--bracket": "22px", "--bracket-w": "4px" } as React.CSSProperties),
					}}
					onPointerDown={startCropMove}
				>
					{/* The webcam frame's brackets on the corners, and a bar on each side for the
					    one-axis resize a free crop needs. Both in grab areas a pointer finds without
					    aiming. */}
					{CROP_CORNERS.map((corner) => (
						<span
							key={corner}
							className={styles.framingHandle}
							data-corner={corner}
							onPointerDown={startCropResize({
								top: corner.startsWith("n"),
								bottom: corner.startsWith("s"),
								left: corner.endsWith("w"),
								right: corner.endsWith("e"),
							})}
						/>
					))}
					{CROP_EDGES.map((edge) => (
						<span
							key={edge}
							className={styles.cropEdge}
							data-edge={edge}
							onPointerDown={startCropResize({
								top: edge === "n",
								bottom: edge === "s",
								left: edge === "w",
								right: edge === "e",
							})}
						/>
					))}
				</div>
			</div>

			<div style={{ flexShrink: 0 }}>
				<div
					style={{ display: "flex", gap: 24, marginBottom: 10 }}
					aria-live="polite"
					aria-atomic="true"
				>
					<RangeStat
						label={t("editClipDialog.originalDuration")}
						value={assetDurationSec === null ? "—" : formatSeconds(assetDurationSec)}
						testId="edit-clip-original-duration"
					/>
					<RangeStat
						label={t("editClipDialog.trimRange")}
						value={`${formatSeconds(draftStart)}–${formatSeconds(draftEnd)}`}
						testId="edit-clip-trim-range"
					/>
					<RangeStat
						label={t("editClipDialog.duration")}
						value={formatSeconds(durationSec)}
						testId="edit-clip-final-duration"
					/>
				</div>

				<div
					style={{
						display: "flex",
						justifyContent: "space-between",
						font: "500 11px/1.4 var(--font-body)",
						fontVariantNumeric: "tabular-nums",
						color: "var(--muted)",
						marginBottom: 4,
					}}
				>
					<span>0:00.0</span>
					<span>{formatSeconds(sourceDurationSec)}</span>
				</div>
				{/* The kept range is the timeline's clip card; the bare groove around it is the
				    discarded head and tail. The playhead is the only thing painted over the grips, and
				    it never takes a grab. */}
				<div
					ref={trackRef}
					data-testid="edit-clip-trim-track"
					className={styles.editClipTrack}
					onPointerDown={startScrub}
				>
					<div
						className={`${styles.editClipRange}${activeEdge ? ` ${styles.editClipRangeDragging}` : ""}`}
						style={{
							left: `${(draftStart / sourceDurationSec) * 100}%`,
							width: `${Math.max(0.5, (durationSec / sourceDurationSec) * 100)}%`,
						}}
					>
						<button
							type="button"
							className={styles.editClipGrip}
							data-edge="start"
							onPointerDown={(e) => startDrag("start", e)}
							aria-label={t("editClipDialog.adjustStart")}
							title={t("editClipDialog.adjustStart")}
						/>
						<button
							type="button"
							className={styles.editClipGrip}
							data-edge="end"
							onPointerDown={(e) => startDrag("end", e)}
							aria-label={t("editClipDialog.adjustEnd")}
							title={t("editClipDialog.adjustEnd")}
						/>
					</div>
					<div
						className={styles.editClipPlayhead}
						data-testid="edit-clip-playhead"
						style={{ left: `${(playheadSec / sourceDurationSec) * 100}%` }}
					/>
				</div>
			</div>

			<div
				style={{
					paddingTop: 8,
					marginTop: 8,
					flexShrink: 0,
					borderTop: "1px solid var(--border-soft)",
				}}
			>
				<div style={{ display: "flex", alignItems: "center", gap: 12 }}>
					<span className={styles.fieldLabel}>{ts("crop.ratio")}</span>
					<div style={{ flex: 1, minWidth: 0 }}>
						<ChoiceRow<string>
							label={ts("crop.ratio")}
							options={CROP_RATIOS.map((r) => ({
								value: r.value,
								label: r.value === "free" ? ts("crop.free") : r.label,
							}))}
							value={cropRatio}
							onChange={handleCropRatioChange}
						/>
					</div>
				</div>
			</div>
		</ModalShell>
	);
}

function RangeStat({ label, value, testId }: { label: string; value: string; testId?: string }) {
	return (
		<div data-testid={testId} style={{ display: "flex", flexDirection: "column", gap: 2 }}>
			<strong
				style={{
					font: "600 15px/1.2 var(--font-body)",
					fontVariantNumeric: "tabular-nums",
					color: "var(--fg)",
				}}
			>
				{value}
			</strong>
			<small style={{ font: "500 12px/1.4 var(--font-body)", color: "var(--muted)" }}>
				{label}
			</small>
		</div>
	);
}

export type UnsavedChoice = "save" | "discard" | "cancel";

interface UnsavedChangesModalProps extends BaseModalProps {
	action: "close" | "new" | "open" | "record";
	busy?: boolean;
	onChoose: (choice: UnsavedChoice) => void;
}

export function UnsavedChangesModal({
	open,
	onClose,
	action,
	busy,
	onChoose,
}: UnsavedChangesModalProps) {
	const td = useScopedT("dialogs");
	const tc = useScopedT("common");
	const titleKeys: Record<UnsavedChangesModalProps["action"], string> = {
		close: "unsavedChanges.modal.closeTitle",
		new: "unsavedChanges.modal.newTitle",
		open: "unsavedChanges.modal.openTitle",
		record: "unsavedChanges.modal.recordTitle",
	};
	const copy = {
		title: td(titleKeys[action]),
		body:
			action === "close"
				? td("unsavedChanges.modal.closeBody")
				: td("unsavedChanges.modal.sharedBody"),
	};
	return (
		<ModalShell open={open} onClose={onClose} title={copy.title} subtitle={copy.body}>
			<div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
				<span
					style={{
						display: "grid",
						placeItems: "center",
						width: 32,
						height: 32,
						borderRadius: 8,
						background: "var(--warn-soft)",
						color: "var(--warn)",
					}}
				>
					<AlertTriangle size={16} />
				</span>
				<div
					style={{
						font: "500 12px var(--font-body)",
						color: "var(--fg-2)",
					}}
				>
					{td("unsavedChanges.modal.notSavedYet")}
				</div>
			</div>
			<div
				style={{
					display: "flex",
					justifyContent: "flex-end",
					gap: 8,
					paddingTop: 12,
					borderTop: "1px solid var(--border-soft)",
				}}
			>
				<button
					type="button"
					className={`${styles.btn} ${styles.btnSecondary}`}
					onClick={() => onChoose("cancel")}
					disabled={busy}
				>
					{tc("actions.cancel")}
				</button>
				<button
					type="button"
					className={`${styles.btn} ${styles.btnSecondary}`}
					onClick={() => onChoose("discard")}
					disabled={busy}
				>
					{td("unsavedChanges.modal.discard")}
				</button>
				<button
					type="button"
					className={`${styles.btn} ${styles.btnPrimary}`}
					onClick={() => onChoose("save")}
					disabled={busy}
				>
					{busy ? td("unsavedChanges.modal.saving") : td("unsavedChanges.modal.saveAndContinue")}
				</button>
			</div>
		</ModalShell>
	);
}

export interface ChatHistoryModalProps extends BaseModalProps {
	sessions: Array<{ id: string; title: string; messageCount: number; createdAt: string }>;
	activeSessionId: string | null;
	onSelect: (id: string) => void;
	onNew: () => void;
}

export function ChatHistoryModal({
	open,
	onClose,
	sessions,
	activeSessionId,
	onSelect,
	onNew: _onNew,
}: ChatHistoryModalProps) {
	void _onNew;
	const t = useScopedT("editor");
	const tc = useScopedT("common");
	return (
		<ModalShell
			open={open}
			onClose={onClose}
			title={t("chat.historyDialog.title")}
			subtitle={t("chat.historyDialog.subtitle")}
		>
			{sessions.length === 0 ? (
				<div
					style={{
						padding: 16,
						textAlign: "center",
						color: "var(--muted)",
						font: "500 13px var(--font-body)",
					}}
				>
					{t("chat.historyDialog.empty")}
				</div>
			) : (
				<div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
					{sessions.map((s) => {
						const isActive = s.id === activeSessionId;
						return (
							<button
								type="button"
								key={s.id}
								style={{
									display: "flex",
									alignItems: "center",
									justifyContent: "space-between",
									padding: "10px 12px",
									border: `1px solid ${isActive ? "var(--accent)" : "transparent"}`,
									borderRadius: 12,
									background: isActive
										? "var(--accent-soft)"
										: "color-mix(in oklab, var(--fg) 5%, transparent)",
									color: "var(--fg-2)",
									cursor: "pointer",
									font: "500 13px var(--font-body)",
									textAlign: "left",
									width: "100%",
								}}
								onClick={() => {
									onSelect(s.id);
									onClose();
								}}
							>
								<span style={{ fontWeight: isActive ? 600 : 500 }}>{s.title}</span>
								<span
									style={{
										font: "500 12px/1 var(--font-body)",
										fontVariantNumeric: "tabular-nums",
										color: "var(--muted)",
									}}
								>
									{t("chat.historyDialog.msgsCount", {
										count: s.messageCount,
										date: new Date(s.createdAt).toLocaleDateString(),
									})}
								</span>
							</button>
						);
					})}
				</div>
			)}
			<div
				style={{
					display: "flex",
					justifyContent: "flex-end",
					gap: 8,
					paddingTop: 12,
					borderTop: "1px solid var(--border-soft)",
				}}
			>
				<button type="button" className={`${styles.btn} ${styles.btnSecondary}`} onClick={onClose}>
					{tc("actions.close")}
				</button>
			</div>
		</ModalShell>
	);
}