Skip to content

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

111 KB
Raw Blame
import {
	AudioLines,
	Clock,
	Crosshair,
	Eraser,
	Loader2,
	Maximize2,
	MessageSquare,
	Mic,
	Music,
	PanelsTopLeft,
	Pencil,
	Scissors,
	Sparkles,
	Trash2,
	Wand2,
	ZoomIn,
} from "lucide-react";
import {
	Fragment,
	memo,
	type KeyboardEvent as ReactKeyboardEvent,
	type PointerEvent as ReactPointerEvent,
	useCallback,
	useEffect,
	useMemo,
	useRef,
	useState,
} from "react";
import { toast } from "sonner";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Tooltip, TooltipProvider } from "@/components/ui/tooltip";
import { toFileUrl } from "@/components/video-editor/projectPersistence";
import { ZOOM_DEPTH_SCALES } from "@/components/video-editor/types";
import { useScopedT } from "@/contexts/I18nContext";
import { useShortcuts } from "@/contexts/ShortcutsContext";
import { useAudioPeaks } from "@/hooks/useAudioPeaks";
import {
	AUDIO_LANE_PAD_PX,
	AUDIO_ROW_GAP_PX,
	AUDIO_ROW_HEIGHT_PX,
	audioGhostExtent,
	collapseTracksToPills,
	packAudioTrackRows,
	slipAudioOffsetMs,
} from "@/lib/ai-edition/document/audioTracks";
import { createId } from "@/lib/ai-edition/document/ids";
import { isGeneratedAssetId } from "@/lib/ai-edition/document/insertion";
import { setUiProbeScrubbing } from "@/lib/ai-edition/perf/uiFrameProbe";
import type { AxcutAudioTrack, AxcutClip } from "@/lib/ai-edition/schema";
import { audioGainScalar } from "@/lib/ai-edition/store/editorSettings";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import { useTimelineTranscriptGate } from "@/lib/ai-edition/store/transcriptionStore";
import { useChatPromptBus } from "@/lib/ai-edition/store/useChatPromptBus";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
import type { useTimeline } from "@/lib/ai-edition/store/useTimeline";
import { collectAutoZoomSuggestionsForLatestDocument } from "@/lib/ai-edition/timeline/apply-auto-zooms";
import { formatSec } from "@/lib/ai-edition/timeline/format";
import {
	newRegionDurationSec,
	setTimelineScale,
} from "@/lib/ai-edition/timeline/newRegionDuration";
import { ventilateSpanAcrossClips } from "@/lib/ai-edition/timeline/region-ventilation";
import {
	type AnnotationTrackDrop,
	annotationDropLayers,
	annotationTrackPills,
	packRegionRows,
	REGION_LANE_PAD_PX,
	REGION_ROW_STEP_PX,
	regionLaneHeight,
} from "@/lib/ai-edition/timeline/regionTracks";
import { coalesceRegionsForRuler } from "@/lib/ai-edition/timeline/timelineMap";
import {
	coalescedTrimGroups,
	resolveTimelineSpanToTrim,
	ventilateTimelineSpanToTrims,
} from "@/lib/ai-edition/timeline/trim-mapping";
import { effectiveZoomScale } from "@/lib/ai-edition/timeline/zoom-scale";
import {
	chainedPans,
	transitionCutsMs,
	zoomTransitions,
} from "@/lib/ai-edition/timeline/zoom-transitions";
import { formatBinding } from "@/lib/shortcuts";
import { nativeBridgeClient } from "@/native/client";
import { TransportBar } from "../TransportBar";
import type { VideoSource } from "../VirtualPreview";
import styles from "./EditorShellV4.module.css";
import { LayoutLane } from "./LayoutLane";
import { LayoutPicker } from "./LayoutPicker";

// The AI option's prompt — sent straight to the chat agent via the prompt-bus.
//
// ponytail: cuts ONLY, deliberately. It used to ask for zooms too ("smart
// zoom-ins on the moments where the cursor dwells… focused on the cursor's
// location"), and the model has no way to do that well: measured on a real 66s
// screencast, every trim it emitted landed strictly inside a true silence with a
// 0.06–0.33s margin and destroyed zero speech, while 7 of its 9 zoom focus points
// missed the actual cursor position in their own window — three of them by more
// than a third of the frame. It places zooms from what the transcript SAYS, not
// from where the pointer WAS. Asking for both in one breath bought misaimed zooms
// at the price of the cuts' credibility, and the cursor-driven wand next to it
// already does the zoom pass from the same telemetry, deterministically.
// Re-widen this when the model can be shown to read the track; the workbench
// scenario `real-wizard-enhance` is what would show it.
const AI_ENHANCE_PROMPT =
	"Cut the dead time in this recording: long pauses, silences, and idle stretches where nothing is being said or done. Keep the pacing tight and natural, and do not cut anything a viewer needs. Apply the edits directly to the timeline.";

type TimelineApi = ReturnType<typeof useTimeline>;

const ASSET_MIME = "application/x-axcut-asset";

type ToolId = "cut" | "comment" | "speed";

// "Nice" ruler steps, from a 20th of a second up to an hour. The one that gets
// used depends on the zoom (see rulerTicks), so the ladder has to cover both a
// 5-second span blown up across the panel and a two-hour recording.
const TICK_STEPS_SEC = [
	0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600,
];
/** Smallest gap two ruler labels may sit at — the step grows until they clear it. */
const MIN_LABEL_GAP_PX = 76;
/** Unlabelled ticks drawn between two labelled ones. */
const MINOR_PER_MAJOR = 5;

// ── lane-pill screen geometry ───────────────────────────────────────
// A pill's width IS its duration — there is no minimum beyond the 1px the CSS
// keeps so a very short region doesn't vanish entirely. The floor used to be
// `max(1.5%, …)` of the whole timeline, a percentage and therefore a DURATION:
// on a 30-minute recording every region shorter than 27 s was drawn as if it
// lasted 27 s, at every zoom level, so agent-placed zooms and trims lied about
// what they covered and touching ones merged into one visual block.
//
// What a pill needs room FOR (two resize handles, a label) is a question about
// its width in PIXELS at the current zoom, which is what pillAffordance answers.
/** Grab-strip width of one resize handle — mirrors .lanePillHandle in the CSS. */
const PILL_HANDLE_PX = 6;
/** Clear body left between two inside-mounted handles. Under this the handles
 *  would meet (or overlap) and a "move" drag would silently become a resize —
 *  the point at which the pill flips to the compact geometry below. */
const PILL_MOVE_PX = 6;
/** Two handles + a grabbable body: the narrowest pill that can host its own
 *  chrome inside its box. */
const PILL_HANDLES_MIN_PX = PILL_HANDLE_PX * 2 + PILL_MOVE_PX;
/**
 * Compact pills keep BOTH affordances by moving the chrome outside the box:
 * handle | gap | «the pill» | gap | handle. The gaps belong to the move target
 * (the pill's ::after strip widens by exactly this much), so even a 1px pill
 * offers ~8px to grab for a move and 6px on each side to resize — at every zoom,
 * at every duration. Mirrors .lanePillCompact in the CSS.
 */
const PILL_MOVE_GAP_PX = 4;
/** Offset of an outside-mounted handle from the pill's edge. */
const PILL_HANDLE_OUT_PX = PILL_HANDLE_PX + PILL_MOVE_GAP_PX;
/** Icon (11px) + the pill's own padding (15px): below this, content is pure
 *  overflow — the lane's colour already says which kind it is, and the title
 *  attribute still gives the value on hover. */
const PILL_CONTENT_MIN_PX = 34;
/** Edge-snap radius while dragging a pill, in screen px. */
const PILL_SNAP_PX = 8;
// One audio pill's height, the vertical step between stacked rows, and lane padding
// are defined in audioTracks.ts and imported above.
// The size a newly created pill aims for (PILL_CREATE_PX) lives in
// timeline/newRegionDuration, because the keyboard shortcuts create regions too
// and they are handled in NewEditorShell, outside this component.
/** Visual separation between two clip cards. Taken off each clip's own width
 *  (see .tlClip) rather than inserted between them, so it cannot displace the
 *  clips that follow — which is what a flex `gap` did, once per junction. */
/** Below this a clip cannot show a label and a delete button inside itself. */
const NARROW_CLIP_PX = 120;
// Whether a card can also carry its edited duration. The label row is capped at
// `calc(100% - 50px)` so it clears the delete button, and everything in it but
// the duration is incompressible: the 30px edit button and the 8px gap after it.
// The timecode is the part that varies — `formatSec` never prints an hour field,
// so a clip past ten minutes reads `16:40.0` and one past a hundred `100:00.0` —
// so its width is measured with canvas `measureText` in the face
// `.tlClipDuration` actually renders, rather than guessed from a per-character
// average. Only where canvas is unavailable (jsdom) does the gate fall back to an
// estimate: 7px per character at 12px.
const CLIP_LABEL_RESERVE_PX = 50;
const CLIP_LABEL_FIXED_PX = 38;
const CLIP_LABEL_FALLBACK_CHAR_PX = 7;
// `.tlClipDuration` renders `500 12px/1.2 var(--font-body)`; canvas wants the
// same face without the line height, so the family comes from the token itself.
let durationMeasureCtx: CanvasRenderingContext2D | null | undefined;
function durationTextPx(text: string): number | undefined {
	if (durationMeasureCtx === undefined) {
		durationMeasureCtx = document.createElement("canvas").getContext("2d");
	}
	const ctx = durationMeasureCtx;
	if (ctx === null) return undefined;
	const family = getComputedStyle(document.documentElement).getPropertyValue("--font-body").trim();
	ctx.font = `500 12px ${family || "sans-serif"}`;
	// `.tlClipDuration` sets tabular numerals, which canvas cannot: there, every digit takes the
	// advance of the widest one, so count each digit at that width rather than at its own.
	let digitPx = 0;
	for (const digit of "0123456789") digitPx = Math.max(digitPx, ctx.measureText(digit).width);
	const others = text.replace(/[0-9]/g, "");
	return ctx.measureText(others).width + digitPx * (text.length - others.length);
}
function cardFitsDuration(cardPx: number, text: string): boolean {
	const textPx = durationTextPx(text) ?? text.length * CLIP_LABEL_FALLBACK_CHAR_PX;
	return cardPx >= CLIP_LABEL_RESERVE_PX + CLIP_LABEL_FIXED_PX + textPx;
}

const CLIP_GUTTER_PX = 6;

/** Enter and Space belong to the focused button. The shell's play/pause shortcut is Space on
 *  WINDOW and `preventDefault()`s it, which cancels the button's own activation, so the
 *  keystroke stops here, natively, and is not prevented. */
function keepActivationKey(e: ReactKeyboardEvent) {
	if (e.key === "Enter" || e.key === " ") e.nativeEvent.stopPropagation();
}
/**
 * Shortest region a resize may leave behind — the storage grid itself (regions
 * are `Math.round`ed to whole ms, and coalesceRegionsForRuler's epsilon is 1 ms),
 * so nothing rounds away to a zero-length row. It replaced a flat 0.2 s floor,
 * which quietly refused the last 200 ms of every trim however far you zoomed in.
 * How SHORT a region can be is a data question; how PRECISELY you can aim at one
 * is the zoom's business, and the two were conflated.
 */
const MIN_REGION_SEC = 0.001;

/**
 * How a pill's chrome is laid out at its current on-screen size.
 *
 * `compact` — the box is too narrow to hold handles AND a draggable body, so the
 * handles mount outside it (see PILL_MOVE_GAP_PX). Nothing is lost: move and
 * resize both stay reachable at any width and any zoom, the pill just stops
 * containing its own controls.
 *
 * `pxPerSec <= 0` means the panel hasn't been measured yet (first paint, jsdom).
 * Assume roomy rather than reflowing every pill's chrome for one frame.
 */
export function pillAffordance(
	durSec: number,
	pxPerSec: number,
): { compact: boolean; roomForLabel: boolean } {
	const widthPx = pxPerSec > 0 ? durSec * pxPerSec : Number.POSITIVE_INFINITY;
	const compact = widthPx < PILL_HANDLES_MIN_PX;
	// `!compact &&` is load-bearing, not belt-and-braces: .lanePillCompact turns
	// overflow visible (it has to, its handles hang outside the box), so a compact
	// pill that rendered a label would spill it across the lane with nothing to
	// clip it. Today PILL_CONTENT_MIN_PX > PILL_HANDLES_MIN_PX makes that
	// impossible; this makes it impossible whatever those two numbers become.
	return { compact, roomForLabel: !compact && widthPx >= PILL_CONTENT_MIN_PX };
}

// Ruler tick label. Precision follows the step: whole seconds read as a clean
// M:SS, but once the ruler is zoomed past one tick per second the fraction is
// the only thing telling two labels apart.
function fmtTick(sec: number, stepSec: number): string {
	if (!Number.isFinite(sec) || sec < 0) sec = 0;
	const digits = stepSec < 0.5 ? 2 : stepSec < 1 ? 1 : 0;
	const h = Math.floor(sec / 3600);
	const m = Math.floor((sec % 3600) / 60);
	const s = sec % 60;
	if (h > 0) {
		const mm = String(m).padStart(2, "0");
		const ss = String(Math.floor(s)).padStart(2, "0");
		return `${h}:${mm}:${ss}`;
	}
	if (digits > 0) {
		const [whole, frac] = s.toFixed(digits).split(".");
		return `${m}:${whole.padStart(2, "0")}.${frac}`;
	}
	return `${m}:${String(Math.round(s)).padStart(2, "0")}`;
}

interface RulerTick {
	sec: number;
	major: boolean;
}

interface PlayheadOverlayProps {
	/** Full timeline length in seconds — the denominator for the playhead's percentage. */
	totalSec: number;
	/** Live scrub position, when a drag is in flight. Takes precedence over the store. */
	overrideTimeSec: number | null;
	canvasStyle: React.CSSProperties;
	onPointerDown: (e: ReactPointerEvent) => void;
	playheadRef?: React.MutableRefObject<HTMLDivElement | null>;
}

/**
 * The playhead reads `currentTimeSec` from the store ITSELF instead of taking it
 * as a prop from V4Timeline.
 *
 * It is the only animated element on the timeline — everything around it (clips,
 * waveforms, ruler, lane pills) is static during playback. Threading the playhead
 * position down as a prop meant V4Timeline (and, above it, NewEditorShell) had to
 * re-render on every one of the ~60 store writes per second that playback
 * produces, just to move this one line: React had to render and commit the whole
 * editor before the playhead's DOM node moved, and any frame where that took
 * longer than ~16 ms showed up as visible playhead stutter.
 *
 * Subscribing here instead keeps the per-frame re-render confined to these three
 * nodes. `memo` then stops the surrounding timeline's own re-renders (zoom/pan,
 * clip edits) from re-rendering it for no reason.
 */
const PlayheadOverlay = memo(function PlayheadOverlay({
	totalSec,
	overrideTimeSec,
	canvasStyle,
	onPointerDown,
	playheadRef,
}: PlayheadOverlayProps) {
	const storeTimeSec = useProjectStore((s) => s.currentTimeSec);
	const pct = ((overrideTimeSec ?? storeTimeSec) / totalSec) * 100;
	return (
		<div className={styles.tlPlayheadLayer} aria-hidden>
			<div className={styles.tlCanvas} style={canvasStyle}>
				<div ref={playheadRef} className={styles.tlPlayhead} style={{ left: `${pct}%` }}>
					<span
						className={styles.tlPlayheadHead}
						style={{ pointerEvents: "auto", cursor: "grab" }}
						onPointerDown={(e) => {
							e.stopPropagation();
							onPointerDown(e);
						}}
					/>
				</div>
			</div>
		</div>
	);
});

/**
 * A clip's loudness as one smooth shape standing on its bottom edge, the way Screen Studio
 * draws it: a filled area under a line, not a row of 2px bars, which read as a barcode.
 *
 * `heights` are percentages of the wave box, one per sample, spread evenly across it. The
 * curve is a Catmull-Rom spline through the samples, so each sample is a point ON the line:
 * the shape is smoothed between them, never moved at them. Control points are held inside
 * the box, and a Bézier stays within its control points, so no stretch of it can poke above
 * full scale or below the baseline.
 */
function waveformPaths(heights: readonly number[]): { area: string; line: string } {
	const n = heights.length;
	const y = (i: number) => 100 - (heights[Math.min(n - 1, Math.max(0, i))] ?? 0);
	const r = (v: number) => Math.round(v * 100) / 100;
	const inBox = (v: number) => r(Math.min(100, Math.max(0, v)));
	let curve = "";
	for (let i = 0; i < n - 1; i++) {
		const c1 = inBox(y(i) + (y(i + 1) - y(i - 1)) / 6);
		const c2 = inBox(y(i + 1) - (y(i + 2) - y(i)) / 6);
		curve += ` C${r(i + 1 / 6)},${c1} ${r(i + 1 - 1 / 6)},${c2} ${i + 1},${r(y(i + 1))}`;
	}
	const start = `0,${r(y(0))}`;
	return {
		area: `M0,100 L${start}${curve} L${n - 1},100 Z`,
		line: `M${start}${curve}`,
	};
}

// The waveform inside a timeline clip. Derived from peaks data; each asset only
// decodes once. Renders nothing while decoding or if the source has no audio
// track, so the clip pill just shows its label until peaks arrive.
const ClipWaveform = memo(function ClipWaveform({
	videoUrl,
	assetDurationSec,
	sourceStartSec,
	sourceEndSec,
	gain,
}: {
	videoUrl: string | undefined;
	assetDurationSec: number | undefined;
	sourceStartSec: number;
	sourceEndSec: number;
	/** Linear output gain — `audioGainScalar(settings.audioGainDb)`, not the dB.
	 *  Passed in rather than read from the settings store here: this component is
	 *  memoised per clip, and subscribing each one to the document would re-render
	 *  every waveform on any edit at all. As a prop it busts the memo on a gain
	 *  change and on nothing else. */
	gain: number;
}) {
	// The duration is what tells `useAudioPeaks` whether this recording is small
	// enough to decode whole — the file's byte size does not, on compressed video.
	const peaks = useAudioPeaks(videoUrl, assetDurationSec);
	const levels = useMemo(() => {
		if (!peaks || peaks.length === 0 || !assetDurationSec) return null;
		const totalBlocks = Math.floor(peaks.length / 2);
		if (totalBlocks === 0) return null;
		const blocksPerSec = totalBlocks / assetDurationSec;
		const startBlock = Math.max(0, Math.floor(sourceStartSec * blocksPerSec));
		const endBlock = Math.min(totalBlocks, Math.ceil(sourceEndSec * blocksPerSec));
		const rangeBlocks = Math.max(1, endBlock - startBlock);
		// One sample per ~120ms of clip duration — dense enough to follow speech —
		// but capped so a long recording doesn't build a path of thousands of
		// points for a clip that is at most ~the timeline width on screen.
		const sampleCount = Math.min(
			400,
			Math.max(20, Math.round((sourceEndSec - sourceStartSec) * 8)),
		);
		const result: number[] = [];
		for (let i = 0; i < sampleCount; i++) {
			const blockStart = startBlock + Math.floor((i / sampleCount) * rangeBlocks);
			const blockEnd = Math.max(
				blockStart + 1,
				startBlock + Math.floor(((i + 1) / sampleCount) * rangeBlocks),
			);
			let amp = 0;
			for (let b = blockStart; b < blockEnd && b < totalBlocks; b++) {
				const lo = Math.abs(peaks[b * 2] ?? 0);
				const hi = Math.abs(peaks[b * 2 + 1] ?? 0);
				amp = Math.max(amp, lo, hi);
			}
			result.push(amp);
		}
		return result;
	}, [peaks, assetDurationSec, sourceStartSec, sourceEndSec]);

	if (!levels) return null;
	// Gain is applied HERE and not inside the memo above, which scans the whole
	// asset's blocks: a slider drag fires one setLive per pointer move, so this
	// keeps a tick at one multiply per sample instead of re-folding the peaks.
	//
	// Clamped because `finish_audio` clamps: it does `(sample * trim).clamp(-1, 1)`
	// per sample, and a sample here is `max|sample|` over its bucket. Gain is positive
	// and clamping is monotonic, so `clamp(max(|s|) * g)` IS the peak of the gained,
	// clipped signal — the shape is exact at every sample, not an impression.
	//
	// The 8% floor is deliberately NOT scaled: it exists so an empty clip still
	// reads as a clip, and it is not amplitude.
	const { area, line } = waveformPaths(
		levels.map((h) => Math.max(8, Math.round(Math.min(1, h * gain) * 100))),
	);
	return (
		<svg
			aria-hidden
			className={styles.tlWave}
			viewBox={`0 0 ${levels.length - 1} 100`}
			preserveAspectRatio="none"
		>
			<path className={styles.tlWaveArea} d={area} />
			<path className={styles.tlWaveLine} d={line} />
		</svg>
	);
});

// One imported audio track on its lane (issue #350). Grab the body to move it,
// the edge handles to trim (left = in-point, which moves the head too; right =
// out-point). The waveform reuses ClipWaveform (its `.tlWave` stands on the pill's
// bottom edge, behind the label, just as it does inside a clip), windowed to the
// track's trim and scaled by the track's own gain. `leftPct`/`widthPct` are
// precomputed by the parent — during a drag they carry the live preview geometry
// — so this stays memoisable: a doc edit that doesn't touch this track, and a
// drag on another one, won't re-render it.
const AudioLanePill = memo(function AudioLanePill({
	track,
	url,
	assetDurationSec,
	leftPct,
	widthPct,
	sourceStartSec,
	sourceEndSec,
	spanSec,
	loopWindowSec,
	row,
	rowHeight,
	selected,
	onStartDrag,
	onSelect,
	label,
	slipHint,
	slipArmed,
	outputGain,
	ghost,
}: {
	track: AxcutAudioTrack;
	url: string | undefined;
	assetDurationSec: number | undefined;
	leftPct: number;
	widthPct: number;
	/** The slice of the source the pill is showing — the track's offset and its
	 *  span, or the live window while an edge is being dragged. */
	sourceStartSec: number;
	sourceEndSec: number;
	/** The pill's own length in seconds, and how much source one repeat plays —
	 *  together they say where the loop boundaries fall. */
	spanSec: number;
	loopWindowSec: number;
	/** Which row of the audio lane this pill occupies, and how tall a row is —
	 *  overlapping tracks are stacked rather than drawn on top of each other. */
	row: number;
	rowHeight: number;
	selected: boolean;
	onStartDrag: (e: ReactPointerEvent, track: AxcutAudioTrack, mode: "move" | "l" | "r") => void;
	onSelect: (id: string) => void;
	label: string;
	/** Appended to the pill's tooltip. A modifier is never discoverable on its own —
	 *  you either read it somewhere or you never find it — and the tooltip is where a
	 *  user already looks to ask what a thing does. */
	slipHint: string;
	/** True while Alt is held, so the pill can say the next drag will slip rather than
	 *  move. Confirms the modifier; the tooltip is what teaches it. */
	slipArmed: boolean;
	/** Linear project output gain, applied on top of the track gain — the mixer
	 *  applies both, so the bars must too or they under-read the exported level. */
	outputGain: number;
	/** Where the rest of the file sits around the pill, as percentages of the canvas
	 *  and the source window it covers. Absent when there is nothing to show. */
	ghost?: {
		leftPct: number;
		widthPct: number;
		sourceStartSec: number;
		sourceEndSec: number;
	} | null;
}) {
	const duration = assetDurationSec ?? track.durationSec;
	return (
		<>
			{/* The rest of the tape, dimmed and unclickable, behind the pill — so the pill
			    reads as a window onto it and an edge drag shows what is still available on
			    each side before it hits the stop. Same height and row as the pill: a ghost
			    that does not line up reads as a separate object sitting behind it. */}
			{ghost ? (
				<div
					aria-hidden
					className={styles.lanePillGhost}
					style={{
						left: `${ghost.leftPct}%`,
						width: `${ghost.widthPct}%`,
						top: AUDIO_LANE_PAD_PX + row * rowHeight,
						height: AUDIO_ROW_HEIGHT_PX,
					}}
				>
					<ClipWaveform
						videoUrl={url}
						assetDurationSec={duration}
						sourceStartSec={ghost.sourceStartSec}
						sourceEndSec={ghost.sourceEndSec}
						gain={audioGainScalar(track.gainDb) * outputGain}
					/>
				</div>
			) : null}
			<div
				role="button"
				tabIndex={0}
				className={`${styles.lanePill} ${styles.laneAudio}${
					selected ? ` ${styles.lanePillSel}` : ""
				}${slipArmed ? ` ${styles.laneAudioSlip}` : ""}`}
				style={{
					left: `${leftPct}%`,
					width: `${widthPct}%`,
					minWidth: 3,
					top: AUDIO_LANE_PAD_PX + row * rowHeight,
					height: AUDIO_ROW_HEIGHT_PX,
				}}
				// Body drag moves the track; it also selects and stops the .tlTracks scrub.
				onPointerDown={(e) => onStartDrag(e, track, "move")}
				onKeyDown={(e) => {
					if (e.key !== "Enter" && e.key !== " ") return;
					e.preventDefault();
					// The shell binds Space to play/pause on `window`, above React's root, so
					// stopping only the synthetic event selects the pill and toggles playback in
					// the same keystroke. Same fix as the region pill below.
					e.nativeEvent.stopPropagation();
					onSelect(track.id);
				}}
				title={`${label}\n${slipHint}`}
			>
				<span
					className={styles.lanePillHandle}
					style={{ left: 0 }}
					onPointerDown={(e) => onStartDrag(e, track, "l")}
				/>
				<ClipWaveform
					videoUrl={url}
					assetDurationSec={duration}
					sourceStartSec={sourceStartSec}
					sourceEndSec={sourceEndSec}
					// Track gain AND the project output gain — `finish_audio` applies both and
					// clamps, so scaling by the track gain alone under-read a boosted output.
					gain={audioGainScalar(track.gainDb) * outputGain}
				/>
				{/* Where the file starts over, so a looping bed reads as one deliberate
			    repeat rather than a mystery. Only drawn when the pill actually
			    outruns its source — otherwise there is nothing to repeat. */}
				{track.loop && loopWindowSec > 0
					? Array.from(
							{ length: Math.min(200, Math.ceil(spanSec / loopWindowSec) - 1) },
							(_, i) => (
								<span
									key={`loop-${i + 1}`}
									data-testid="audio-loop-mark"
									className={styles.laneLoopMark}
									style={{ left: `${(((i + 1) * loopWindowSec) / spanSec) * 100}%` }}
								/>
							),
						)
					: null}
				<span className={styles.laneAudioLabel}>
					<Music size={12} />
					{label}
				</span>
				<span
					className={styles.lanePillHandle}
					style={{ right: 0 }}
					onPointerDown={(e) => onStartDrag(e, track, "r")}
				/>
			</div>
		</>
	);
});

interface LanePill {
	id: string;
	kind: "annotation" | "speed" | "trim" | "zoom" | "cameraFullscreen" | "shaderEffect";
	start: number;
	end: number;
	label: string;
	/** Underlying row ids this pill represents — >1 for a coalesced trim group. */
	sourceIds: string[];
	layer?: number;
	stackOrder?: number;
}

function LayoutChangeMenu({ tl, onClose }: { tl: TimelineApi; onClose: () => void }) {
	const t = useScopedT("timeline");
	const time = useProjectStore((s) => s.currentTimeSec);
	const active = tl.layoutSegments.find((r) => time >= r.start && time < r.end);
	const clip = tl.clips.find((c) => time >= c.timelineStartSec && time < c.timelineEndSec);
	const camera = tl.assets.find((a) => a.id === clip?.assetId)?.cameraTrack;
	return (
		<div>
			<div style={{ marginBottom: 10, fontSize: 12 }}>
				{t("layouts.fromUntil", { start: formatSec(time), end: formatSec(active?.end ?? time) })}
			</div>
			<LayoutPicker
				value={active?.member.preset ?? "picture-in-picture"}
				hasCamera={Boolean(camera?.visible && camera.sourcePath)}
				onSelect={(preset) => {
					void tl.addLayoutChange(preset, time);
					onClose();
				}}
			/>
		</div>
	);
}

export function V4Timeline({
	tl,
	setCurrentTime,
	variant = "edit",
	onDropAsset,
	videoSources = [],
	playing,
	onTogglePlay,
	onEditClip,
	onAddVoiceover,
	onAnnotationRowCountChange,
}: {
	tl: TimelineApi;
	setCurrentTime: (sec: number) => void;
	variant?: "edit" | "media";
	onDropAsset?: (assetId: string) => Promise<void>;
	videoSources?: VideoSource[];
	playing: boolean;
	onTogglePlay: () => void;
	/** Opens the (now single, shell-level) EditClipModal for this clip —
	 * trim in/out and crop both live there per-clip. */
	onEditClip: (clip: AxcutClip) => void;
	/** Opens the voiceover recorder. Shell-level like the clip editor: the
	 *  dialog owns the microphone and the shell owns the transport. */
	onAddVoiceover: () => void;
	/** Exact rendered annotation row count, including the current drag preview. */
	onAnnotationRowCountChange?: (rowCount: number) => void;
}) {
	const t = useScopedT("timeline");
	const ts = useScopedT("settings");
	// The live bindings, not the defaults: these keys are remappable, and a menu
	// that taught the wrong one would be worse than teaching none.
	const { shortcuts, isMac } = useShortcuts();
	// Wheel zoom/pan listens on the whole pane (toolbar down through the nav bar),
	// not just the lanes — a user scrolling over the ruler or the hint labels
	// expects the same zoom/pan the lanes give, not silence.
	const panelRef = useRef<HTMLDivElement | null>(null);
	const tracksRef = useRef<HTMLDivElement | null>(null);
	// The transformed canvas is the true timeline coordinate frame — clips, pills
	// and the playhead are all positioned inside it. Time↔x math must measure THIS
	// (not the padded/scrollbar-inset tracks box), else clicks map to the wrong
	// time and the mapping drifts as the scrollbar appears/disappears.
	const canvasRef = useRef<HTMLDivElement | null>(null);
	const navRef = useRef<HTMLDivElement | null>(null);
	const clipsRef = useRef<HTMLDivElement | null>(null);
	// True while a clip pointer-drag actually moved the pointer past the
	// threshold, so the click fired on pointerup selects nothing (a drag is
	// not a select). Reset at the start of each new clip pointerdown.
	const didClipDragRef = useRef(false);
	const [nav, setNav] = useState({ start: 0, end: 1 });
	// On-screen width of one full (unzoomed) timeline, in px. The ruler needs it
	// to pick a tick step that reads at THIS panel size — a step that looks right
	// on a wide window crams into an unreadable smear on a narrow one.
	const [viewportWidthPx, setViewportWidthPx] = useState(0);
	const [dragOver, setDragOver] = useState(false);
	const [snapPct, setSnapPct] = useState<number | null>(null);
	// Live clip-reorder drag: the dragged clip follows the pointer directly
	// (pointerDeltaX, no transition) while every clip between its origin and
	// live target slides sideways by the dragged clip's own width+gap (with
	// a CSS transition) to open a visible gap at the drop point — a manual
	// FLIP-style reorder rather than a static insertion line.
	const [clipDrag, setClipDrag] = useState<{
		id: string;
		from: number;
		target: number;
		pointerDeltaX: number;
		shiftPx: number;
	} | null>(null);
	const { settings, set: setSettings } = useEditorSettings();

	const [autoEnhanceOpen, setAutoEnhanceOpen] = useState(false);
	const [audioMenuOpen, setAudioMenuOpen] = useState(false);
	const [layoutOpen, setLayoutOpen] = useState(false);
	// Subscribe to availability, not the time itself: the full timeline must not
	// re-render on every playhead tick while it stays inside the same footage.
	const canChangeLayout = useProjectStore(
		(s) =>
			variant === "edit" &&
			tl.hasDoc &&
			tl.clips.some(
				(clip) =>
					s.currentTimeSec >= clip.timelineStartSec && s.currentTimeSec < clip.timelineEndSec,
			),
	);
	useEffect(() => {
		if (!canChangeLayout) {
			setLayoutOpen(false);
			return;
		}
		const open = () => setLayoutOpen(true);
		window.addEventListener("openscreen:change-layout", open);
		return () => window.removeEventListener("openscreen:change-layout", open);
	}, [canChangeLayout]);
	const [autoBusy, setAutoBusy] = useState(false);
	// The AI cut pass reads the transcript, and the transcript is produced in the
	// background (see transcriptionStore). Until it is there, the entry says why
	// rather than handing the agent a prompt it cannot honour — the failure mode
	// that made this button the wrong first click for a new user.
	const transcriptGate = useTimelineTranscriptGate();
	const smartCutsBlocked = transcriptGate.state !== "ready";
	const smartCutsHint =
		transcriptGate.state === "pending"
			? t("toolbar.smartCutsWaiting")
			: transcriptGate.state === "ready"
				? t("toolbar.smartZoomsAndCutsHint")
				: transcriptGate.reason === "no-audio"
					? t("toolbar.smartCutsNoAudio")
					: transcriptGate.reason === "no-speech"
						? t("toolbar.smartCutsNoSpeech")
						: transcriptGate.reason === "failed"
							? t("toolbar.smartCutsFailed")
							: t("toolbar.smartCutsNeedsTranscript");

	const clips = tl.clips;
	// The pauses added words created, placed on the ruler. Everything below measures the
	// EXPANDED ruler — stored clip geometry plus the time those pauses add — because that
	// is the film's real length and the one the playhead runs along. Stored geometry is
	const total = useMemo(
		() =>
			Math.max(
				1,
				clips.reduce((m, c) => Math.max(m, c.timelineEndSec), 0),
			),
		[clips],
	);
	const pctOf = useCallback((sec: number) => (sec / total) * 100, [total]);
	/** Stored raw seconds → a percentage of the expanded ruler. */
	const pctAt = pctOf;
	const showLanes = variant === "edit";

	// The visible fraction of the timeline, and what one second is worth on screen
	// at that zoom. Every screen-space rule below — ruler step, pill affordances,
	// snap radius — goes through this instead of being written as a fraction of
	// `total`, which is a duration in disguise and so scales with the recording.
	const navSpan = Math.max(0.02, nav.end - nav.start);
	const pxPerSec = viewportWidthPx / navSpan / total;
	// Publish the scale so the keyboard shortcuts (NewEditorShell) size a new
	// region exactly like the buttons below do — `nav` never leaves this
	// component, so without this they fall back to a flat default and a pill
	// created with `Z` comes out invisible on a long recording.
	useEffect(() => {
		setTimelineScale(pxPerSec);
	}, [pxPerSec]);

	// ── region lanes ────────────────────────────────────────────────
	// zoom/speed/annotation: one pill per row, never coalesced — each carries
	// distinct per-instance content (depth/focus, speed value, text) that two
	// touching-but-different regions must not silently merge into one.
	// Pills follow the universal merge rule (timelineMap): regions of the same kind whose
	// PROPERTIES are equal and whose spans touch render as ONE pill, however they came to be
	// adjacent. Annotations can overlap on separate tracks; other modifiers repel on edit.
	// Trims obey the same rule with an empty property set, so they always merge.
	const annPills: LanePill[] = useMemo(
		() =>
			annotationTrackPills(tl.annotationRegions).map((p) => ({
				id: p.id,
				kind: "annotation" as const,
				start: p.start,
				end: p.end,
				label:
					(p.member.type === "text" ? p.member.content || p.member.textContent : "")?.trim() ||
					t("toolbar.newAnnotation"),
				sourceIds: p.ids,
				layer: p.layer,
				stackOrder: p.stackOrder,
			})),
		[tl.annotationRegions, t],
	);
	const savedAnnotationRows = useMemo(() => packRegionRows(annPills), [annPills]);

	const speedRuns = coalesceRegionsForRuler(tl.speedRegions);
	const speedPills: LanePill[] = speedRuns.map((p) => ({
		id: p.ids[0],
		kind: "speed",
		start: p.start,
		end: p.end,
		label: `${(p.member as { speed?: number }).speed ?? 1.5}×`,
		sourceIds: p.ids,
	}));
	const effectNames = new Map(tl.shaderEffects.map((effect) => [effect.id, effect.name]));
	const shaderEffectPills: LanePill[] = coalesceRegionsForRuler(tl.shaderEffectRanges).map((p) => ({
		id: p.ids[0],
		kind: "shaderEffect",
		start: p.start,
		end: p.end,
		label: effectNames.get(p.member.effectId) ?? "",
		sourceIds: p.ids,
	}));
	const zoomRuns = coalesceRegionsForRuler(tl.zoomRegions);
	const zoomPills: LanePill[] = zoomRuns.map((p) => ({
		id: p.ids[0],
		kind: "zoom",
		start: p.start,
		end: p.end,
		// Matches RightPanelStack's effectiveZoomScale: a custom scale (from the
		// slider) overrides the depth preset; otherwise show the depth's actual
		// preset value, not a fabricated linear approximation of it.
		label: `${(p.member.customScale ?? ZOOM_DEPTH_SCALES[p.member.depth]).toFixed(2)}×`,
		sourceIds: p.ids,
	}));

	// trims: content-free (no per-instance text/settings), so touching rows —
	// inevitable once a trim is ventilated across a clip boundary — are
	// coalesced into one pill. This is what makes growing a trim across a
	// junction look like one continuously-growing pill instead of visibly
	// splitting, aligning trims with how zoom/speed/annotation already behave.
	const trimPills: LanePill[] = coalescedTrimGroups(tl.trimRanges, clips).map((g) => ({
		id: g.ids[0],
		kind: "trim",
		start: g.start,
		end: g.end,
		label: formatSec(g.end - g.start),
		sourceIds: g.ids,
	}));

	// Ruler ticks are chosen from what is actually ON SCREEN, not from the clip
	// length: the canvas is widened by 1/navSpan, so the same recording shows one
	// label per 30s zoomed out and one per tenth of a second zoomed in. The step
	// is the first "nice" one whose on-screen gap clears MIN_LABEL_GAP_PX, which
	// is why the labels never collide however narrow the panel gets.
	const rulerTicks = useMemo((): { step: number; ticks: RulerTick[] } => {
		if (!Number.isFinite(pxPerSec) || pxPerSec <= 0) return { step: 1, ticks: [] };
		const step =
			TICK_STEPS_SEC.find((s) => s * pxPerSec >= MIN_LABEL_GAP_PX) ??
			TICK_STEPS_SEC[TICK_STEPS_SEC.length - 1];
		const minor = step / MINOR_PER_MAJOR;
		// Emit the visible window only (plus a step of margin so a tick never pops
		// in at the edge): at a 50× zoom the full timeline would otherwise be
		// thousands of off-screen nodes re-rendered on every pan.
		const from = Math.max(0, nav.start * total - step);
		const to = Math.min(total, nav.end * total + step);
		const ticks: RulerTick[] = [];
		for (let i = Math.ceil(from / minor - 1e-6); i * minor <= to + 1e-6; i++) {
			ticks.push({ sec: i * minor, major: i % MINOR_PER_MAJOR === 0 });
		}
		return { step, ticks };
	}, [total, nav.start, nav.end, pxPerSec]);

	// Live scrub position. The store write behind it is rAF-throttled (see
	// seekToClientX), so this keeps the playhead and the timecode pinned to the
	// pointer for the frame the store hasn't caught up on yet. Handed down as an
	// override to the two components that read the playhead from the store.
	const [scrubbingTimeSec, setScrubbingTimeSec] = useState<number | null>(null);
	const rafSeekRef = useRef<number>(0);
	const pendingSeekTimeRef = useRef<number | null>(null);

	// ── interactions ────────────────────────────────────────────────
	const playheadElRef = useRef<HTMLDivElement | null>(null);

	// Seek timeline position from a clientX pointer position.
	const seekToClientX = useCallback(
		(clientX: number, isImmediate = false) => {
			// Measure the canvas (the zoomed timeline frame): (clientX - left)/width
			// is the fraction along the FULL timeline under the cursor, so it stays
			// correct under zoom/pan and is unaffected by padding or the scrollbar.
			const el = canvasRef.current;
			if (!el) return;
			const r = el.getBoundingClientRect();
			const pct = Math.min(1, Math.max(0, (clientX - r.left) / r.width));
			const targetTime = pct * total;

			// Direct DOM playhead update (0ms latency, zero React re-render overhead)
			if (playheadElRef.current) {
				playheadElRef.current.style.left = `${pct * 100}%`;
			}

			pendingSeekTimeRef.current = targetTime;

			if (isImmediate) {
				if (rafSeekRef.current !== 0) {
					cancelAnimationFrame(rafSeekRef.current);
					rafSeekRef.current = 0;
				}
				setScrubbingTimeSec(targetTime);
				setCurrentTime(targetTime);
				return;
			}

			// Throttled React state + store update / D3D seek via rAF to avoid re-render and IPC floods.
			if (rafSeekRef.current === 0) {
				rafSeekRef.current = requestAnimationFrame(() => {
					rafSeekRef.current = 0;
					if (pendingSeekTimeRef.current !== null) {
						setScrubbingTimeSec(pendingSeekTimeRef.current);
						setCurrentTime(pendingSeekTimeRef.current);
					}
				});
			}
		},
		[setCurrentTime, total],
	);

	// Mousedown anywhere on the empty timeline (ruler, lanes background, or
	// the playhead head itself) seeks immediately AND arms a scrub drag —
	// a single pointerdown→pointermove→pointerup replaces the old
	// click-only seek, and doubles as the playhead's drag handle since
	// dragging from its exact position is the same math as dragging from
	// anywhere else. Also clears any region selection, closing the
	// selected-element settings pane (FloatingInspector) the way clicking
	// away from a selected element is expected to.
	const startScrub = useCallback(
		(e: ReactPointerEvent) => {
			if (e.button !== 0) return;
			// Media has no playhead rendered, so there is nothing to scrub. Guarded
			// here rather than at the three call sites: seeking an invisible cursor
			// would still move `currentTimeSec`, i.e. silently reposition the Edit
			// tab's preview from a screen that shows no time at all.
			if (!showLanes) return;
			const target = e.target as HTMLElement;
			if (target.closest("[data-clip-id]") || target.closest(`.${styles.lanePill}`)) return;
			tl.clearSelection();
			seekToClientX(e.clientX, true);
			// Sonde de fluidité (diagnostic) : marque la fenêtre de drag pour que les
			// intervalles rAF mesurés pendant le scrub soient comptés à part.
			setUiProbeScrubbing(true);
			const move = (ev: PointerEvent) => seekToClientX(ev.clientX);
			const up = () => {
				setUiProbeScrubbing(false);
				window.removeEventListener("pointermove", move);
				window.removeEventListener("pointerup", up);
				if (rafSeekRef.current !== 0) {
					cancelAnimationFrame(rafSeekRef.current);
					rafSeekRef.current = 0;
				}
				if (pendingSeekTimeRef.current !== null) {
					setCurrentTime(pendingSeekTimeRef.current);
					pendingSeekTimeRef.current = null;
				}
				setScrubbingTimeSec(null);
			};
			window.addEventListener("pointermove", move);
			window.addEventListener("pointerup", up);
		},
		[seekToClientX, tl, setCurrentTime, showLanes],
	);

	const [activePillDrag, setActivePillDrag] = useState<{
		id: string;
		kind: LanePill["kind"];
		start: number;
		end: number;
		drop?: AnnotationTrackDrop;
		layers?: Map<string, number>;
	} | null>(null);
	const activePillDragRef = useRef<{
		id: string;
		kind: LanePill["kind"];
		start: number;
		end: number;
		drop?: AnnotationTrackDrop;
		layers?: Map<string, number>;
	} | null>(null);

	// A merged pill can be several regions that merely match (#1017), and an edit must reach
	// only the one the user pointed at, so the pill splits: a click at `atSec` selects the last
	// region starting at or before it. Without a pointer (keyboard), the pill's first region.
	// The store still edits every fragment of that region across a clip junction together.
	// Returns the id selected.
	const selectPill = useCallback(
		(pill: LanePill, additive: boolean, atSec?: number): string => {
			const regions: Record<LanePill["kind"], ReadonlyArray<{ id: string; startMs: number }>> = {
				annotation: tl.annotationRegions,
				speed: tl.speedRegions,
				zoom: tl.zoomRegions,
				cameraFullscreen: tl.cameraFullscreenRegions,
				shaderEffect: tl.shaderEffectRanges,
				// Nothing to edit on a trim but its span, and a span edit moves the whole pill.
				trim: [],
			};
			const atMs = (atSec ?? Number.NaN) * 1000;
			const [pointed] = regions[pill.kind]
				.filter((r) => pill.sourceIds.includes(r.id) && r.startMs <= atMs)
				.sort((a, b) => b.startMs - a.startMs);
			const id = pointed?.id ?? pill.id;
			tl.selectRegion(pill.kind, id, { additive });
			return id;
		},
		[tl],
	);

	// Drag a lane pill to move it (mode "move", keeps duration) or resize one
	// edge (mode "l"/"r"). Zoom/speed/annotation are timeline-ms; trims map
	// back to source-seconds through their carrying clip.
	const startPillDrag = useCallback(
		(e: ReactPointerEvent, pill: LanePill, dragMode: "move" | "l" | "r") => {
			e.preventDefault();
			e.stopPropagation();
			// Scale drag deltas against the canvas (full zoomed timeline) width, so a
			// drag tracks the cursor exactly regardless of padding, scrollbar or zoom.
			const el = canvasRef.current;
			if (!el) return;
			const r = el.getBoundingClientRect();
			// A move rebuilds the pill as one region that keeps this id, so the selection survives.
			const grabbed = selectPill(pill, e.shiftKey, ((e.clientX - r.left) / r.width) * total);
			const startX = e.clientX;
			const startY = e.clientY;
			const originalRow = savedAnnotationRows.rowOf.get(pill.id) ?? 0;
			const dur = pill.end - pill.start;
			// A trim can span several clips; it's stored as one source-time entry per
			// covered clip. `trimOwned` are the entry ids this drag controls — seeded
			// from every row the grabbed (possibly already-coalesced) pill represents,
			// then grows as the span reaches into more clips (fresh ids appended).
			// `trimOwned` only grows; ids past the current fragment count are handed
			// to `setTrimEntries` as `dropIds` so a shrinking span deletes the entries
			// it no longer needs.
			const trimOwned: string[] = [...pill.sourceIds];
			// Snap targets: clip boundaries + timeline ends. Within PILL_SNAP_PX of
			// one on screen, an edge snaps and a vertical guide is shown.
			// The radius is in PIXELS: as a fraction of total (it was 1.2%) it was a
			// 21-second magnet on a 30-minute project, so a pill dragged anywhere near
			// a junction jumped to it however far you zoomed in to place it precisely.
			const snapTargets = [
				0,
				total,
				...clips.map((c) => c.timelineStartSec),
				...clips.map((c) => c.timelineEndSec),
			];
			// 0 = no snapping at all while the panel is unmeasured (first paint):
			// better to drop the edge exactly where it was released than to move it
			// by a radius computed from a width we do not have.
			const snapThresh = pxPerSec > 0 ? PILL_SNAP_PX / pxPerSec : 0;
			const snap = (v: number): number => {
				let best = v;
				let bestD = snapThresh;
				for (const t of snapTargets) {
					const d = Math.abs(t - v);
					if (d < bestD) {
						bestD = d;
						best = t;
					}
				}
				setSnapPct(best === v ? null : (best / total) * 100);
				return best;
			};
			const apply = async (
				start: number,
				end: number,
				drop?: AnnotationTrackDrop,
			): Promise<void> => {
				const s = Math.max(0, Math.min(end - MIN_REGION_SEC, start));
				const en = Math.min(total, Math.max(s + MIN_REGION_SEC, end));
				if (pill.kind === "zoom") await tl.updateZoomSpan(grabbed, s * 1000, en * 1000);
				else if (pill.kind === "speed") await tl.updateSpeedSpan(grabbed, s * 1000, en * 1000);
				else if (pill.kind === "annotation") {
					if (drop === undefined) await tl.updateAnnotationSpan(grabbed, s * 1000, en * 1000);
					else await tl.updateAnnotationSpan(grabbed, s * 1000, en * 1000, drop);
				} else if (pill.kind === "cameraFullscreen")
					await tl.updateCameraFullscreenSpan(grabbed, s * 1000, en * 1000);
				else if (pill.kind === "shaderEffect")
					await tl.updateShaderEffectSpan(grabbed, s * 1000, en * 1000);
				else {
					// Trims are stored in source-time per asset but manipulated on the
					// timeline like every other pill. Ventilate the new span across the
					// clips it covers (one source range per clip) — the same primitive
					// zoom/speed/annotation use on reorder, so trims can now be grown
					// across a clip boundary just like a zoom.
					let ranges = ventilateTimelineSpanToTrims(s, en, clips);
					if (ranges.length === 0) {
						// Span sits in a gap / past the end: fall back to the nearest clip.
						const resolved = resolveTimelineSpanToTrim(s, en, clips);
						if (!resolved) return;
						ranges = [resolved];
					}
					// Grow the owned-id list to cover every fragment, keeping ids stable
					// across frames; ids past the current fragment count are dropped.
					while (trimOwned.length < ranges.length) trimOwned.push(createId("trim"));
					const entries = ranges.map((rng, i) => ({ id: trimOwned[i], ...rng }));
					const dropIds = trimOwned.slice(ranges.length);
					await tl.setTrimEntries(entries, dropIds);
				}
			};
			const move = (ev: PointerEvent) => {
				const dxSec = ((ev.clientX - startX) / r.width) * total;
				let ns = pill.start;
				let ne = pill.end;
				if (dragMode === "move") {
					ns = Math.max(0, Math.min(total - dur, snap(pill.start + dxSec)));
					ne = ns + dur;
				} else if (dragMode === "l") {
					ns = Math.max(0, Math.min(pill.end - MIN_REGION_SEC, snap(pill.start + dxSec)));
					ne = pill.end;
				} else {
					ns = pill.start;
					ne = Math.min(total, Math.max(pill.start + MIN_REGION_SEC, snap(pill.end + dxSec)));
				}
				let drop: AnnotationTrackDrop | undefined;
				if (pill.kind === "annotation" && dragMode === "move") {
					const rowDelta = Math.round((ev.clientY - startY) / REGION_ROW_STEP_PX);
					if (rowDelta !== 0)
						drop = {
							row: originalRow + rowDelta,
							direction: rowDelta < 0 ? "up" : "down",
						};
				}
				const layers = drop
					? annotationDropLayers(
							annPills,
							pill.id,
							{ start: ns, end: ne },
							drop,
							savedAnnotationRows,
						)
					: undefined;
				const nextState = { id: pill.id, kind: pill.kind, start: ns, end: ne, drop, layers };
				activePillDragRef.current = nextState;
				setActivePillDrag(nextState);
			};
			const up = () => {
				setSnapPct(null);
				window.removeEventListener("pointermove", move);
				window.removeEventListener("pointerup", up);
				const finalDrag = activePillDragRef.current;
				if (finalDrag) {
					void apply(finalDrag.start, finalDrag.end, finalDrag.drop).finally(() => {
						if (activePillDragRef.current === finalDrag) {
							activePillDragRef.current = null;
							setActivePillDrag(null);
						}
					});
				} else {
					activePillDragRef.current = null;
					setActivePillDrag(null);
				}
			};
			window.addEventListener("pointermove", move);
			window.addEventListener("pointerup", up);
		},
		[tl, selectPill, total, clips, pxPerSec, annPills, savedAnnotationRows],
	);

	// Live preview geometry for an audio track being dragged (issue #350), the
	// audio-lane counterpart of activePillDrag — see startAudioDrag. Times are
	// output-timeline (start) and source (trimStart/trimEnd) seconds.
	const [audioDrag, setAudioDrag] = useState<{
		id: string;
		start: number;
		trimStart: number;
		trimEnd: number;
	} | null>(null);
	const audioDragRef = useRef<typeof audioDrag>(null);
	/** `in -> out / length` pinned to the pointer while an audio edge is pulled or the
	 *  media is slipped under the pill. Rendered at the component root: the lane sits
	 *  inside the zoomed canvas transform, which would scale a chip placed in it. */
	const [audioDragTip, setAudioDragTip] = useState<{
		x: number;
		y: number;
		inSec: number;
		outSec: number;
		durationSec: number;
	} | null>(null);
	// The user-visible tracks and their lane rows. Packed from the STORED spans,
	// not the live drag geometry: a pill that changed rows halfway through a drag
	// would jump out from under the pointer.
	const audioPills = useMemo(() => collapseTracksToPills(tl.audioTracks), [tl.audioTracks]);
	// One row per KIND, and the packer unchanged INSIDE each kind (issue #560). Placement
	// now clamps same-kind pills apart, so intra-kind packing is the legacy escape hatch —
	// it keeps a document written before that rule legible instead of stacking its pills on
	// top of each other. A kind with no tracks takes no row, so the common single-bed
	// project stays exactly as tall as it was.
	const audioRows = useMemo(() => {
		const voice = audioPills.filter((p) => p.kind === "voiceover");
		const music = audioPills.filter((p) => p.kind !== "voiceover");
		const voiceRows = packAudioTrackRows(voice);
		const musicRows = packAudioTrackRows(music);
		const rowOf = new Map<string, number>();
		const base = voice.length > 0 ? voiceRows.rowCount : 0;
		for (const pill of voice) rowOf.set(pill.id, voiceRows.rowOf.get(pill.id) ?? 0);
		for (const pill of music) rowOf.set(pill.id, base + (musicRows.rowOf.get(pill.id) ?? 0));
		return {
			rowOf,
			rowCount: Math.max(1, base + (music.length > 0 ? musicRows.rowCount : 0)),
		};
	}, [audioPills]);

	// Whether Alt is held, so an audio pill can show that the next drag slips. Window
	// listeners rather than per-pill handlers: the key is pressed BEFORE the pointer
	// reaches the pill as often as after it, so a pill-local listener would miss the
	// case the affordance exists for. `blur` clears it because a modifier held while
	// the window loses focus never sends its keyup.
	const [slipArmed, setSlipArmed] = useState(false);
	useEffect(() => {
		const sync = (e: KeyboardEvent) => setSlipArmed(e.altKey);
		const clear = () => setSlipArmed(false);
		window.addEventListener("keydown", sync);
		window.addEventListener("keyup", sync);
		window.addEventListener("blur", clear);
		return () => {
			window.removeEventListener("keydown", sync);
			window.removeEventListener("keyup", sync);
			window.removeEventListener("blur", clear);
		};
	}, []);

	// Drag an audio track: "move" slides the head (both edges together), "l"/"r"
	// trim the in/out points. The left edge moves the head AND the in-point so the
	// right edge stays put — hence the single placeAudioTrack commit on release.
	// Like the region pills, the preview is local state and the document is written
	// once, on pointerup.
	const startAudioDrag = useCallback(
		(e: ReactPointerEvent, track: AxcutAudioTrack, mode: "move" | "l" | "r") => {
			e.preventDefault();
			e.stopPropagation();
			tl.selectAudioTrack(track.id);
			// Start clean: a previous drag's commit may still be in flight (its ref is
			// cleared only when `placeAudioTrack` resolves). Without this, a plain
			// select-click that never moves would let `up` read that stale value and
			// re-commit the old drag — a redundant write and an extra undo step.
			audioDragRef.current = null;
			const el = canvasRef.current;
			if (!el) return;
			const r = el.getBoundingClientRect();
			const startX = e.clientX;
			const asset = tl.assets.find((a) => a.id === track.assetId);
			// The source length caps the out-point; fall back to the current window when
			// the file hasn't been probed (durationSec 0), so a drag can't extend past it.
			const spanSec = Math.max(0, (track.endMs - track.startMs) / 1000);
			const sourceLen = asset?.durationSec || track.durationSec || spanSec;
			const origStart = track.startMs / 1000;
			const origTrimStart = track.offsetMs / 1000;
			const origTrimEnd = origTrimStart + spanSec;
			// Alt inside the pill slips it: the span stays put and the media slides under
			// it. On the BODY only — the edges keep their crop semantics.
			//
			// An edge drag sets the in-point at TIMELINE scale, which is unusable once the
			// file is much longer than the pill: reaching 3:00 inside a four-minute bed on
			// a five-second view means dragging three minutes of ruler. So the slip rate is
			// derived from the FILE — one viewport width traverses all of it — floored at
			// the timeline's own scale so a slip is never slower than moving the pill,
			// which would be its own surprise on a file shorter than the view.
			const slipping = mode === "move" && e.altKey && sourceLen > 0;
			const slipSecPerPx = Math.max(total / r.width, sourceLen / Math.max(1, r.width * navSpan));
			// A looping track may be pulled out PAST the end of its file — that is
			// the whole point of looping, and capping at the source length is what
			// made the loop toggle do nothing: the span could never exceed the
			// window loop repeats, so it always played exactly once. Only the
			// programme end bounds it (applied below).
			const maxEnd = track.loop
				? Number.POSITIVE_INFINITY
				: sourceLen > 0
					? sourceLen
					: origTrimEnd;
			// Snap the moving edge to clip boundaries and the timeline ends, same PILL_SNAP_PX
			// magnet the region pills use.
			const snapTargets = [
				0,
				total,
				...clips.map((c) => c.timelineStartSec),
				...clips.map((c) => c.timelineEndSec),
			];
			const snapThresh = pxPerSec > 0 ? PILL_SNAP_PX / pxPerSec : 0;
			const snap = (v: number): number => {
				let best = v;
				let bestD = snapThresh;
				for (const target of snapTargets) {
					const d = Math.abs(target - v);
					if (d < bestD) {
						bestD = d;
						best = target;
					}
				}
				setSnapPct(best === v ? null : (best / total) * 100);
				return best;
			};
			const move = (ev: PointerEvent) => {
				if (slipping) {
					const nextOffsetMs = slipAudioOffsetMs(
						track.offsetMs,
						track.endMs - track.startMs,
						sourceLen,
						(ev.clientX - startX) * slipSecPerPx * 1000,
					);
					if (nextOffsetMs == null) return;
					const nextTrimStart = nextOffsetMs / 1000;
					setAudioDragTip({
						x: ev.clientX,
						y: ev.clientY,
						inSec: nextTrimStart,
						outSec: nextTrimStart + spanSec,
						durationSec: sourceLen,
					});
					// The span does not move; only the window onto the file does.
					const slipState = {
						id: track.id,
						start: origStart,
						trimStart: nextTrimStart,
						trimEnd: nextTrimStart + spanSec,
					};
					audioDragRef.current = slipState;
					setAudioDrag(slipState);
					return;
				}
				const dxSec = ((ev.clientX - startX) / r.width) * total;
				let ns = origStart;
				let nts = origTrimStart;
				let nte = origTrimEnd;
				if (mode === "move") {
					// Cap so the whole track lands by `total`: no pill past 100%, and the
					// export (which truncates at the programme end) matches what's shown.
					const upper = Math.max(0, total - (origTrimEnd - origTrimStart));
					ns = Math.min(Math.max(0, snap(origStart + dxSec)), upper);
				} else if (mode === "l") {
					// The left edge can't cross the right one, and can't reveal more head
					// than the source has (trimStart floors at 0 → head floors at
					// origStart - origTrimStart).
					const rightEdge = origStart + (origTrimEnd - origTrimStart);
					const lowerLeft = Math.max(0, origStart - origTrimStart);
					let newLeft = snap(origStart + dxSec);
					newLeft = Math.min(Math.max(newLeft, lowerLeft), rightEdge - MIN_REGION_SEC);
					ns = newLeft;
					nts = origTrimStart + (newLeft - origStart);
					nte = origTrimEnd;
				} else {
					// Right edge: move the out-point, head fixed. Snap on the timeline
					// position of the edge, then map back to a source out-point.
					const snappedRight = snap(origStart + (origTrimEnd - origTrimStart) + dxSec);
					const newTrimEnd = origTrimStart + (snappedRight - origStart);
					// Cap the out-point at the source length AND the programme end (`total`).
					nte = Math.min(
						Math.max(newTrimEnd, origTrimStart + MIN_REGION_SEC),
						maxEnd,
						origTrimStart + Math.max(0, total - origStart),
					);
				}
				// The readout answers "where am I in the file", which is the one thing the
				// pill cannot show: its edges stop at the content, but nothing said where
				// that content was.
				if (mode !== "move") {
					setAudioDragTip({
						x: ev.clientX,
						y: ev.clientY,
						inSec: nts,
						outSec: nte,
						durationSec: sourceLen,
					});
				}
				const next = { id: track.id, start: ns, trimStart: nts, trimEnd: nte };
				audioDragRef.current = next;
				setAudioDrag(next);
			};
			const up = () => {
				setSnapPct(null);
				setAudioDragTip(null);
				window.removeEventListener("pointermove", move);
				window.removeEventListener("pointerup", up);
				const fin = audioDragRef.current;
				if (fin) {
					void tl
						.placeAudioTrack(fin.id, {
							startMs: Math.round(fin.start * 1000),
							endMs: Math.round((fin.start + Math.max(0, fin.trimEnd - fin.trimStart)) * 1000),
							// Carries the left-edge trim: without it the head moved but the
							// source kept playing from the same point, so dragging the edge
							// in just slid the audio along instead of cutting its head off.
							offsetMs: Math.round(fin.trimStart * 1000),
						})
						.finally(() => {
							if (audioDragRef.current === fin) {
								audioDragRef.current = null;
								setAudioDrag(null);
							}
						});
				} else {
					audioDragRef.current = null;
					setAudioDrag(null);
				}
			};
			window.addEventListener("pointermove", move);
			window.addEventListener("pointerup", up);
		},
		// navSpan: the slip rate is derived from the VISIBLE width, so a zoom that
		// leaves `total` alone still changes it. Left out, the rate froze at whatever
		// the zoom was when the callback was last built.
		[tl, total, clips, pxPerSec, navSpan],
	);

	const startNavDrag = useCallback(
		(mode: "left" | "right" | "pan", e: ReactPointerEvent) => {
			e.preventDefault();
			e.stopPropagation();
			const r = navRef.current?.getBoundingClientRect();
			if (!r) return;
			const startX = e.clientX;
			const s0 = nav.start;
			const e0 = nav.end;
			const move = (ev: PointerEvent) => {
				const dx = (ev.clientX - startX) / r.width;
				let start = s0;
				let end = e0;
				if (mode === "left") start = Math.min(e0 - 0.05, Math.max(0, s0 + dx));
				else if (mode === "right") end = Math.max(s0 + 0.05, Math.min(1, e0 + dx));
				else {
					const w = e0 - s0;
					start = Math.max(0, Math.min(1 - w, s0 + dx));
					end = start + w;
				}
				setNav({ start, end });
			};
			const up = () => {
				window.removeEventListener("pointermove", move);
				window.removeEventListener("pointerup", up);
			};
			window.addEventListener("pointermove", move);
			window.addEventListener("pointerup", up);
		},
		[nav],
	);

	// Plain scroll = vertical scroll (the panel can be too short to show every
	// lane + the main track). Shift+scroll = horizontal pan. Ctrl+scroll = zoom
	// around the cursor's timeline position. Shift is tested first, so it wins
	// when both are held: holding Shift always pans, never zooms.
	// Attached as a native (non-passive) listener rather than React's onWheel:
	// React marks wheel handlers passive by default, so e.preventDefault()
	// there silently no-ops and the browser/OS still intercepts Ctrl+wheel as
	// a page-zoom gesture.
	// Listens on the whole panel (ref below) so the ruler, the hint labels and
	// the nav bar all zoom/pan too — only .tlTracks scrolls natively, but the
	// gesture shouldn't be confined to wherever that scroll happens to live.
	// The rect stays tracksRef regardless of which descendant the wheel fired
	// on: ruler + tracks share one horizontal padding (see the width effect
	// below), so tracksRef reads the same left/width either way, and it's the
	// one guaranteed to exist whenever showLanes is true.
	useEffect(() => {
		const panel = panelRef.current;
		const tracks = tracksRef.current;
		if (!panel || !tracks) return;
		// Media shows no zoom window, so leave the wheel alone there: a zoom with
		// no control to undo it and no ruler reading to explain it is a trap.
		if (!showLanes) return;
		const onWheelNative = (e: WheelEvent) => {
			const r = tracks.getBoundingClientRect();
			const viewportPct = Math.min(1, Math.max(0, (e.clientX - r.left) / r.width));
			if (e.shiftKey) {
				e.preventDefault();
				setNav((prev) => {
					const width = prev.end - prev.start;
					// Shift often routes the wheel onto deltaX; accept whichever axis moved.
					const wheelDelta = e.deltaX !== 0 ? e.deltaX : e.deltaY;
					const delta = (wheelDelta / r.width) * width;
					const start = Math.max(0, Math.min(1 - width, prev.start + delta));
					return { start, end: start + width };
				});
			} else if (e.ctrlKey) {
				e.preventDefault();
				// A trackpad can deliver a horizontal swipe here, leaving deltaY at 0.
				// Read whichever axis moved, otherwise the sign test below always
				// reads "up" and the gesture only ever zooms in.
				const wheelDelta = e.deltaY !== 0 ? e.deltaY : e.deltaX;
				if (wheelDelta === 0) return;
				setNav((prev) => {
					const width = prev.end - prev.start;
					const cursorFrac = prev.start + viewportPct * width;
					const zoomFactor = wheelDelta > 0 ? 1.12 : 1 / 1.12;
					const nextWidth = Math.min(1, Math.max(0.02, width * zoomFactor));
					const start = Math.max(0, Math.min(1 - nextWidth, cursorFrac - viewportPct * nextWidth));
					return { start, end: start + nextWidth };
				});
			}
			// Otherwise let the native vertical scroll of .tlTracks run (no preventDefault).
		};
		panel.addEventListener("wheel", onWheelNative, { passive: false });
		return () => panel.removeEventListener("wheel", onWheelNative);
	}, [showLanes]);

	// Track the tracks' content width for the ruler. .tlTracks and .tlRulerRow
	// carry the same horizontal padding and the tracks' scrollbar is hidden, so
	// this content box is exactly one unzoomed canvas wide.
	useEffect(() => {
		const el = tracksRef.current;
		if (!el) return;
		setViewportWidthPx(el.clientWidth);
		const ro = new ResizeObserver((entries) => {
			for (const entry of entries) setViewportWidthPx(entry.contentRect.width);
		});
		ro.observe(el);
		return () => ro.disconnect();
	}, []);

	// zoom/pan: the tracks canvas is widened by 1/(navEnd-navStart) and shifted.
	// The width % resolves against the CONTAINER, the translate % against the
	// canvas's own (already widened) box — so scrolling to nav.start is a flat
	// -nav.start of the canvas. Scaling it by 1/navSpan as well double-counted
	// the zoom and threw the whole timeline off-screen at any nav.start > 0.
	const canvasStyle = {
		width: `${(100 / navSpan).toFixed(3)}%`,
		transform: `translateX(${(-nav.start * 100).toFixed(3)}%)`,
	} as const;

	const laneOf = (kind: LanePill["kind"]) =>
		kind === "annotation"
			? styles.laneAnnotation
			: kind === "speed"
				? styles.laneSpeed
				: kind === "trim"
					? styles.laneTrim
					: kind === "cameraFullscreen"
						? styles.laneCameraFullscreen
						: kind === "shaderEffect"
							? styles.laneShaderEffect
							: styles.laneZoom;
	const pillIcon = (kind: LanePill["kind"]) =>
		kind === "annotation" ? (
			<MessageSquare size={12} />
		) : kind === "speed" ? (
			<Clock size={12} />
		) : kind === "trim" ? (
			<Scissors size={12} />
		) : kind === "cameraFullscreen" ? (
			<Maximize2 size={12} />
		) : kind === "shaderEffect" ? (
			<Sparkles size={12} />
		) : (
			<ZoomIn size={12} />
		);

	// Drag a clip left/right to reorder it relative to its neighbours. Pointer-
	// driven (like the lane pills), not HTML5 DnD — that's reserved for dropping
	// a *new* asset in from the media panel. A short move threshold keeps a
	// plain click as "select" and a stationary press as "double-click to edit".
	// On drop we hand the target index to tl.moveClip, which delegates to the
	// same document/timeline.ts#moveClip the agent's "moveClip" tool uses.
	// (That tool takes a neighbour's id rather than this index — the index is
	// relative to the array with the moved clip already removed, see below.)
	const startClipDrag = useCallback(
		(e: ReactPointerEvent, clip: AxcutClip) => {
			if (e.button !== 0) return;
			// Let the delete button (and any future in-clip control) handle its
			// own pointer events instead of starting a drag.
			if ((e.target as HTMLElement).closest("[data-no-clip-drag]")) return;
			if (clips.length < 2) return;
			const container = clipsRef.current;
			const clipEl = (e.currentTarget as HTMLElement) ?? null;
			if (!container || !clipEl) return;
			const startX = e.clientX;
			const from = clips.findIndex((c) => c.id === clip.id);
			if (from < 0) return;
			didClipDragRef.current = false;
			let dragging = false;
			// Width + gap the dragged clip displaces its neighbours by — measured
			// once at drag start (only its position changes during the drag, not
			// its size).
			const shiftAmount = clipEl.getBoundingClientRect().width + CLIP_GUTTER_PX;

			// Boundaries are captured once, before any transform is applied —
			// re-querying live rects mid-drag would pick up the dragged clip's own
			// translated (pointer-following) position and corrupt the math, since
			// its rect no longer reflects its untouched slot.
			const originalRects = Array.from(
				container.querySelectorAll<HTMLElement>("[data-clip-id]"),
			).map((el) => el.getBoundingClientRect());
			const boundaries =
				originalRects.length === 0
					? [0]
					: [
							originalRects[0].left,
							...originalRects.slice(1).map((r, i) => (originalRects[i].right + r.left) / 2),
							originalRects[originalRects.length - 1].right,
						];
			// Nearest clip boundary to `clientX`, as an insertion index into the
			// *full* clip array (0..n).
			const computeInsertFull = (clientX: number) => {
				let bi = 0;
				let bd = Number.POSITIVE_INFINITY;
				for (let i = 0; i < boundaries.length; i++) {
					const d = Math.abs(boundaries[i] - clientX);
					if (d < bd) {
						bd = d;
						bi = i;
					}
				}
				return bi;
			};
			// insertFull indexes the full array; moveClip (and our own preview
			// math) target the array with the dragged clip already removed, so
			// shift down by one when the drop point is to the right of its origin.
			const computeTarget = (clientX: number) => {
				const insertFull = computeInsertFull(clientX);
				return insertFull > from ? insertFull - 1 : insertFull;
			};

			const move = (ev: PointerEvent) => {
				if (!dragging && Math.abs(ev.clientX - startX) < 4) return;
				dragging = true;
				didClipDragRef.current = true;
				const target = computeTarget(ev.clientX);
				setClipDrag({
					id: clip.id,
					from,
					target,
					pointerDeltaX: ev.clientX - startX,
					shiftPx: shiftAmount,
				});
			};
			const up = async (ev: PointerEvent) => {
				window.removeEventListener("pointermove", move);
				window.removeEventListener("pointerup", up);
				if (dragging) {
					const target = computeTarget(ev.clientX);
					// Keep the slid-open preview on screen through the async save so
					// there's no one-frame snap-back to the original order before the
					// store's new order lands.
					if (target !== from) await tl.moveClip(clip.id, target);
				}
				setClipDrag(null);
			};
			window.addEventListener("pointermove", move);
			window.addEventListener("pointerup", up);
		},
		[clips, tl],
	);

	// `shortcut` is the user's live binding, shown as the tooltip's chip. The strings carry no key:
	// these actions can be remapped, and a key written into a translation would then lie.
	const tools: Array<{ id: ToolId; label: string; shortcut: string; icon: React.ReactNode }> = [
		{
			id: "cut",
			label: t("buttons.addTrim"),
			shortcut: formatBinding(shortcuts.addTrim, isMac),
			icon: <Scissors size={16} />,
		},
		{
			id: "comment",
			label: t("buttons.addAnnotation"),
			shortcut: formatBinding(shortcuts.addAnnotation, isMac),
			icon: <MessageSquare size={16} />,
		},
		{
			id: "speed",
			label: t("buttons.addSpeed"),
			shortcut: formatBinding(shortcuts.addSpeed, isMac),
			icon: <Clock size={16} />,
		},
	];

	// Auto-enhance option 1 — the deterministic cursor-telemetry auto-zoom
	// (ported from main; NOT AI). Reads the clicks recorded with each take and
	// plans zooms around them.
	//
	// Telemetry belongs to a RECORDING, not to a clip: it is fetched per asset and read in
	// that asset's source time. Projecting it onto the ruler is `buildAutoZoomSuggestionsForClips`'
	// job — every clip drawing on the asset gets its own zooms, including the second clip over
	// a recording already used once. Feeding the raw source-time spans to `addZoomsBulk` (which
	// reads RAW TIMELINE ms) is what confined every suggestion to the first clip's stretch of
	// ruler. Each asset with clips is asked, not just the first: a second recording on the
	// timeline was previously never consulted at all.
	const runAutoZooms = useCallback(async () => {
		setAutoEnhanceOpen(false);
		const document = useProjectStore.getState().document;
		if (!document || document.timeline.clips.length === 0) {
			toast.error(t("toolbar.importRecordingFirst"));
			return;
		}
		setAutoBusy(true);
		try {
			// Collected against the document as it is now, and again if the clips moved
			// while the telemetry was being read: the suggestions carry timeline spans and
			// `addZoomsBulk` anchors them against whatever the store holds at write time,
			// so a trim or a reorder during that multi-second wait would land them on
			// different media.
			const collected = await collectAutoZoomSuggestionsForLatestDocument(
				() => useProjectStore.getState().document,
				(videoPath) => nativeBridgeClient.cursor.getTelemetry(videoPath),
			);
			const suggestions = collected?.suggestions ?? [];
			if (suggestions.length === 0) {
				toast.info(t("toolbar.noAutoZoomMoments"), {
					description: t("toolbar.noAutoZoomMomentsDescription"),
				});
				return;
			}
			const added = await tl.addZoomsBulk(suggestions);
			// A failed write returns 0 and has already toasted why. Without this the user
			// got "Added 0 automatic zooms" stacked on top of "Failed to save project",
			// with no zoom anywhere -- a success message for something that did not happen.
			if (added === 0) return;
			toast.success(
				t(added === 1 ? "toolbar.addedAutoZoom" : "toolbar.addedAutoZoomPlural", { count: added }),
			);
		} catch (err) {
			toast.error(t("toolbar.autoZoomFailed"), {
				description: err instanceof Error ? err.message : String(err),
			});
		} finally {
			setAutoBusy(false);
		}
	}, [tl, t]);

	// Auto-enhance option 2 — hand a generic prompt to the AI agent (smart
	// zooms + cuts) via the chat prompt-bus. The chat panel owns the outcome
	// toast: submitting is not the same as being accepted (no usable provider
	// bounces the prompt), and only the consumer knows which happened.
	const runAiEnhance = useCallback(() => {
		setAutoEnhanceOpen(false);
		useChatPromptBus.getState().submit(AI_ENHANCE_PROMPT);
	}, []);

	// Any region under the pill: a click selects the one it lands on, not always the first.
	const isPillSelected = (p: LanePill) =>
		p.sourceIds.some((id) => tl.selection?.id === id || tl.multiSelection.some((m) => m.id === id));
	// Optimistic preview: during a clip-reorder drag, slide each region pill by
	// the same amount as the clip it sits on — mirroring the clip transforms so
	// zoom/speed/annotation/trim pills travel with their content in real time,
	// then land exactly where the reprojection (document/timeline.ts#moveClip)
	// puts them on drop. Returns px shift + whether it should track immediately
	// (the region on the dragged clip follows the pointer with no easing).
	const regionPreviewShift = (startSec: number): { px: number; immediate: boolean } => {
		if (!clipDrag) return { px: 0, immediate: false };
		const idx = clips.findIndex(
			(c) => startSec >= c.timelineStartSec && startSec < c.timelineEndSec,
		);
		if (idx < 0) return { px: 0, immediate: false };
		const { from, target, pointerDeltaX, shiftPx } = clipDrag;
		if (idx === from) return { px: pointerDeltaX, immediate: true };
		if (target > from && idx > from && idx <= target) return { px: -shiftPx, immediate: false };
		if (target < from && idx >= target && idx < from) return { px: shiftPx, immediate: false };
		return { px: 0, immediate: false };
	};

	// One rendered pill box — either the whole region (normal case) or one
	// fragment of a region being eagerly split-previewed across a clip-drag
	// junction (see renderPills below). Fragments are inert previews (no
	// handles/selection/content beyond the leading one) with the touching inner
	// edge de-styled so a split pill still reads as one continuous shape.
	const renderOnePill = (seg: {
		pill: LanePill;
		row: number;
		key: string;
		segStart: number;
		segEnd: number;
		shiftPx: number;
		immediate: boolean;
		showContent: boolean;
		interactive: boolean;
		suppressLeftSeam: boolean;
		suppressRightSeam: boolean;
	}) => {
		const { pill: p } = seg;
		const durSec = seg.segEnd - seg.segStart;
		// The box is exactly as long as the effect is; only what fits INSIDE it
		// varies with the zoom.
		const { compact, roomForLabel } = pillAffordance(durSec, pxPerSec);
		return (
			<div
				key={seg.key}
				role={seg.interactive ? "button" : undefined}
				data-region-id={p.id}
				data-track-row={seg.row}
				aria-label={
					p.kind === "annotation"
						? `${p.label}, ${t("tracks.annotation", { index: seg.row + 1 })}`
						: p.label
				}
				tabIndex={seg.interactive ? 0 : undefined}
				className={`${styles.lanePill} ${laneOf(p.kind)}${
					compact ? ` ${styles.lanePillCompact}` : ""
				}${seg.interactive && isPillSelected(p) ? ` ${styles.lanePillSel}` : ""}`}
				style={{
					top: REGION_LANE_PAD_PX + seg.row * REGION_ROW_STEP_PX,
					left: `${pctAt(seg.segStart)}%`,
					// Measured on the expanded ruler at BOTH ends: a region straddling a pause
					// covers it, so its box has to grow by that pause and not merely slide.
					width: `${pctOf(seg.segEnd - seg.segStart)}%`,
					transform: seg.shiftPx ? `translateX(${seg.shiftPx}px)` : undefined,
					transition: !clipDrag
						? undefined
						: seg.immediate
							? "none"
							: "transform 150ms cubic-bezier(0.2, 0, 0, 1)",
					...(seg.suppressLeftSeam
						? { borderTopLeftRadius: 0, borderBottomLeftRadius: 0, borderLeftWidth: 0 }
						: {}),
					...(seg.suppressRightSeam
						? { borderTopRightRadius: 0, borderBottomRightRadius: 0, borderRightWidth: 0 }
						: {}),
				}}
				onPointerDown={seg.interactive ? (e) => startPillDrag(e, p, "move") : undefined}
				// A pill is focusable and announced as a button, so Enter and Space have to
				// activate it — without this a keyboard user could tab to a region and then
				// reach nothing that acts on a selection: Delete, copy/paste, the inspector.
				//
				// `nativeEvent.stopPropagation()`, not just the synthetic one: the editor
				// shell listens on WINDOW, above React's root container, and Space is bound
				// to play/pause there. Stopping only the synthetic event would select the
				// pill and toggle playback in the same keystroke.
				onKeyDown={
					seg.interactive
						? (e) => {
								if (e.key !== "Enter" && e.key !== " ") return;
								e.preventDefault();
								e.nativeEvent.stopPropagation();
								selectPill(p, e.shiftKey);
							}
						: undefined
				}
				// Annotations teach vertical dragging on the pill; other kinds only repeat
				// their name when the pill is too narrow to draw it.
				title={
					p.kind === "annotation"
						? `${p.label} — ${t("tracks.dragHint")}`
						: seg.showContent && roomForLabel
							? undefined
							: p.label
				}
			>
				{seg.interactive ? (
					<span
						className={styles.lanePillHandle}
						style={{ left: compact ? -PILL_HANDLE_OUT_PX : 0 }}
						onPointerDown={(e) => startPillDrag(e, p, "l")}
					/>
				) : null}
				{seg.showContent && roomForLabel ? (
					<>
						{pillIcon(p.kind)}
						<span className={styles.lanePillLabel}>{p.label}</span>
					</>
				) : null}
				{seg.interactive ? (
					<span
						className={styles.lanePillHandle}
						style={{ right: compact ? -PILL_HANDLE_OUT_PX : 0 }}
						onPointerDown={(e) => startPillDrag(e, p, "r")}
					/>
				) : null}
			</div>
		);
	};

	// Only annotations stack. Pack their live geometry once, for pills and lane height.
	const effectiveAnnotations = useMemo(
		() =>
			annPills.map((p) => ({
				...p,
				...(activePillDrag?.id === p.id
					? { start: activePillDrag.start, end: activePillDrag.end }
					: {}),
				layer: activePillDrag?.layers?.get(p.id) ?? p.layer,
			})),
		[annPills, activePillDrag],
	);
	const annotationRows = useMemo(
		() =>
			activePillDrag?.kind === "annotation"
				? packRegionRows(effectiveAnnotations)
				: savedAnnotationRows,
		[effectiveAnnotations, savedAnnotationRows, activePillDrag?.kind],
	);
	useEffect(() => {
		onAnnotationRowCountChange?.(annotationRows.rowCount);
	}, [annotationRows.rowCount, onAnnotationRowCountChange]);

	const liveSpan = <T extends { start: number; end: number }>(id: string, p: T): T =>
		activePillDrag?.id === id ? { ...p, start: activePillDrag.start, end: activePillDrag.end } : p;

	const renderPills = (pills: LanePill[], emptyLabel: string) => {
		const annotations = pills === annPills;
		const effectivePills = annotations ? effectiveAnnotations : pills.map((p) => liveSpan(p.id, p));
		return (
			<>
				{effectivePills.length === 0 ? (
					// The lane is as wide as the ZOOMED canvas, so centring the hint on it
					// would slide it off-screen as soon as the timeline is zoomed in. Span
					// the visible window instead, and the hint stays centred in view.
					<span
						className={styles.laneEmpty}
						style={{ left: `${nav.start * 100}%`, width: `${navSpan * 100}%` }}
					>
						{emptyLabel}
					</span>
				) : null}
				{effectivePills.flatMap((p) => {
					// Eager split preview: the instant a clip is grabbed, a pill that
					// straddles the dragged clip's junction shows the same per-clip
					// split it would resolve to on drop (via moveClip's reprojection),
					// instead of moving as one block glued to whichever clip owns its
					// start. Only fork into fragments when they'd actually move
					// differently — a pill unaffected by this drag stays one DOM node.
					if (clipDrag) {
						const frags = ventilateSpanAcrossClips(p.start, p.end, clips);
						if (frags.length >= 2) {
							const clipById = new Map(clips.map((c) => [c.id, c]));
							const shifts = frags.map((f) => {
								const c = clipById.get(f.clipId);
								return c
									? regionPreviewShift(c.timelineStartSec + f.localStartSec)
									: { px: 0, immediate: false };
							});
							const first = shifts[0];
							const differ = shifts.some(
								(s) => s.px !== first.px || s.immediate !== first.immediate,
							);
							if (differ) {
								return frags.flatMap((f, i) => {
									const c = clipById.get(f.clipId);
									if (!c) return [];
									return [
										renderOnePill({
											pill: p,
											row: annotations ? (annotationRows.rowOf.get(p.id) ?? 0) : 0,
											key: `${p.id}__f${i}`,
											segStart: c.timelineStartSec + f.localStartSec,
											segEnd: c.timelineStartSec + f.localEndSec,
											shiftPx: shifts[i].px,
											immediate: shifts[i].immediate,
											showContent: i === 0,
											interactive: false,
											suppressLeftSeam: i > 0,
											suppressRightSeam: i < frags.length - 1,
										}),
									];
								});
							}
						}
					}
					const shift = regionPreviewShift(p.start);
					return [
						renderOnePill({
							pill: p,
							row: annotations ? (annotationRows.rowOf.get(p.id) ?? 0) : 0,
							key: p.id,
							segStart: p.start,
							segEnd: p.end,
							shiftPx: shift.px,
							immediate: shift.immediate,
							showContent: true,
							interactive: true,
							suppressLeftSeam: false,
							suppressRightSeam: false,
						}),
					];
				})}
			</>
		);
	};

	// Each zoom's camera moves (#1028): the pill shows the hold, the zoom-in runs in the trail
	// before it and the zoom-out in the trail after it, on the speed-aware clock the compositor
	// uses. The part a trim or a clip junction cuts is hatched: the export jumps there instead of
	// easing. The timeline's own end is no junction: nothing plays after it to jump to. Chained
	// zooms get one pan trail between them instead of a zoom-out and a zoom-in. Display only,
	// not a control. Hidden while a clip is dragged, when the pills split and slide.
	const renderZoomTrails = () => {
		if (clipDrag) return null;
		const ms = (span: { start: number; end: number }) => ({
			startMs: span.start * 1000,
			endMs: span.end * 1000,
		});
		const speeds = speedRuns.map((r) => ({
			id: r.ids[0],
			speed: r.member.speed,
			...ms(liveSpan(r.ids[0], r)),
		}));
		const trims = trimPills.map((p) => ms(liveSpan(p.id, p)));
		const totalMs = total * 1000;
		const sec = (cutMs: number) => (cutMs / 1000).toFixed(2);
		const zooms = zoomRuns.map((r) => ms(liveSpan(r.ids[0], r)));
		const junctions = clips
			.filter((c) => c.timelineStartSec > 0)
			.map((c) => ms({ start: c.timelineStartSec, end: c.timelineStartSec }));
		const pans = chainedPans(zooms, speeds, [...trims, ...junctions]);
		return zoomRuns.flatMap((r, i) => {
			const zoom = zooms[i];
			const pan = pans.find((p) => p.from === i);
			const panned = pans.some((p) => p.to === i);
			const moves = zoomTransitions({ ...zoom, scale: effectiveZoomScale(r.member) }, speeds);
			const cut = transitionCutsMs(zoom, moves, trims, junctions);
			const outUntilMs = Math.min(moves.outUntilMs, totalMs);
			const zoomIn = {
				side: "in",
				fromMs: moves.inFromMs,
				toMs: zoom.startMs,
				cutFromMs: moves.inFromMs,
				cutToMs: moves.inFromMs + cut.inMs,
				text:
					cut.inMs > 0
						? t(cut.inByJunction ? "trails.zoomInJunction" : "trails.zoomInCut", {
								seconds: sec(cut.inMs),
							})
						: t("trails.zoomIn"),
			};
			const trails = [
				...(panned ? [] : [zoomIn]),
				pan
					? {
							side: "pan",
							fromMs: zoom.endMs,
							toMs: Math.min(pan.untilMs, totalMs),
							cutFromMs: 0,
							cutToMs: 0,
							text: t("trails.pan"),
						}
					: {
							side: "out",
							fromMs: zoom.endMs,
							toMs: outUntilMs,
							cutFromMs: moves.outUntilMs - cut.outMs,
							cutToMs: outUntilMs,
							text:
								cut.outMs > 0
									? t(cut.outByJunction ? "trails.zoomOutJunction" : "trails.zoomOutCut", {
											seconds: sec(cut.outMs),
										})
									: t("trails.zoomOut"),
						},
			];
			return trails
				.filter((trail) => trail.toMs > trail.fromMs)
				.map((trail) => {
					const lengthMs = trail.toMs - trail.fromMs;
					const cutMs = trail.cutToMs - trail.cutFromMs;
					return (
						<Tooltip key={`${r.ids[0]}:${trail.side}`} content={trail.text}>
							<div
								role="img"
								aria-label={trail.text}
								data-zoom-trail={trail.side}
								className={`${styles.zoomTrail} ${styles.laneZoom}`}
								style={{
									top: 5,
									left: `${pctAt(trail.fromMs / 1000)}%`,
									width: `${pctOf(lengthMs / 1000)}%`,
								}}
							>
								{cutMs > 0 ? (
									<span
										data-zoom-trail-cut=""
										className={styles.zoomTrailCut}
										style={{
											left: `${((trail.cutFromMs - trail.fromMs) / lengthMs) * 100}%`,
											width: `${(cutMs / lengthMs) * 100}%`,
										}}
									/>
								) : null}
							</div>
						</Tooltip>
					);
				});
		});
	};

	return (
		<div className={styles.tl} ref={panelRef}>
			<div className={styles.tlToolbar}>
				{showLanes ? (
					// Its own provider rather than leaning on the app root's: the toolbar
					// is the only thing here that needs one, and every test that renders
					// a timeline (directly or through the shell) would otherwise have to
					// know to supply it. Nesting under the root provider is harmless.
					<TooltipProvider>
						<div className={styles.tlTools} role="toolbar" aria-label={t("toolbar.timelineTools")}>
							<Popover open={autoEnhanceOpen} onOpenChange={setAutoEnhanceOpen}>
								<Tooltip content={t("toolbar.autoEnhance")}>
									<PopoverTrigger asChild>
										<button
											type="button"
											className={styles.tlToolBtn}
											aria-label={t("toolbar.autoEnhance")}
											// `aria-disabled`, not `disabled`, so the tooltip still opens while a pass runs; the
											// click must not open the menu meanwhile (Radix skips a prevented click).
											aria-disabled={autoBusy || undefined}
											onClick={(e) => {
												if (autoBusy) e.preventDefault();
											}}
										>
											{autoBusy ? (
												<Loader2 className="animate-spin" size={16} />
											) : (
												<Wand2 size={16} />
											)}
										</button>
									</PopoverTrigger>
								</Tooltip>
								<PopoverContent
									align="start"
									sideOffset={6}
									animated={false}
									className="w-auto border-0 bg-transparent p-0 shadow-none"
								>
									<div
										className={styles.recMenu}
										style={{ position: "relative", bottom: "auto", width: 244 }}
									>
										<button
											type="button"
											className={styles.recMenuRow}
											onClick={() => void runAutoZooms()}
										>
											<ZoomIn size={16} style={{ flexShrink: 0 }} />
											<span style={{ display: "flex", flexDirection: "column", gap: 1 }}>
												<span style={{ fontWeight: 600 }}>{t("toolbar.automaticZooms")}</span>
												<span style={{ fontSize: 12, color: "var(--muted)" }}>
													{t("toolbar.automaticZoomsHint")}
												</span>
											</span>
										</button>
										<button
											type="button"
											className={styles.recMenuRow}
											onClick={runAiEnhance}
											disabled={smartCutsBlocked}
											title={
												transcriptGate.reason === "failed" ? transcriptGate.message : undefined
											}
											style={
												smartCutsBlocked ? { opacity: 0.55, cursor: "not-allowed" } : undefined
											}
										>
											{transcriptGate.state === "pending" ? (
												<Loader2 size={16} className="animate-spin" style={{ flexShrink: 0 }} />
											) : (
												<Sparkles size={16} style={{ flexShrink: 0 }} />
											)}
											<span style={{ display: "flex", flexDirection: "column", gap: 1 }}>
												<span style={{ fontWeight: 600 }}>{t("toolbar.smartZoomsAndCuts")}</span>
												<span style={{ fontSize: 12, color: "var(--muted)" }}>{smartCutsHint}</span>
											</span>
										</button>
									</div>
								</PopoverContent>
							</Popover>
							<span className={styles.tlToolSep} aria-hidden />
							{tools.map((tool) => (
								<Fragment key={tool.id}>
									<Tooltip content={tool.label} shortcut={tool.shortcut}>
										<button
											type="button"
											className={styles.tlToolBtn}
											aria-label={tool.label}
											onClick={() => {
												// Read at CLICK time: a render-time value would be one zoom
												// notch stale when the user zooms and immediately creates.
												const dur = newRegionDurationSec();
												if (tool.id === "speed") void tl.addSpeed(dur);
												if (tool.id === "comment") void tl.addAnnotation(dur);
												if (tool.id === "cut") void tl.addTrim(dur);
											}}
										>
											{tool.icon}
										</button>
									</Tooltip>
									{/* Add audio sits right after Add annotation (issue #350). */}
									{/* One audio button, two ways in. A mic and a music note side by
								    side both just said "audio" and left the user to guess which
								    was which; a waveform is neutral between them, and the menu
								    names the two paths outright. Mirrors the auto-enhance
								    button's menu right next to it. */}
									{tool.id === "comment" ? (
										<Popover open={audioMenuOpen} onOpenChange={setAudioMenuOpen}>
											<Tooltip
												content={t("toolbar.addAudioTooltip")}
												shortcut={formatBinding(shortcuts.addAudio, isMac)}
											>
												<PopoverTrigger asChild>
													<button
														type="button"
														className={styles.tlToolBtn}
														aria-label={t("toolbar.addAudioTooltip")}
													>
														<AudioLines size={16} />
													</button>
												</PopoverTrigger>
											</Tooltip>
											<PopoverContent
												align="start"
												sideOffset={6}
												animated={false}
												className="w-auto border-0 bg-transparent p-0 shadow-none"
											>
												<div
													className={styles.recMenu}
													style={{ position: "relative", bottom: "auto", width: 244 }}
												>
													<button
														type="button"
														className={styles.recMenuRow}
														onClick={() => {
															setAudioMenuOpen(false);
															onAddVoiceover();
														}}
													>
														<Mic size={16} style={{ flexShrink: 0 }} />
														<span style={{ display: "flex", flexDirection: "column", gap: 1 }}>
															<span style={{ fontWeight: 600 }}>{t("audio.addVoiceover")}</span>
															<span style={{ fontSize: 12, color: "var(--muted)" }}>
																{t("audio.addVoiceoverHint")}
															</span>
														</span>
														<kbd className={styles.recMenuKey}>
															{formatBinding(shortcuts.addVoiceover, isMac)}
														</kbd>
													</button>
													<button
														type="button"
														className={styles.recMenuRow}
														onClick={() => {
															setAudioMenuOpen(false);
															void tl.addAudio();
														}}
													>
														<Music size={16} style={{ flexShrink: 0 }} />
														<span style={{ display: "flex", flexDirection: "column", gap: 1 }}>
															<span style={{ fontWeight: 600 }}>{ts("audioTrack.add")}</span>
															<span style={{ fontSize: 12, color: "var(--muted)" }}>
																{t("audio.importFileHint")}
															</span>
														</span>
														<kbd className={styles.recMenuKey}>
															{formatBinding(shortcuts.addAudio, isMac)}
														</kbd>
													</button>
												</div>
											</PopoverContent>
										</Popover>
									) : null}
								</Fragment>
							))}
							<Tooltip
								content={t("buttons.addZoom")}
								shortcut={formatBinding(shortcuts.addZoom, isMac)}
							>
								<button
									type="button"
									className={styles.tlToolBtn}
									aria-label={t("buttons.addZoom")}
									onClick={() => void tl.addZoom(newRegionDurationSec())}
								>
									<ZoomIn size={16} />
								</button>
							</Tooltip>
							{/* One name and one tip for both states: `aria-pressed` carries which one it is. */}
							<Tooltip content={t("buttons.autoFocusAllTip")}>
								<button
									type="button"
									className={styles.tlToolBtn}
									aria-pressed={settings.autoFocusAll}
									aria-label={t("buttons.autoFocusAll")}
									onClick={() => void setSettings({ autoFocusAll: !settings.autoFocusAll })}
								>
									<Crosshair size={16} />
								</button>
							</Tooltip>
							<Popover open={canChangeLayout && layoutOpen} onOpenChange={setLayoutOpen}>
								<Tooltip
									content={t("layouts.changeHere")}
									shortcut={formatBinding(shortcuts.addCameraFullscreen, isMac)}
								>
									<PopoverTrigger asChild>
										<button
											type="button"
											className={styles.tlToolBtn}
											aria-label={t("layouts.changeHere")}
											disabled={!canChangeLayout}
											data-testid="change-layout"
										>
											<PanelsTopLeft size={16} />
										</button>
									</PopoverTrigger>
								</Tooltip>
								<PopoverContent align="start" style={{ width: 290 }}>
									<LayoutChangeMenu tl={tl} onClose={() => setLayoutOpen(false)} />
								</PopoverContent>
							</Popover>
							{/* Last, behind a divider: every button before it adds a region, this one
							    clears them. Absent with its divider, not greyed out, when there is
							    nothing to clear. One write in the store, so one Ctrl+Z restores every
							    region. */}
							{tl.hasEditRegions ? (
								<>
									<span className={styles.tlToolSep} aria-hidden />
									<Tooltip content={t("buttons.clearTimeline")}>
										<button
											type="button"
											className={styles.tlToolBtn}
											aria-label={t("buttons.clearTimeline")}
											onClick={() => void tl.clearTimeline()}
										>
											<Eraser size={16} />
										</button>
									</Tooltip>
								</>
							) : null}
						</div>
					</TooltipProvider>
				) : (
					// Media is an ARRANGING surface: add, remove, reorder. Nothing here
					// plays or edits, so the transport, the scroll hints, the zoom nav and
					// the playhead are absent rather than inert — this caption is the whole
					// header, and it centres because it is alone in the row.
					<div
						style={{
							display: "flex",
							flexDirection: "column",
							gap: 2,
							margin: "0 auto",
							textAlign: "center",
						}}
					>
						<span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--fg-2)" }}>
							{t("toolbar.arrangeClips")}
						</span>
						<span style={{ fontSize: 12, color: "var(--meta)" }}>
							{t("toolbar.arrangeClipsHint")}
						</span>
					</div>
				)}
				{showLanes ? (
					<>
						{/* Its own provider, like the tool strip above: TransportBar has a tooltip too. */}
						<TooltipProvider>
							<TransportBar
								playing={playing}
								overrideTimeSec={scrubbingTimeSec}
								clips={clips}
								onTogglePlay={onTogglePlay}
							/>
						</TooltipProvider>
						<div className={styles.tlHints}>
							<span className={styles.tlHint}>
								<span className={styles.tlKbd}>Shift+Scroll</span> {t("labels.pan")}
							</span>
							<span className={styles.tlHint}>
								<span className={styles.tlKbd}>Ctrl+Scroll</span> {t("labels.zoom")}
							</span>
						</div>
					</>
				) : null}
			</div>

			{/* Ruler + tracks share one relative wrapper so a single playhead overlay
			    (below) can span both — one continuous line whose head aligns with the
			    clips regardless of the tracks' scrollbar (scrollbar-gutter keeps all
			    three canvases the same width). */}
			<div className={styles.tlBody}>
				{/* Fixed ruler header: the ruler ticks stay pinned right below the toolbar
			    so they don't scroll off when the panel is short — only the lanes/clips
			    below scroll. Shares the tracks' zoom/pan transform so ticks line up. */}
				<div className={styles.tlRulerRow} onPointerDown={startScrub}>
					<div className={styles.tlCanvas} style={canvasStyle}>
						<div className={styles.tlRuler}>
							{rulerTicks.ticks.map((tick) => (
								<div
									key={tick.sec}
									className={`${styles.tlTick}${tick.major ? ` ${styles.tlTickMajor}` : ""}`}
									style={{ left: `${pctAt(tick.sec)}%` }}
								>
									{tick.major ? (
										<span className={styles.tlTickLabel}>{fmtTick(tick.sec, rulerTicks.step)}</span>
									) : null}
								</div>
							))}
						</div>
					</div>
				</div>

				<div ref={tracksRef} className={styles.tlTracks} onPointerDown={startScrub}>
					<div ref={canvasRef} className={styles.tlCanvas} style={canvasStyle}>
						{snapPct !== null ? (
							<div aria-hidden className={styles.tlSnapGuide} style={{ left: `${snapPct}%` }} />
						) : null}

						{showLanes ? (
							<>
								{/* An empty lane advertises the shortcut that fills it ("Press A to add
								    annotation") rather than restating that it is empty — the same hint
								    strings the pre-v4 timeline used, so the keys stay translated. The key
								    is the live binding, formatted like the toolbar tooltip's chip, so a
								    rebind in the shortcuts dialog moves the hint with it (#966). */}
								<div
									className={styles.tlLane}
									data-track-kind="annotation"
									style={{ height: regionLaneHeight(annotationRows.rowCount) }}
								>
									{renderPills(
										annPills,
										t("hints.pressAnnotation", {
											key: formatBinding(shortcuts.addAnnotation, isMac),
										}),
									)}
								</div>
								<div className={styles.tlLane} data-track-kind="speed">
									{renderPills(
										speedPills,
										t("hints.pressSpeed", { key: formatBinding(shortcuts.addSpeed, isMac) }),
									)}
								</div>
								<div className={styles.tlLane} data-track-kind="trim">
									{renderPills(
										trimPills,
										t("hints.pressTrim", { key: formatBinding(shortcuts.addTrim, isMac) }),
									)}
								</div>
								<div className={styles.tlLane} data-track-kind="zoom">
									{/* Its own provider, like the toolbar's: see the note there. */}
									<TooltipProvider>{renderZoomTrails()}</TooltipProvider>
									{renderPills(
										zoomPills,
										t("hints.pressZoom", { key: formatBinding(shortcuts.addZoom, isMac) }),
									)}
								</div>
								<LayoutLane tl={tl} total={total} canvasRef={canvasRef} pxPerSec={pxPerSec} />
								{/* Agent-written shader effects: one at a time, so one row. Only when the project
								    has one: an agent writes them, nothing in the editor adds one, so an empty
								    row would offer nothing. The shell grows by its height
								    (`EFFECT_LANE_EXPANSION_PX`). */}
								{tl.shaderEffectRanges.length > 0 ? (
									<div className={styles.tlLane}>{renderPills(shaderEffectPills, "")}</div>
								) : null}
								{/* Imported audio tracks (issue #350). Always shown, like every other
								    lane — "Add audio" is a toolbar peer of the region tools now (and
								    has a keyboard shortcut), so an empty lane advertises the shortcut
								    that fills it rather than hiding until the first import. */}
								<div
									className={`${styles.tlLane} ${styles.tlLaneAudio}`}
									// Grows a row per overlapping track, so three voiceovers over
									// the same stretch are three legible pills rather than one
									// pile nobody can aim at.
									style={{
										height:
											audioRows.rowCount * AUDIO_ROW_HEIGHT_PX +
											(audioRows.rowCount - 1) * AUDIO_ROW_GAP_PX +
											AUDIO_LANE_PAD_PX * 2,
									}}
								>
									{tl.audioTracks.length === 0 ? (
										<span
											className={styles.laneEmpty}
											style={{ left: `${nav.start * 100}%`, width: `${navSpan * 100}%` }}
										>
											{t("hints.pressAudio", {
												audioKey: formatBinding(shortcuts.addAudio, isMac),
												voiceoverKey: formatBinding(shortcuts.addVoiceover, isMac),
											})}
										</span>
									) : (
										// One pill per user-visible track: the document stores one
										// clip-anchored fragment per clip the track covers, and the
										// lane must not show a split take as two pills.
										audioPills.map((track) => {
											const asset = tl.assets.find((a) => a.id === track.assetId);
											const duration = asset?.durationSec ?? track.durationSec;
											// While this track is being dragged, lay it out from the live
											// preview geometry instead of the not-yet-written document.
											const drag = audioDrag?.id === track.id ? audioDrag : null;
											const start = drag ? drag.start : track.startMs / 1000;
											// A drag carries its span as the trim window it is dragging
											// the edges of; the pill's width is that window.
											const widthSec = drag
												? Math.max(0, drag.trimEnd - drag.trimStart)
												: Math.max(0, (track.endMs - track.startMs) / 1000);
											const trimStart = drag ? drag.trimStart : track.offsetMs / 1000;
											const trimEnd = trimStart + widthSec;
											return (
												<AudioLanePill
													key={track.id}
													track={track}
													url={asset ? toFileUrl(asset.originalPath) : undefined}
													assetDurationSec={duration}
													leftPct={pctOf(start)}
													widthPct={pctOf(widthSec)}
													row={audioRows.rowOf.get(track.id) ?? 0}
													rowHeight={AUDIO_ROW_HEIGHT_PX + AUDIO_ROW_GAP_PX}
													spanSec={widthSec}
													loopWindowSec={Math.max(0, (duration || 0) - trimStart)}
													sourceStartSec={trimStart}
													// A looping pill can outrun its file; the waveform draws
													// the source it actually has.
													sourceEndSec={duration > 0 ? Math.min(trimEnd, duration) : trimEnd}
													selected={tl.selectedAudioTrackId === track.id}
													onStartDrag={startAudioDrag}
													onSelect={tl.selectAudioTrack}
													label={track.label || asset?.label || ts("audioTrack.defaultLabel")}
													slipHint={ts("audioTrack.slipHint", {
														modifier: isMac ? "Option" : "Alt",
													})}
													slipArmed={slipArmed}
													outputGain={audioGainScalar(settings.audioGainDb)}
													ghost={((g) =>
														g
															? {
																	leftPct: pctOf(g.startT),
																	widthPct: pctOf(g.endT - g.startT),
																	sourceStartSec: g.sourceStartSec,
																	sourceEndSec: g.sourceEndSec,
																}
															: null)(
														audioGhostExtent(
															trimStart,
															widthSec,
															duration,
															start,
															start + widthSec,
															total,
														),
													)}
												/>
											);
										})
									)}
								</div>
							</>
						) : null}

						<div
							ref={clipsRef}
							className={`${styles.tlClips}${dragOver ? ` ${styles.tlClipsDrag}` : ""}`}
							onDragOver={(e) => {
								e.preventDefault();
								e.dataTransfer.dropEffect = "copy";
								if (!dragOver) setDragOver(true);
							}}
							onDragLeave={() => setDragOver(false)}
							onDrop={(e) => {
								e.preventDefault();
								setDragOver(false);
								const id = e.dataTransfer.getData(ASSET_MIME);
								if (id && onDropAsset) void onDropAsset(id).catch(() => undefined);
							}}
						>
							{clips.map((c, i) => {
								const dur = c.timelineEndSec - c.timelineStartSec;
								// On the expanded ruler the box also carries whatever pauses fall
								// inside it — the film really does stay on this clip's frame for
								// them, so they belong to its box rather than between boxes.
								const boxStart = c.timelineStartSec;
								const boxEnd = c.timelineEndSec;
								const boxLen = boxEnd - boxStart;
								const asset = tl.assets.find((a) => a.id === c.assetId);
								const clipVideoUrl = videoSources.find((v) => v.id === c.assetId)?.src;
								const selected = tl.clipSelection === c.id;
								const dragging = clipDrag?.id === c.id;
								// Siblings between the dragged clip's origin and its live
								// target slide sideways (via the base .tlClip transition) to
								// open a gap at the drop point; the dragged clip itself
								// follows the pointer directly (see .tlClipDragging's
								// transition:none override).
								let clipTransform: string | undefined;
								if (dragging) {
									clipTransform = `translateX(${clipDrag.pointerDeltaX}px)`;
								} else if (clipDrag) {
									const { from, target, shiftPx } = clipDrag;
									if (target > from && i > from && i <= target)
										clipTransform = `translateX(${-shiftPx}px)`;
									else if (target < from && i >= target && i < from)
										clipTransform = `translateX(${shiftPx}px)`;
								}
								// Too narrow to hold its own controls. An insertion of a few tenths
								// of a second on a half-minute timeline is a handful of pixels, and
								// there is no arrangement that fits a button inside that — so while
								// it is selected the controls step outside the box instead.
								const narrow = boxLen * pxPerSec < NARROW_CLIP_PX;
								// The gutter is taken out of the card's own width below, so the
								// room the label actually has is that much less than the span.
								const durText = formatSec(dur);
								// The gutter separates two cards; the last one has nothing after it and
								// reaches the end of the timeline.
								const gutterPx = i === clips.length - 1 ? 0 : CLIP_GUTTER_PX;
								return (
									<div
										key={c.id}
										data-clip-id={c.id}
										className={`${styles.tlClip}${narrow ? ` ${styles.tlClipNarrow}` : ""}${
											// Amber, because nobody shot it. Same token the mark it replaces
											// used, so an insertion still reads as one at a glance.
											isGeneratedAssetId(c.assetId) ? ` ${styles.tlClipGenerated}` : ""
										}${selected ? ` ${styles.tlClipSel}` : ""}${
											dragging ? ` ${styles.tlClipDragging}` : ""
										}`}
										style={{
											left: `${pctOf(boxStart)}%`,
											// Minus the gutter that separates two cards (it used to be the
											// flex row's `gap`). A clip shorter than the gutter lands on
											// .tlClip's 1px min-width instead of collapsing — same rule as
											// the lane pills above.
											width: gutterPx
												? `calc(${pctOf(boxLen)}% - ${gutterPx}px)`
												: `${pctOf(boxLen)}%`,
											transform: clipTransform,
										}}
										onPointerDown={(e) => startClipDrag(e, c)}
										onClick={(e) => {
											e.stopPropagation();
											// A completed reorder-drag also fires a click; don't let it
											// double as a selection.
											if (didClipDragRef.current) {
												didClipDragRef.current = false;
												return;
											}
											tl.selectClip(c.id);
										}}
										onDoubleClick={(e) => {
											e.stopPropagation();
											onEditClip(c);
										}}
										// The file name is here rather than on the card: which file a clip
										// comes from matters less than what can be done with it.
										title={`${asset?.label ?? c.assetId}\n${t("toolbar.dragToReorderHint")}`}
									>
										<ClipWaveform
											videoUrl={clipVideoUrl}
											assetDurationSec={asset?.durationSec}
											sourceStartSec={c.sourceStartSec}
											sourceEndSec={c.sourceEndSec ?? c.sourceStartSec + dur}
											gain={audioGainScalar(settings.audioGainDb)}
										/>
										<div className={styles.tlClipLabel}>
											<button
												type="button"
												className={styles.tlClipEdit}
												data-no-clip-drag
												title={t("toolbar.editInOutPoints")}
												aria-label={t("toolbar.editInOutPoints")}
												onClick={(e) => {
													e.stopPropagation();
													onEditClip(c);
												}}
												onKeyDown={keepActivationKey}
											>
												<Pencil size={15} />
											</button>
											{cardFitsDuration(boxLen * pxPerSec - gutterPx, durText) ? (
												<span className={styles.tlClipDuration}>{durText}</span>
											) : null}
										</div>
										{selected ? (
											<button
												type="button"
												data-no-clip-drag
												className={styles.tlClipDelete}
												data-narrow={narrow ? "true" : undefined}
												title={t("toolbar.deleteClip")}
												aria-label={t("toolbar.deleteClip")}
												onClick={(e) => {
													e.stopPropagation();
													void tl.removeClip(c.id);
												}}
												onKeyDown={keepActivationKey}
											>
												<Trash2 size={15} />
											</button>
										) : null}
									</div>
								);
							})}
							{dragOver ? (
								<div aria-hidden className={styles.tlDropHint}>
									{t("toolbar.dropToAdd")}
								</div>
							) : null}
						</div>
					</div>
				</div>

				{/* Single playhead overlay spanning the ruler + tracks: fixed vertically
			    (a cursor, so it doesn't scroll with the lanes) and sharing the exact
			    same zoom/pan transform + width as the canvases, so its line stays
			    continuous from the ruler down through the clips and its head aligns.
			    Edit only: there is no playback to follow on the Media surface. */}
				{showLanes ? (
					<PlayheadOverlay
						totalSec={total}
						overrideTimeSec={scrubbingTimeSec}
						canvasStyle={canvasStyle}
						onPointerDown={startScrub}
						playheadRef={playheadElRef}
					/>
				) : null}
			</div>

			{/* Zoom/pan window. Edit only: arranging clips needs the whole timeline
			    on screen at once, and there is nothing to zoom INTO without lanes. */}
			{showLanes ? (
				<div ref={navRef} className={styles.tlNav}>
					<div className={styles.tlNavTrack} aria-hidden />
					<div
						className={styles.tlNavWindow}
						// Whole timeline in view: the thumb goes quiet (see .tlNavWindow[data-full]).
						data-full={navSpan >= 0.999 || undefined}
						title={t("labels.panTip")}
						style={{
							left: `${(nav.start * 100).toFixed(2)}%`,
							width: `${((nav.end - nav.start) * 100).toFixed(2)}%`,
						}}
						onPointerDown={(e) => startNavDrag("pan", e)}
					>
						{/* Grips on the window's own edges: pulling one zooms, as a range slider's
						    thumbs would. */}
						<span
							className={styles.tlNavGrip}
							data-edge="start"
							title={t("labels.zoomTip")}
							onPointerDown={(e) => startNavDrag("left", e)}
						/>
						<span
							className={styles.tlNavGrip}
							data-edge="end"
							title={t("labels.zoomTip")}
							onPointerDown={(e) => startNavDrag("right", e)}
						/>
					</div>
				</div>
			) : null}
			{/* The crop readout, at the component ROOT rather than in the lane: the lane
			    sits inside the zoomed canvas transform, which would scale a chip placed
			    there. `in -> out / length` — 0:00.0 and out = length are the boundary
			    states, self-evident without copy, which is why this adds no locale key. */}
			{audioDragTip ? (
				<div className={styles.tlDragTip} style={{ left: audioDragTip.x, top: audioDragTip.y }}>
					{formatSec(audioDragTip.inSec)} → {formatSec(audioDragTip.outSec)}
					{audioDragTip.durationSec > 0 ? ` / ${formatSec(audioDragTip.durationSec)}` : ""}
				</div>
			) : null}
		</div>
	);
}