Skip to content

Open source CapCut alternative.

TypeScript
239 KB
Raw Blame
"use client";
import { TimelineActionButton } from "@/cut/components/TimelineActionButton";
import { TimelineGroupActions } from "@/cut/components/TimelineGroupActions";

import { useTranslations } from "next-intl";
import { Fragment, useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
import { ArrowDownToLine, AudioLines, Check, Clapperboard, Copy, Diamond, Download, EllipsisVertical, Eye, EyeOff, FolderOpen, FolderPlus, Fullscreen, Loader2, Magnet, MoreHorizontal, PanelBottomClose, Pause, Play, Scissors, SkipBack, Sticker, Trash2, Type, Volume2, VolumeX } from "lucide-react";
import { EFFECT_CHIP_ICONS, effectIconKind, SHAPE_CHIP_ICONS, TRANSITION_ICONS } from "@/cut/components/entityIcons";
import { Button } from "@/components/ui/button";
import { GuidesMenu } from "@/cut/components/GuidesMenu";
import { EmptyTimelineNote, TimelinePicker } from "@/cut/components/TimelinePicker";
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Slider } from "@/components/ui/slider";
import { Skeleton } from "@/components/ui/skeleton";
import {
  clearAssetDrag,
  clearElementDrag,
  draggingAssetId,
  draggingAssetIds,
  draggingElement,
  draggedLutKey,
  draggingLibraryMany,
  draggingTemplate,
  hasAssetDrag,
  hasElementDrag,
  hasLibraryDrag,
  hasTemplateDrag,
} from "@/cut/lib/assetDrag";
import { libraryLutId, LUT_MARK_ICON } from "@/cut/lib/linkedLibrary";
import { registerFileLanding, registerTransitionLanding } from "@/cut/lib/timelineDrop";
import { audioClipRefs, clipRefs, draggingRef, hasRefDrag, refFromAsset, type AssetRef } from "@/cut/lib/assetRef";
import { sendFrameToChat, type FrameGrabOrigin } from "@/cut/lib/chatIntake";
import { copyRefImage } from "@/cut/lib/refMedia";
import { useCutCaps } from "@/cut/lib/backend/hooks";
import {
  addProjectTemplateToTimeline,
  addTemplateToProject,
  importLibraryAsset,
  libraryMediaUrl,
  libraryPosterUrl,
  saveAssetToLibrary,
  type LibraryAsset,
} from "@/cut/lib/library";
import { originalSettings } from "@/cut/lib/exportClient";
import type { ExportDoc } from "@/cut/lib/renderSnapshot";
import { useExports } from "@/cut/lib/exportStore";
import { isDragActive, startDrag, subscribeDragActive } from "@/cut/lib/drag";
import { keyboardToEditor, shortcutDecline } from "@/cut/lib/shortcutGate";
import { additiveClick } from "@/cut/lib/hostKeys";
import { CLIP_GAP, landOnRow, laneDragFor, laneDragParts, laneDragSlots, resolveRow, startLaneMove, startLaneTrim, type LaneDrag, type RowBox } from "@/cut/lib/laneTracks";
import { reportSwallowed } from "@/cut/lib/report";
import { downloadMedia, dropEdgeFrames, ensurePeaks, importImage, importStockAudio, importStockVideo, peekEdgeFrame, requestEdgeFrame, missingMediaFor, revealMedia, stripFailedFor, subscribeStripStatus } from "@/cut/lib/media";
import { planFilmstrip, type FilmTile } from "@/cut/lib/filmstrip";
import { waveGain } from "@/cut/lib/waveform";
import { canSplitItem } from "@/cut/lib/itemKinds";
import { track0Clips, laneGapAt, blockClipAt, sameLane, type LaneRef, clipLen, clipSpeed, getClipSpans, maxClipFade, overlayLaneOrder, overlayLayers, projectDuration, resolveTransitions, rippleInsert, useEditor } from "@/cut/lib/store";
import type { VideoTrackPlacement } from "@/cut/lib/store";
import { playheadAt, setSkim, skimAt, subscribePlayhead, usePlayhead, useSkim } from "@/cut/lib/playhead";
import { useBrushUi } from "@/cut/lib/removal/brushUi";
import { useMatteBakes } from "@/cut/lib/removal/bakeJobs";
import { cardMatteKey } from "@/cut/lib/cameraCard";
import { laneHidden, subtitleLaneCount } from "@/cut/lib/subtitles";
import { formatTime, formatTimecode } from "@/cut/lib/time";
import { hasSpeedCurve, headSrc, retimeOf, SPEED_CURVE_MAX, SPEED_CURVE_MIN, tailSrc, type EffectId, type Retime, type SpeedNode } from "@donkeycut/effects-kit";
import { BLOCK_COLOR } from "@/cut/lib/blockSource";
import { isLinkedAssetType, assetIsSilent, previewUrl, emptySubtitles, fontStack, IMAGE_CLIP_SECONDS, isAudioTransition, clipName, isTextOverlay, overlayName, transitionBarStart, transitionDefaultSeconds, XBAR_MAGNET_PX, type ShapeKind } from "@/cut/lib/types";
import type { AudioClip, ClipSpan, ColorGrade, MediaAsset, Overlay, Selection, StickerOverlay, SubtitleCue, TimelineTransition, TransitionBoundaryKind, TransitionStyle, VideoClip } from "@/cut/lib/types";
import { isLottieAsset } from "@/cut/lib/lottieAssets";
import { gradeCssApprox, normalizeGrade } from "@donkeycut/effects-kit";
import { useLabels } from "@/i18n/labels";
import { ExportsDock } from "@/cut/components/ExportsDock";
import { cn } from "@/lib/utils";

/**
 * Is this landing the one already on screen? Values one level deep, and
 * element-wise inside a list of them, so a preview rebuilt from the same
 * numbers compares equal.
 */
function sameLanding(a: unknown, b: unknown, depth = 2): boolean {
  if (a === b) return true;
  if (depth <= 0 || !a || !b || typeof a !== "object" || typeof b !== "object") return false;
  if (Array.isArray(a) || Array.isArray(b)) {
    return (
      Array.isArray(a) &&
      Array.isArray(b) &&
      a.length === b.length &&
      a.every((v, i) => sameLanding(v, b[i], depth - 1))
    );
  }
  const ak = Object.keys(a);
  const bk = Object.keys(b);
  return (
    ak.length === bk.length &&
    ak.every((k) =>
      sameLanding((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k], depth - 1)
    )
  );
}

/**
 * A drop preview that re-renders only when the landing actually moves.
 *
 * `dragover` fires many times a second, and most of those events report the
 * landing already drawn — a still pointer keeps the events coming. Storing a
 * fresh object for each one re-renders the whole timeline for no visible
 * change, which is churn on its own and fuel for anything downstream that
 * reacts to a render.
 */
function useDropPreview<T>(initial: T): [T, (next: T) => void] {
  const [value, setValue] = useState<T>(initial);
  const set = useCallback((next: T) => {
    setValue((cur) => (sameLanding(cur, next) ? cur : next));
  }, []);
  return [value, set];
}


/** Video row height: the picture band plus the sound band under it. */
const VIDEO_H = 88;
const OVERLAY_H = VIDEO_H; // every video track shares the same row height
/** Extra row height under a video row whose clips carry mask keys: room for
 * the key rail below the bars. The diamonds read as part of the clip, so the
 * row's separator line sits clear under them — a picked key's ring included —
 * and the next row keeps its usual distance below the line. */
const KEYRAIL_EXTRA = 20;
const AUDIO_H = 44;
/** The sound band along a video clip box's bottom edge. */
const WAVE_H = 24;
/** The picture band above it — the filmstrip's height. A clip with nothing to
 * play in the band (an image, a silent video) drops the band and its box stops
 * at the filmstrip's edge. */
const FILM_H = VIDEO_H - 4 - WAVE_H;
/** Whether a clip has a sound band to draw: a video carrying audio of its own,
 * or a recording bound to it (`sound`, which the band then draws). Muting
 * greys the band down, so the clip keeps its shape and its waveform. An image
 * or a silent video has nothing to show there. */
const hasSoundBand = (asset: MediaAsset, sound?: MediaAsset) =>
  asset.type === "video" && !!(sound ?? asset).peaks?.length;
/** A video row's height. Rows whose clips carry no audio lose the sound band's
 * worth, so the row ends where the filmstrips do. An empty row keeps the full
 * height: it is a drop target for clips that do have sound. */
const videoRowH = (list: ClipSpan[]) =>
  list.length > 0 && !list.some((sp) => hasSoundBand(sp.asset, sp.sound?.asset))
    ? VIDEO_H - WAVE_H
    : VIDEO_H;
/** The `mt-1.5` every row carries, so a row drag knows what one row's worth of
 * travel is. */
const ROW_GAP = 6;
/** One soundtrack lane's step down the band: the lane plus the gap a video
 * row keeps above it, so every lane's clip sits the same distance under the
 * line above. */
const AUDIO_ROW = AUDIO_H + ROW_GAP;

/** The three bands whose rows reorder: the video stack, the element rows, and
 * the soundtrack lanes. Subtitle rows are language tracks, managed in the
 * panel, so they stay put. */
type RowBand = "video" | "overlay" | "audio";

/** A row being dragged to a new place in its own band. Rows are display
 * indices, 0 = the band's top row. The boxes are the band's rows measured in
 * screen space at the grab: the rows move while the drag runs, so hit-testing
 * against where they started is what keeps the target from flickering. */
interface RowDrag {
  band: RowBand;
  from: number;
  to: number;
  /** Pointer travel, clamped so the carried row stays inside its band. */
  dy: number;
  rows: { top: number; h: number }[];
  /** The viewport the landing outline draws across. */
  left: number;
  width: number;
}

/** Where row `r` shows while `d` is in flight: the carried row is at the
 * target, and the rows it passed close up behind it. */
function shownRow(d: RowDrag, r: number): number {
  if (r === d.from) return d.to;
  if (d.from < d.to) return r > d.from && r <= d.to ? r - 1 : r;
  return r >= d.to && r < d.from ? r + 1 : r;
}

/** The box the carried row will land in, in screen space. */
function landingBox(d: RowDrag): { top: number; h: number } {
  const held = d.rows[d.from];
  const seat = d.rows[d.to];
  return {
    top: d.to > d.from ? seat.top + seat.h - held.h : seat.top,
    h: held.h,
  };
}

/** Where a dragged video clip can land. Re-exported name for the store's
 * placement union (existing track, 0 included / newly-inserted track). */
type TrackTarget = VideoTrackPlacement;

/** Two placements point at the same drop. */
function samePlacement(a: TrackTarget | null, b: TrackTarget | null): boolean {
  if (!a || !b || a.kind !== b.kind) return false;
  return a.kind === "track"
    ? a.track === (b as { track: number }).track
    : a.level === (b as { level: number }).level;
}
/** Video track 0 — the store's `clips` array — as a drop placement. */
const TRACK_ZERO: TrackTarget = { kind: "track", track: 0 };
const TEXT_H = 28;
const SUB_H = 22;
const RULER_H = 26;
const PAD_END = 320;
/** Breathing room on both sides so the playhead cap is never clipped. The left
 * one doubles as the gutter — the strip that stays put while the timeline
 * scrolls under it — so widening this widens the column controls will sit in. */
const PAD_SIDE = 20;
// Where the playhead sits after a page turn while following, and how long the
// turn's glide takes. A reduced-motion setting turns the page in one step.
const FOLLOW_MARGIN = 80;
const FOLLOW_GLIDE_MS = 420;
const reducedMotion = () =>
  typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;

/** Zoom range, in timeline pixels per second of media. */
const ZOOM_MIN = 12;
const ZOOM_MAX = 800;
/** px/sec at which `dur` seconds fill a `width`-px viewport, with room spared
 * for the side padding. */
const fitZoom = (width: number, dur: number) => Math.max((width - 60) / dur, 0.01);
/** The slider's left end: zoomed all the way out, the project still fills at
 * least 70% of the viewport, so the timeline never shrinks into a corner. A
 * very short project caps at half of ZOOM_MAX to keep the slider some travel. */
const zoomFloor = (width: number, dur: number) =>
  dur > 0
    ? Math.min(Math.max((width * 0.7) / dur, 0.01), ZOOM_MAX / 2)
    : ZOOM_MIN;
/**
 * Zoom reads as a ratio — doubling px/sec feels like one step whether you start
 * at 20 or at 400 — so the slider travels in log space. A linear track would
 * spend its first sixth on every zoom anyone uses and the rest on extremes.
 */
const zoomToSlider = (pps: number, min: number) =>
  (Math.log(pps / min) / Math.log(ZOOM_MAX / min)) * 100;
const sliderToZoom = (pos: number, min: number) => min * (ZOOM_MAX / min) ** (pos / 100);

// A high-contrast selected state: a bright blue ring outside the box, a halo,
// and a raised stacking order, so a selected item reads clearly against its
// neighbours. The ring sits outside every kind of item alike, which is the
// only way it measures the same on all of them: a video clip's filmstrip
// covers its box, so an inner ring vanished under the thumbnails, while an
// audio, text or subtitle bar paints its own background and showed that same
// ring at full width on top of this one.
const SELECTED_SHADOW =
  "z-10 shadow-[0_0_0_2px_#0a84ff,0_2px_11px_rgba(10,132,255,0.6)]";

/**
 * Element bars carry their family's color: text purple, elements (shapes and
 * stickers) magenta, effects teal — the three places they come from, so a row
 * reads as what it holds before any label does. The drag highlights take the
 * carried item's color too, so a move keeps the same identity the whole way.
 *
 * Written out rather than composed, since Tailwind reads whole class names.
 */
type OverlayFamily = "text" | "element" | "effect";

/**
 * A place on the transition track a transition can sit: a cut between two
 * clips that touch, or an open edge — a clip's head or tail with nothing
 * against it, where the picture arrives from or leaves to nothing.
 *
 * `at` is the boundary itself (the cut, the head, the tail) and `len` the room
 * a transition takes there.
 */
/** `len` is what already plays at this boundary, 0 when nothing does — the
 * length a landing bar takes is that or the dropped style's own default
 * (`anchorLen`), since a cross dissolve wants a shorter one than a blend. */
type Anchor = { kind: "cut" | "in" | "out"; clipId: string; at: number; len: number };

/** One transition bar drawn on the row: the store object itself and the place
 * it resolved to (null while it sits inert). */
type XBar = {
  t: TimelineTransition;
  role: { kind: Anchor["kind"]; clipId: string } | null;
};


const overlayFamily = (o: Overlay): OverlayFamily =>
  o.kind === "effect" ? "effect" : o.kind === "shape" || o.kind === "sticker" ? "element" : "text";

/** The glyph on an effect's bar: a waveform for the treatments that work on
 * the sound, sparkles for the ones that work on the picture. */
function EffectChipIcon({ effect }: { effect: EffectId }) {
  const Icon = EFFECT_CHIP_ICONS[effectIconKind(effect)];
  return <Icon className="mr-1 size-2.5 shrink-0" />;
}

/** The stretch a panel element takes when dropped — `addElement`'s default
 * length — so the landing ghost matches what the drop makes. */
const ELEMENT_DROP_SECONDS = 3;

/** The video stack's landing-slot chrome. */
const VIDEO_SLOT =
  "rounded-[2.5px] bg-[#0a84ff]/10 shadow-[inset_0_0_0_1.5px_rgba(10,132,255,0.4)]";

const FAMILY_STYLE: Record<
  OverlayFamily,
  { bar: string; row: string; slot: string }
> = {
  text: {
    bar: "bg-[#7B4BD1]",
    row: "border-[#7B4BD1]/70 bg-[#7B4BD1]/5",
    slot: "bg-[#7B4BD1]/10 shadow-[inset_0_0_0_1.5px_rgba(123,75,209,0.5)]",
  },
  element: {
    bar: "bg-[#C43C87]",
    row: "border-[#C43C87]/70 bg-[#C43C87]/5",
    slot: "bg-[#C43C87]/10 shadow-[inset_0_0_0_1.5px_rgba(196,60,135,0.5)]",
  },
  effect: {
    bar: "bg-[#0D8577]",
    row: "border-[#0D8577]/70 bg-[#0D8577]/5",
    slot: "bg-[#0D8577]/10 shadow-[inset_0_0_0_1.5px_rgba(13,133,119,0.5)]",
  },
};

/** Width of the trim grab zone at each end of a bar — paired with the `w-`
 * in `trimHandle` below; anything else drawn on a bar keeps clear of it. */
const TRIM_W = 10;

const trimBase =
  "tl-trim absolute z-3 w-[10px] cursor-ew-resize after:absolute after:left-[3px] after:w-1 after:rounded-full after:bg-white after:opacity-0 after:shadow-[0_0_0_1px_rgba(0,0,0,0.35)] after:transition-opacity group-hover:after:opacity-90 hover:after:opacity-100";

const trimHandle = cn(
  trimBase,
  "top-0 bottom-0 after:top-1/2 after:h-[calc(100%-10px)] after:-translate-y-1/2"
);

/** The trim zone for a bar `w` px wide. A bar too narrow to keep a grabbable
 * middle swaps its full-height zones for short tabs centered on its edges, so
 * the strips above and below stay the bar's own — a sliver still has
 * somewhere to grab for a move. */
const trimFor = (w: number) =>
  w < TRIM_W * 3 + 4
    ? cn(trimBase, "top-1/2 h-[max(30%,6px)] -translate-y-1/2 after:top-0 after:h-full")
    : trimHandle;

/** On-timeline length a dropped image occupies (it has no intrinsic duration). */
const STILL_SECONDS = IMAGE_CLIP_SECONDS;

/** The resting track rail: a hairline under an occupied row so it reads as a
 * track, bleeding past the content's side padding to run edge to edge. */
const laneRail = (top: number, key?: React.Key) => (
  <div
    key={key}
    data-tl-rail
    className="pointer-events-none absolute h-px bg-border"
    style={{ top, left: -PAD_SIDE, right: -PAD_SIDE }}
  />
);

/** The resting-track pattern an empty project shows: the same hairline rails
 * the video rows draw, repeating downward. Shared by the scroll content and
 * the overscroll underlay so both paint the identical picture. */
const REST_RAILS = `repeating-linear-gradient(to bottom, transparent 0 ${VIDEO_H + 4}px, var(--border) ${VIDEO_H + 4}px ${VIDEO_H + 5}px, transparent ${VIDEO_H + 5}px ${VIDEO_H + 6}px)`;

/** The card-white ruler band with its baseline. Pinned wherever it paints —
 * the ruler stays put while the rows scroll, so its surface never follows the
 * vertical scroll either. */
function RulerBand() {
  return (
    <div
      className="pointer-events-none absolute inset-x-0 top-0 border-b border-border bg-card"
      style={{ height: RULER_H }}
    />
  );
}

/** The timeline with nothing on it: a hairline under each occupied row, and
 * the resting rails where a project has no rows yet.
 *
 * Painted twice, in the two places the tracks are not. Behind the scroller it
 * is what a rubber-band bounce reveals; in the pinned gutter it is what the
 * timeline scrolls under. Both draw from here so the surface cannot come apart
 * at either edge. Fills its parent, which is what positions it. */
function RestingSurface({
  railYs,
  empty,
  timelineH,
}: {
  railYs: number[];
  empty: boolean;
  timelineH: number;
}) {
  return (
    <>
      {railYs.map((y, i) => (
        <div key={i} className="absolute inset-x-0 h-px bg-border" style={{ top: y }} />
      ))}
      {empty && (
        <div
          className="absolute inset-x-0"
          style={{ top: RULER_H, height: timelineH, background: REST_RAILS }}
        />
      )}
    </>
  );
}

/** An asset type that lands as a video clip — footage or a still image. */
const isClipMedia = (t: string | undefined): t is "video" | "image" =>
  t === "video" || t === "image";

/** A sticker asset lands as a sticker element, never as a clip: it is a
 * cut-out to lay over the picture, so a drop on the timeline goes to the
 * element rows however it arrives. */
const stickerOf = (a: MediaAsset | undefined | null): MediaAsset | null =>
  a && a.origin === "sticker" ? a : null;

const draggedSticker = (): MediaAsset | null => {
  const id = draggingAssetId();
  return stickerOf(id ? useEditor.getState().assets.find((a) => a.id === id) : null);
};

/** One item a media drag carries, whatever tile it came from: a project
 * asset, a library card, a stock video, sound or image. Every item lands the
 * same way once it is in the project; only how it gets there differs, and
 * `land` is that difference. */
interface CarriedMedia {
  kind: "video" | "audio" | "image";
  name: string;
  /** How much timeline the item takes when it lands. */
  duration: number;
  /** The project asset for this item — already there, or imported now. */
  land: (projectId: string) => Promise<MediaAsset>;
  /** What a video landing segment paints while it is carried; sound and
   * stickers paint none. */
  ghost?: DropGhost;
}

/** The grade id of the LUT a library drag is carrying, or null when the drag
 * holds anything else. A LUT has no place on the timeline as a clip: it lands
 * on the clip under the pointer as that clip's grade. */
function draggedLut(e: React.DragEvent): string | null {
  const key = draggedLutKey(e);
  return key ? libraryLutId(key) : null;
}

/** The clip box under a point, read off the DOM the boxes are drawn in. */
function clipIdAt(x: number, y: number): string | null {
  for (const el of document.elementsFromPoint(x, y)) {
    const sel = (el as HTMLElement).dataset?.tlSel;
    if (sel?.startsWith("clip:")) return sel.slice(5);
  }
  return null;
}

/** Everything a drag carries, the grabbed item first. A single card is a run
 * of one, so every media drop takes the same path; a font, which has no
 * place on the timeline, is left out. */
function carriedMedia(e: React.DragEvent): CarriedMedia[] {
  if (hasLibraryDrag(e)) {
    return draggingLibraryMany().flatMap((lib) =>
      isLinkedAssetType(lib.type)
        ? []
        : [
            {
              kind: lib.type,
              name: lib.title || lib.name,
              duration: lib.type === "image" ? STILL_SECONDS : lib.duration,
              land: (projectId: string) => importLibraryAsset(projectId, lib),
              ...(isClipMedia(lib.type)
                ? {
                    ghost: {
                      url: libraryMediaUrl(lib.fileName, lib.residency),
                      kind: lib.type,
                      name: lib.title || lib.name,
                      duration: lib.duration,
                      width: lib.width,
                      height: lib.height,
                      // The card's cover is already painted and cached, so
                      // the segment has a frame of the video in it from the
                      // first move — true frames replace it tile by tile as
                      // the reads land.
                      poster: libraryPosterUrl(lib),
                    },
                  }
                : {}),
            },
          ]
    );
  }
  if (hasAssetDrag(e)) {
    const assets = useEditor.getState().assets;
    return draggingAssetIds().flatMap((id) => {
      const asset = assets.find((a) => a.id === id);
      if (!asset || isLinkedAssetType(asset.type)) return [];
      return [
        {
          kind: asset.type,
          name: asset.name,
          duration: asset.type === "image" ? STILL_SECONDS : asset.duration,
          land: async () => asset,
          ...(isClipMedia(asset.type) && !stickerOf(asset) ? { ghost: { asset } } : {}),
        },
      ];
    });
  }
  // A stock tile carries only the unified ref: a sound, a clip, or a still.
  if (!hasRefDrag(e)) return [];
  const ref = draggingRef();
  if (!ref) return [];
  if (ref.scope === "stock" && ref.kind === "audio") {
    return [
      {
        kind: "audio",
        name: ref.name,
        duration: ref.duration ?? 0,
        land: (projectId) =>
          importStockAudio(projectId, { url: ref.url, name: ref.name, duration: ref.duration }),
      },
    ];
  }
  if (ref.scope === "stock" && ref.kind === "video") {
    return [
      {
        kind: "video",
        name: ref.name,
        duration: ref.duration ?? 0,
        land: (projectId) =>
          importStockVideo(projectId, {
            url: ref.url,
            name: ref.name,
            duration: ref.duration,
            width: ref.width,
            height: ref.height,
          }),
        ghost: {
          url: ref.url,
          kind: "video",
          name: ref.name,
          duration: ref.duration ?? 0,
          width: ref.width,
          height: ref.height,
          poster: ref.thumb,
        },
      },
    ];
  }
  if (ref.kind === "image") {
    return [
      {
        kind: "image",
        name: ref.name,
        duration: STILL_SECONDS,
        land: (projectId) => importImage(projectId, ref),
        ghost: { url: ref.url, kind: "image", name: ref.name, duration: STILL_SECONDS },
      },
    ];
  }
  return [];
}

export function Timeline() {
  const tr = useTranslations("timeline.main");
  const transitionLabel = useLabels("transition");
  const shapeLabel = useLabels("shape");
  const effectLabel = useLabels("effect");
  const clips = useEditor((s) => s.clips);
  const audioClips = useEditor((s) => s.audioClips);
  // The composited layers (every clip off track 0), derived from the one
  // clip list — the timeline draws them as the tracks around track 0.
  const overlayClips = useMemo(() => overlayLayers(clips), [clips]);
  const overlays = useEditor((s) => s.overlays);
  const assets = useEditor((s) => s.assets);
  const pps = useEditor((s) => s.pxPerSec);
  const timelineH = useEditor((s) => s.timelineH);
  const multiSelection = useEditor((s) => s.multiSelection);
  const subtitles = useEditor((s) => s.subtitles);
  // An OS file drag carrying media lights the track area as a drop target.
  const fileDropHint = useEditor((s) => s.dropActive === "media");
  const scrollRef = useRef<HTMLDivElement>(null);
  const innerRef = useRef<HTMLDivElement>(null);
  const timeAt = (clientX: number) => {
    const rect = innerRef.current!.getBoundingClientRect();
    return (clientX - rect.left) / pps;
  };
  // Selection made elsewhere (a chat pill click) lands offscreen: scroll the
  // selected item's bar into view. In-view selections stay put.
  useEffect(
    () =>
      useEditor.subscribe((s, prev) => {
        if (!s.selection || s.selection === prev.selection) return;
        const scroller = scrollRef.current;
        const el = scroller?.querySelector(
          `[data-tl-sel="${s.selection.kind}:${s.selection.id}"]`
        );
        if (!scroller || !el) return;
        const r = el.getBoundingClientRect();
        const v = scroller.getBoundingClientRect();
        if (r.right < v.left) scroller.scrollLeft += r.left - v.left - 48;
        else if (r.left > v.right) scroller.scrollLeft += r.right - v.right + 48;
        if (r.top < v.top) scroller.scrollTop += r.top - v.top - 12;
        else if (r.bottom > v.bottom) scroller.scrollTop += r.bottom - v.bottom + 12;
      }),
    []
  );
  // The rail copies behind the scroller follow vertical scroll so they stay
  // glued under the live rails; overscroll can't move them, so the surface
  // runs unbroken through the bounce. (Horizontal position is moot — every
  // line is uniform across the full width.)
  const rulerUnderlayRef = useRef<HTMLDivElement>(null);
  // The left gutter paints that same surface out in front of the scroller, and
  // is glued to the content the same way — it is held out of the horizontal
  // scroll, not out of the vertical one.
  const gutterRef = useRef<HTMLDivElement>(null);
  const gutterFaceRef = useRef<HTMLDivElement>(null);
  const gutterShadowRef = useRef<HTMLDivElement>(null);
  // The track toggles ride the gutter column, glued to vertical scroll the
  // same way the gutter surface is.
  const gutterCtlRef = useRef<HTMLDivElement>(null);
  // The toolbar's editing tools and zoom fold into a menu when the bar cannot
  // hold them beside the transport. Both sides go at once — a bar with the
  // tools on the left and a menu on the right for the zoom alone would be a
  // third arrangement to reason about for no gain. The transport is what the
  // sides have to fit around, so its track is measured, not assumed.
  const barRef = useRef<HTMLDivElement>(null);
  const toolsBareRef = useRef<HTMLDivElement>(null);
  const zoomRef = useRef<HTMLDivElement>(null);
  const transportRef = useRef<HTMLDivElement>(null);
  const [barTight, setBarTight] = useState(false);
  useEffect(() => {
    const bar = barRef.current;
    const bare = toolsBareRef.current;
    const zoom = zoomRef.current;
    const transport = transportRef.current;
    if (!bar || !bare || !zoom || !transport) return;
    const fitBar = () => {
      // Each side track is what is left of the bar once the transport has its
      // width, halved; the tools keep their own margin inside that.
      const side = (bar.clientWidth - transport.offsetWidth) / 2 - 10;
      setBarTight(bare.offsetWidth > side || zoom.offsetWidth > side);
    };
    fitBar();
    // Measure when contextual actions change or the transport gains an hours field.
    const ro = new ResizeObserver(fitBar);
    ro.observe(bar);
    ro.observe(bare);
    ro.observe(transport);
    return () => ro.disconnect();
  }, []);
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const sync = () => {
      const y = `translateY(${-el.scrollTop}px)`;
      if (rulerUnderlayRef.current) rulerUnderlayRef.current.style.transform = y;
      if (gutterRef.current) gutterRef.current.style.transform = y;
      if (gutterCtlRef.current) gutterCtlRef.current.style.transform = y;
      // Once the timeline has scrolled, the gutter has something running under
      // it — its face covers that, and the edge shadow says so. At rest both
      // stay hidden: the underlay already paints the same surface, and a clip
      // sitting at 0 keeps its selection ring whole.
      const scrolled = el.scrollLeft > 0;
      gutterFaceRef.current?.toggleAttribute("data-scrolled", scrolled);
      gutterShadowRef.current?.toggleAttribute("data-scrolled", scrolled);
      publishStripView(el);
    };
    sync();
    el.addEventListener("scroll", sync);
    return () => el.removeEventListener("scroll", sync);
  }, []);
  // The track rails are content-anchored, so the bounce drags them along and
  // cuts them off at the content edge just like the ruler. The underlay
  // repeats each rail as a static full-width line at the same height;
  // measuring the live rails after every render keeps the copies honest
  // against whatever rows the current layout (or an active drag) shows.
  const [railYs, setRailYs] = useState<number[]>([]);
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const box = el.getBoundingClientRect();
    const ys = Array.from(
      el.querySelectorAll<HTMLElement>("[data-tl-rail]"),
      (r) => Math.round(r.getBoundingClientRect().top - box.top + el.scrollTop)
    );
    setRailYs((prev) =>
      prev.length === ys.length && prev.every((v, i) => v === ys[i]) ? prev : ys
    );
  });
  // Where each toggle-bearing row sits, measured the same way as the rails:
  // the rows live in the scrolled content, but the toggles are pinned in the
  // gutter, so they need the rows' content-space tops.
  const [gutterYs, setGutterYs] = useState<{
    video: { track: number; y: number; h: number }[];
    audioTop: number | null;
    textTop: number | null;
    subTop: number | null;
    xTop: number | null;
  }>({ video: [], audioTop: null, textTop: null, subTop: null, xTop: null });
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const box = el.getBoundingClientRect();
    const contentY = (sel: string) => {
      const r = el.querySelector<HTMLElement>(sel);
      return r ? Math.round(r.getBoundingClientRect().top - box.top + el.scrollTop) : null;
    };
    const video = Array.from(el.querySelectorAll<HTMLElement>("[data-tl-vrow]"), (r) => ({
      track: Number(r.dataset.tlVrow),
      y: Math.round(r.getBoundingClientRect().top - box.top + el.scrollTop),
      h: Math.round(r.getBoundingClientRect().height),
    }));
    const audioTop = contentY("[data-tl-arows]");
    const textTop = contentY("[data-tl-trows]");
    const subTop = contentY("[data-tl-srows]");
    const xTop = contentY("[data-tl-xrows]");
    setGutterYs((prev) =>
      prev.audioTop === audioTop &&
      prev.textTop === textTop &&
      prev.subTop === subTop &&
      prev.xTop === xTop &&
      prev.video.length === video.length &&
      prev.video.every(
        (v, i) => v.track === video[i].track && v.y === video[i].y && v.h === video[i].h
      )
        ? prev
        : { video, audioTop, textTop, subTop, xTop }
    );
  });
  // Measured width of the scroll viewport, so the ruler and tracks always draw
  // end-to-end no matter how wide the window is.
  const [viewportW, setViewportW] = useState(900);

  // Membership set so every track can highlight all selected items, not just
  // the primary one.
  const selKeys = useMemo(
    () => new Set(multiSelection.map((x) => (x ? `${x.kind}:${x.id}` : ""))),
    [multiSelection]
  );

  const spans = useMemo(() => getClipSpans(clips, assets), [clips, assets]);
  // A row whose clips carry mask keys grows by the rail band, so the diamonds
  // sit fully below the clips with the usual row gap kept under them.
  const railFor = (list: { clip: VideoClip }[]) =>
    list.some((sp) => sp.clip.mask?.kf?.length || hasSpeedCurve(sp.clip)) ? KEYRAIL_EXTRA : 0;
  const rail0 = railFor(spans);
  const rowH0 = videoRowH(spans);
  // Per-upper-track spans: each track carries its own transitions, so its row
  // needs the same overlap-aware geometry (insets, badges) as track 0's.
  const overlayTrackSpans = useMemo(() => {
    const m = new Map<number, ClipSpan[]>();
    for (const c of overlayClips)
      if (!m.has(c.track)) m.set(c.track, getClipSpans(clips, assets, c.track));
    return m;
  }, [overlayClips, clips, assets]);
  const total = projectDuration({ clips, audioClips, overlays });
  const zoomMin = zoomFloor(viewportW, total);
  // Fill the viewport at minimum so a wide window never leaves the ruler/tracks
  // cut off; grow past it once the content is longer. While a trim/slide drag
  // is in flight, hold the width at its drag-start value so the scroll area
  // doesn't resize under the pointer; it commits on release.
  const dragging = useSyncExternalStore(subscribeDragActive, isDragActive, () => false);
  const liveContentW = Math.max(total * pps + PAD_END, viewportW - PAD_SIDE * 2, 600);
  const [widthHold, setWidthHold] = useState({ dragging, width: liveContentW });
  if (widthHold.dragging !== dragging) setWidthHold({ dragging, width: liveContentW });
  const contentW = dragging ? widthHold.width : liveContentW;

  // Drop preview while dragging a media asset onto video track 0: where the
  // clip would land, how long it runs, and what the source looks like, so the
  // preview reads as the segment itself sliding along the row rather than an
  // empty slot.
  const [assetDrop, setAssetDrop] = useDropPreview<{
    t: number;
    len: number;
    ghost?: DropGhost;
    shifts?: { id: string; start: number }[];
  } | null>(null);
  // Kind of external media being dragged over the timeline (audio vs video).
  const [dropType, setDropType] = useState<"video" | "audio" | null>(null);
  // The clip a carried LUT is held over, lit as the drop's target.
  const [lutTarget, setLutTarget] = useState<string | null>(null);
  // The pending drop preview: which track/gap, at what time, for how long —
  // and which resident clips slide right to open the room, so the row can
  // paint them parting ahead of the drop.
  const [overlayDrop, setOverlayDrop] = useDropPreview<{
    target: TrackTarget;
    t: number;
    len: number;
    shifts?: { id: string; start: number }[];
    /** External media paints its landing as the segment itself — filmstrip at
     * true length; without one the slot is the plain highlight (internal drags
     * already carry their own clip). */
    ghost?: DropGhost;
  } | null>(null);
  // Stage-x pixel a snapped title edge sits at, for the guide line (null = off).
  const [snapX, setSnapX] = useState<number | null>(null);
  // The row an external drag resolved to last, so a new track that has
  // opened under the pointer keeps its hold until the drag returns to a row.
  const heldRow = useRef<number | null>(null);

  // Residents sliding ahead of an in-flight drop: clip id → the start it
  // previews at. Painted as an animated left offset, so the row opens room
  // while the drop hovers and flows back the moment the drag aims elsewhere.
  const dropPartAt = useMemo(() => {
    const m = new Map<string, number>();
    for (const sh of assetDrop?.shifts ?? []) m.set(sh.id, sh.start);
    for (const sh of overlayDrop?.shifts ?? []) m.set(sh.id, sh.start);
    return m;
  }, [assetDrop, overlayDrop]);

  // The video stack's rows as screen boxes, top first — the frontmost layer
  // down to track 0 — read live, since rows mount and shift while a drag runs.
  const videoRows = () =>
    Array.from(innerRef.current?.querySelectorAll<HTMLElement>("[data-tl-vrow]") ?? [], (el) => {
      const r = el.getBoundingClientRect();
      return { track: Number(el.dataset.tlVrow), top: r.top, h: r.height };
    }).sort((a, b) => a.top - b.top);

  // Which drop an external media drag is over: the same row rule every lane
  // drag uses — the row under the pointer takes the clip and opens room for
  // it, and a new track comes from carrying it past the top or the bottom of
  // the stack, where the new row then mounts and holds itself.
  const resolveDropTrack = useCallback((clientY: number): TrackTarget => {
    // An empty video timeline has no base yet: the first clip always lands on
    // track 0, whatever height the pointer is at. Otherwise a drop above the
    // thin empty row resolves to an overlay track, leaving track 0 empty — and
    // an empty track 0 plays black (the compositor's master lives there).
    const st = useEditor.getState();
    if (st.clips.length === 0) return TRACK_ZERO;
    const rows = videoRows();
    if (!rows.length) return TRACK_ZERO;
    // With the magnet on, nothing opens below track 0.
    const row = resolveRow(rows, clientY, heldRow.current, { top: true, bottom: !st.magnet });
    heldRow.current = row;
    if (row < 0)
      return { kind: "insert", level: Math.max(0, ...overlayLayers(st.clips).map((c) => c.track)) + 1 };
    if (row >= rows.length) return { kind: "insert", level: 0 };
    if (!Number.isInteger(row)) return { kind: "insert", level: rows[Math.floor(row)].track };
    return { kind: "track", track: rows[row].track };
  }, []);

  // Drive the drop preview while a clip is dragged across tracks: highlight the
  // target row's landing slot, or the new track's row past the stack. A row
  // takes the drop as an insert at the pointer — its later clips ripple right —
  // so the slot previews the ripple landing the drop will actually take.
  const previewCross = useCallback(
    (target: TrackTarget | null, start = 0, len = 0, ghost?: DropGhost, carried = 0) => {
      // The drag let go of the placement system (it is home, or it ended): the
      // next resolve starts from the geometry alone.
      if (target === null) {
        heldRow.current = null;
        return setOverlayDrop(null);
      }
      // One piece of media over a block fills it, so the ghost takes the
      // block's own span.
      if (carried === 1 && target.kind === "track" && target.track === 0) {
        const cur = useEditor.getState();
        const block = blockClipAt(cur.clips, cur.assets, Math.max(0, start));
        if (block)
          return setOverlayDrop({
            target,
            t: block.start,
            len: clipLen(block),
            shifts: [],
            ghost,
          });
      }
      const landing =
        target.kind === "track"
          ? rippleInsert(
              useEditor.getState().clips.filter((c) => c.track === target.track),
              Math.max(0, start),
              len
            )
          : { start, shifts: [] };
      setOverlayDrop({ target, t: landing.start, len, shifts: landing.shifts, ghost });
    },
    []
  );

  // A drag that left the timeline or landed lets go of the placement hold too,
  // so the next one starts from the geometry alone.
  const endCrossDrag = useCallback(() => {
    heldRow.current = null;
    setOverlayDrop(null);
  }, []);

  // The one in-flight lane-track drag (audio, title, upper layer, or cue):
  // the coordinator publishes it so each section can render the ghost, the
  // landing slot, and grow its row stack while a new row is hovered.
  const [laneDrag, setLaneDrag] = useState<LaneDrag | null>(null);
  // A video clip is being dragged (internal or external): the would-be new
  // tracks past the stack's edges can open, and every clip parts.
  const videoDragActive = laneDrag?.kind === "video" || dropType === "video";

  // Right-click on any row's empty space — video, audio, or title: a small
  // popover offering to close that row's gap under the cursor. The cut is
  // row-local — only that row's later items slide left — so the menu carries
  // the gap it would cut and the row tints it red while the menu is open.
  const [gapMenu, setGapMenu] = useState<
    { x: number; y: number; lane: LaneRef; gap: { start: number; len: number } } | null
  >(null);
  useEffect(() => {
    if (!gapMenu) return;
    const close = (e: KeyboardEvent) => {
      if (e.key === "Escape") setGapMenu(null);
    };
    window.addEventListener("keydown", close);
    return () => window.removeEventListener("keydown", close);
  }, [gapMenu]);

  // Right-click on an element bar: a small popover to hide or show it — and,
  // when the click landed on a keyframe diamond, to remove that key.
  const [barMenu, setBarMenu] = useState<
    { x: number; y: number; id: string; key?: number; transition?: boolean } | null
  >(null);
  useEffect(() => {
    if (!barMenu) return;
    const close = (e: KeyboardEvent) => {
      if (e.key === "Escape") setBarMenu(null);
    };
    window.addEventListener("keydown", close);
    return () => window.removeEventListener("keydown", close);
  }, [barMenu]);

  // Right-click on a video clip: a one-item popover that grabs the frame
  // under the pointer into the chat composer. The menu carries the grab —
  // the asset, the source second under the pointer, and the spot the flight
  // starts from — and the held skimmer line stands at `t` while it is open.
  const readOnly = useEditor((s) => s.readOnly);
  const [frameMenu, setFrameMenu] = useState<
    { x: number; y: number; t: number; asset: MediaAsset; srcT: number; from: FrameGrabOrigin } | null
  >(null);
  useEffect(() => {
    if (!frameMenu) return;
    const close = (e: KeyboardEvent) => {
      if (e.key === "Escape") setFrameMenu(null);
    };
    window.addEventListener("keydown", close);
    return () => window.removeEventListener("keydown", close);
  }, [frameMenu]);
  const openFrameMenu = (
    e: React.MouseEvent,
    grab: { asset: MediaAsset; srcT: number; from: FrameGrabOrigin }
  ) => {
    if (readOnly) return;
    e.preventDefault();
    e.stopPropagation();
    const s = useEditor.getState();
    if (s.playing) s.setPlaying(false);
    setFrameMenu({ x: e.clientX, y: e.clientY, t: timeAt(e.clientX), ...grab });
  };
  // While the menu is open, the skimmer holds at the grab time in its darker
  // held state — the preview shows the frame the line marks, and HoverLine's
  // pointer listeners stand down so crossing onto the menu can't yank it.
  // On close the skimmer resumes right under the pointer (tracked while the
  // menu was up), or clears when the pointer has left the timeline.
  const menuPointer = useRef<{ x: number; y: number } | null>(null);
  useEffect(() => {
    if (!frameMenu) return;
    const scrollEl = scrollRef.current;
    menuPointer.current = { x: frameMenu.x, y: frameMenu.y };
    const track = (e: PointerEvent) => {
      menuPointer.current = { x: e.clientX, y: e.clientY };
    };
    window.addEventListener("pointermove", track);
    setSkim(frameMenu.t);
    return () => {
      window.removeEventListener("pointermove", track);
      const p = menuPointer.current;
      const r = scrollEl?.getBoundingClientRect();
      const inside =
        !!p && !!r && p.x >= r.left && p.x <= r.right && p.y >= r.top && p.y <= r.bottom;
      // Resuming playback while the menu was up (Space) hands the picture
      // back to the playhead; re-arming the skimmer then would freeze every
      // DOM surface on the held frame while the canvas plays on.
      setSkim(
        inside && !useEditor.getState().playing ? Math.max(0, timeAt(p.x)) : null,
      );
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps -- timeAt reads live refs
  }, [frameMenu]);

  // Element rows: overlays carry a `lane`; used lanes compact to contiguous
  // display rows, so an emptied row disappears on its own. The order is the
  // store's, shared with the lane drags so a drop lands where it was aimed.
  const overlayLanes = useMemo(() => {
    const used = overlayLaneOrder(overlays);
    const rowOf = new Map(used.map((l, i) => [l, i]));
    return { used, rowOf, count: used.length };
  }, [overlays]);
  // The color an element drag paints its landing slot with: the carried item's
  // own, so the move reads as one thing from grab to drop.
  const slotFamily = (id: string): OverlayFamily => {
    const held = overlays.find((o) => o.id === id);
    return held ? overlayFamily(held) : "text";
  };

  // Video tracks above track 0 (PiP / composited layers), listed highest-first
  // so the top row is the frontmost layer and track 0 sits at the bottom of
  // the stack; empty tracks vanish.
  const aboveTracks = useMemo(
    () => [...new Set(overlayClips.map((c) => c.track).filter((n) => n > 0))].sort((a, b) => b - a),
    [overlayClips]
  );
  // The z-levels a drop past the stack's edges would open a new track at: a
  // new top layer above, or a new track 0 below (the spine transplants there).
  const topInsertLevel = (aboveTracks[0] ?? 0) + 1;
  const bottomInsertLevel = 0;
  // A video track's display row, top first: the layers in stack order, then
  // track 0 at the bottom — the row numbers a video lane drag speaks in.
  const videoRowCount = aboveTracks.length + 1;

  // Audio tracks mirror the title tracks: clips carry a `lane`; used lanes
  // compact to contiguous display rows, so empty tracks disappear on their own.
  // Drop preview while an audio asset is dragged over the timeline: which row
  // (one past the end = new track), at what time, for how long.
  const [audioDrop, setAudioDrop] = useDropPreview<{
    row: number;
    t: number;
    len: number;
  } | null>(null);
  const audioRef = useRef<HTMLDivElement>(null);
  const overlayRef = useRef<HTMLDivElement>(null);
  const audioLanes = useMemo(() => {
    const used = [...new Set(audioClips.map((a) => a.lane ?? 0))].sort((a, b) => a - b);
    const rowOf = new Map(used.map((l, i) => [l, i]));
    return { used, rowOf, count: used.length };
  }, [audioClips]);
  // What the gutter's track-wide eye/speaker reflect and flip, tallied per
  // video track. Sound counts only clips whose source carries audio, so an
  // all-image track offers no speaker.
  const trackState = useMemo(() => {
    const m = new Map<
      number,
      { total: number; hidden: number; sound: number; muted: number }
    >();
    const byId = new Map(assets.map((a) => [a.id, a]));
    for (const c of clips) {
      const t = m.get(c.track) ?? { total: 0, hidden: 0, sound: 0, muted: 0 };
      t.total++;
      if (c.hidden) t.hidden++;
      const asset = byId.get(c.assetId);
      // Sound the track actually carries — a video with no audio of its own
      // has nothing to mute, so its row shows no speaker. It is also what sets
      // the row height: every clip with sound draws a band, muted or not.
      if (asset && asset.type === "video" && !!asset.peaks?.length) {
        t.sound++;
        if (c.muted) t.muted++;
      }
      m.set(c.track, t);
    }
    return m;
  }, [clips, assets]);
  // The same tally per soundtrack lane; `hidden` is an audio segment's mute.
  const audioLaneState = useMemo(() => {
    const m = new Map<number, { total: number; hidden: number }>();
    for (const a of audioClips) {
      const lane = a.lane ?? 0;
      const t = m.get(lane) ?? { total: 0, hidden: 0 };
      t.total++;
      if (a.hidden) t.hidden++;
      m.set(lane, t);
    }
    return m;
  }, [audioClips]);
  // And per title lane.
  const textLaneState = useMemo(() => {
    const m = new Map<number, { total: number; hidden: number }>();
    for (const o of overlays) {
      const lane = o.lane ?? 0;
      const t = m.get(lane) ?? { total: 0, hidden: 0 };
      t.total++;
      if (o.hidden) t.hidden++;
      m.set(lane, t);
    }
    return m;
  }, [overlays]);
  // Reveals the resting toggles while the pointer is over the track area;
  // a toggle whose track has anything off stays visible on its own.
  const [trackHover, setTrackHover] = useState(false);

  // A whole row on its way to a new place in its band. The gutter is the
  // handle: a press there grabs the row it sits on, and the drag stays inside
  // that band — a row is only ever above or below its own kind, so there is
  // nowhere else for it to go.
  const [rowDrag, setRowDrag] = useState<RowDrag | null>(null);
  // The band's rows in screen space, top row first. The video stack measures
  // its own row elements (their heights vary with the mask key rail); the
  // stacked bands are uniform, so their rows come off the band's top edge.
  const rowBoxes = useCallback((band: RowBand): RowBox[] => {
    if (band === "video") return videoRows();
    const el = band === "overlay" ? overlayRef.current : audioRef.current;
    return Array.from(el?.querySelectorAll<HTMLElement>("[data-tl-row]") ?? [], (row) => {
      const r = row.getBoundingClientRect();
      return { top: r.top, h: r.height };
    });
  }, []);
  const videoRowBoxes = useCallback(() => rowBoxes("video"), [rowBoxes]);
  const audioRowBoxes = useCallback(() => rowBoxes("audio"), [rowBoxes]);
  const overlayRowBoxes = useCallback(() => rowBoxes("overlay"), [rowBoxes]);
  /** The row boxes a stacked band lays out for its used rows, so gestures
   * can read the band's geometry live. */
  const rowMarks = (n: number, h: number, shift: number) =>
    Array.from({ length: n }, (_, r) => (
      <div
        key={`row-${r}`}
        data-tl-row=""
        className="pointer-events-none absolute inset-x-0"
        style={{ top: r * h + shift, height: h }}
      />
    ));
  // Grab a row by its gutter cell and carry it to a new place in the band.
  const gripRow = (band: RowBand, row: number) => (e: React.PointerEvent) => {
    const rows = rowBoxes(band);
    if (e.button !== 0 || rows.length < 2 || row >= rows.length) return;
    const held = rows[row];
    const first = rows[0];
    const last = rows[rows.length - 1];
    // The carried row travels between the band's own edges and no further.
    const floor = first.top - held.top;
    const ceil = last.top + last.h - (held.top + held.h);
    let to = row;
    setRowDrag({ band, from: row, to, dy: 0, rows, left: 0, width: 0 });
    const view = scrollRef.current?.getBoundingClientRect();
    const left = view?.left ?? 0;
    const width = view?.width ?? 0;
    startDrag(e, {
      cursor: () => "grabbing",
      onMove: (_dx, dy) => {
        const travel = Math.max(floor, Math.min(ceil, dy));
        const mid = held.top + held.h / 2 + travel;
        to = rows.length - 1;
        for (let i = 0; i < rows.length; i++)
          if (mid < rows[i].top + rows[i].h) {
            to = i;
            break;
          }
        setRowDrag({ band, from: row, to, dy: travel, rows, left, width });
      },
      onUp: () => {
        setRowDrag(null);
        if (to === row) return;
        const s = useEditor.getState();
        // The video stack draws top-down but numbers bottom-up, so its rows
        // reach the store flipped.
        if (band === "video") s.moveVideoTrack(rows.length - 1 - row, rows.length - 1 - to);
        else if (band === "overlay") s.moveOverlayLane(row, to);
        else s.moveAudioLane(row, to);
      },
    });
  };
  /** A stacked band's row top while a row drag runs: the carried row rides the
   * pointer, the rest sit at the place they are closing up into. */
  const stackedRowTop = (band: "overlay" | "audio", row: number, h: number) =>
    rowDrag?.band !== band
      ? row * h
      : row === rowDrag.from
        ? row * h + rowDrag.dy
        : shownRow(rowDrag, row) * h;
  /** The same for the video stack, where rows are laid out in flow and shift
   * by a transform instead. */
  const videoRowShift = (row: number) => {
    if (rowDrag?.band !== "video") return 0;
    const step = rowDrag.rows[rowDrag.from].h + ROW_GAP;
    if (row === rowDrag.from) return rowDrag.dy;
    if (rowDrag.from < rowDrag.to) return row > rowDrag.from && row <= rowDrag.to ? -step : 0;
    return row >= rowDrag.to && row < rowDrag.from ? step : 0;
  };

  // Chat mention token per audio clip ("@s1"), keyed by clip id — the same
  // handles the chat resolves against, so the token shown on hover is exactly
  // what pulls this sound into a message.
  const audioMentions = useMemo(() => {
    const map = new Map<string, string>();
    for (const ref of audioClipRefs(audioClips, assets)) {
      if (ref.handle) map.set(ref.id, `@${ref.handle}`);
    }
    return map;
  }, [audioClips, assets]);

  // The same, per video clip ("@c3"), across every track — an upper-track
  // insert is as referenceable as one on the spine, and the chip on hover is
  // exactly what pulls it into a message.
  const clipMentions = useMemo(() => {
    const map = new Map<string, string>();
    for (const ref of clipRefs(clips, assets)) {
      if (ref.handle) map.set(ref.id, `@${ref.handle}`);
    }
    return map;
  }, [clips, assets]);

  // The audio row under a screen y, by the resolver a lane drag aims with:
  // past either edge of the band, beyond the same reach, is a new lane there
  // (-1 above, one past the last below), and the row already aimed at holds
  // while the band shifts under the pointer. Before any audio exists there
  // are no rows, so everything resolves to 0.
  const audioRowAt = useCallback(
    (clientY: number): number =>
      resolveRow(audioRowBoxes(), clientY, audioDrop?.row ?? null, { top: true, bottom: true }),
    [audioRowBoxes, audioDrop]
  );

  // Every place on every video track a transition can sit: the cuts, where one
  // clip hands over to the next, and the open edges — a clip's head with
  // nothing before it, its tail with nothing after — where it arrives from or
  // leaves to nothing. Each boundary offers exactly one: two clips that touch
  // make a cut, and anything else is an edge. `len` is the room a transition
  // takes there, so a drop can show its footprint before it lands.
  const anchors = useMemo(() => {
    const out: Anchor[] = [];
    const collect = (list: ClipSpan[]) =>
      list.forEach((sp, i) => {
        const prev = list[i - 1];
        const next = list[i + 1];
        const end = sp.start + sp.len;
        // The same touch tolerance the blend goes live with, so an anchor is
        // a cut exactly when a transition dropped there would play.
        const openHead = !prev || prev.start + prev.len < sp.start - 0.02;
        const touchesNext = next && next.start <= end + 0.02;
        if (openHead) {
          out.push({
            kind: "in",
            clipId: sp.clip.id,
            at: sp.start,
            len: sp.clip.animIn?.seconds ?? 0,
          });
        }
        if (touchesNext) {
          out.push({
            kind: "cut",
            clipId: sp.clip.id,
            at: end,
            len: sp.clip.transition ?? 0,
          });
        } else {
          out.push({
            kind: "out",
            clipId: sp.clip.id,
            at: end,
            len: sp.clip.animOut?.seconds ?? 0,
          });
        }
      });
    collect(spans);
    overlayTrackSpans.forEach(collect);
    return out;
  }, [spans, overlayTrackSpans]);
  // The boundary a drop lands on: the closest one within the same magnet reach
  // a dragged bar snaps by. Past that there is no boundary in play and the bar
  // parks where it was dropped.
  const nearestAnchor = (t: number) => {
    const best = anchors.reduce<Anchor | null>(
      (found, a) => (!found || Math.abs(a.at - t) < Math.abs(found.at - t) ? a : found),
      null
    );
    return best && Math.abs(best.at - t) <= XBAR_MAGNET_PX / pps ? best : null;
  };

  // Every transition bar in the doc, live or parked. A bar is its own object
  // on the row: the clips it happens to line up with decide whether it plays,
  // and moving or deleting clips leaves it exactly where it is.
  const bars = useEditor((s) => s.transitions);
  const barRoles = useMemo(() => resolveTransitions(clips, bars), [clips, bars]);
  const transitions = useMemo<XBar[]>(
    () =>
      bars
        .map((t) => {
          // A bar can play several same-instant boundaries; the rank-first
          // one names it on the row.
          const role = barRoles.get(t.id)?.[0] ?? null;
          return { t, role };
        })
        .sort((a, b) => a.t.start - b.t.start),
    [bars, barRoles]
  );

  /** How a bar reads on the row: its style, and the edge it plays when it
   * plays one, e.g. "Cross fade in". */
  const barLabel = (x: XBar) => {
    const name = transitionLabel(x.t.style);
    if (x.role?.kind === "in") {
      return tr("transitionIn", { name });
    }
    if (x.role?.kind === "out") {
      return tr("transitionOut", { name });
    }
    return name;
  };

  /** The room a bar of `style` takes at this anchor: whatever already plays
   * there, or that style's own default length. */
  const anchorLen = (a: Anchor, style: TransitionStyle) =>
    a.len || transitionDefaultSeconds(style);

  /** Where a bar of `len` seconds sits when it lands on this anchor: an
   * entrance starts at the clip's head, a cross dissolve straddles the cut,
   * everything else ends on the boundary. */
  const anchorBarStart = (a: Anchor, len: number, style: TransitionStyle) =>
    transitionBarStart(style, a.kind, a.at, len);
  /** The box a bar draws in. Its window is [start, start+seconds], but the box
   * floors at a readable width, so it is pinned to the instant it claims: a
   * cross dissolve stays centered on the cut it straddles, an entrance keeps
   * its head on the boundary, everything else keeps its tail there. */
  const barBox = (
    t: Pick<TimelineTransition, "start" | "seconds" | "style">,
    kind: TransitionBoundaryKind
  ) => {
    const width = Math.max(14, t.seconds * pps - CLIP_GAP);
    const left =
      kind === "in"
        ? t.start * pps
        : isAudioTransition(t.style)
          ? (t.start + t.seconds / 2) * pps - width / 2
          : (t.start + t.seconds) * pps - width;
    return { left, width };
  };

  /** The bar already playing this anchor's boundary, if any — through any of
   * its roles, so a bar serving several same-instant boundaries is the
   * incumbent at each of them. */
  const barAt = (a: Anchor) =>
    bars.find((t) =>
      (barRoles.get(t.id) ?? []).some((r) => r.kind === a.kind && r.clipId === a.clipId)
    ) ?? null;

  /** Land a new bar from the panel: it takes the nearest anchor when one is
   * around, replacing whatever played there, and sits free anywhere else. */
  const dropTransitionAt = (time: number, style: TransitionStyle) => {
    const st = useEditor.getState();
    if (st.readOnly) return;
    const a = nearestAnchor(time);
    const len = a ? anchorLen(a, style) : transitionDefaultSeconds(style);
    st.beginHistoryBatch();
    const incumbent = a ? barAt(a) : null;
    if (incumbent) st.removeTransition(incumbent.id);
    const id = st.addTransition({
      start: a ? anchorBarStart(a, len, style) : time,
      seconds: len,
      style,
    });
    st.endHistoryBatch();
    st.select({ kind: "transition", id });
  };
  // A transition copied from a catalog tile uses the panel drop placement.
  const dropTransitionRef = useRef(dropTransitionAt);
  useEffect(() => {
    dropTransitionRef.current = dropTransitionAt;
  });
  useEffect(
    () => registerTransitionLanding((time, style) => dropTransitionRef.current(time, style)),
    []
  );

  const moveTransition = (e: React.PointerEvent, x: XBar) => {
    startLaneMove(e, "transition", x.t.id, {
      pps, rows: () => [], homeRow: 0, onDrag: setLaneDrag, onSnap: setSnapX,
    });
  };

  const trimTransition = (e: React.PointerEvent, x: XBar, side: "l" | "r") => {
    startLaneTrim(e, "transition", x.t.id, side, {
      pps, onSnap: setSnapX,
    });
  };

  // The landing preview for a shape, sticker or effect dragged out of a
  // panel, drawn the way a bar drag is: the slot outline on the target row
  // where the drop lands, and the bar itself carried at the pointer (`y` is
  // the bar's top in band pixels).
  const [elementDrop, setElementDrop] = useDropPreview<{
    row: number;
    t: number;
    y: number;
  } | null>(null);
  const overlayRowAt = (clientY: number): number =>
    resolveRow(overlayRowBoxes(), clientY, elementDrop?.row ?? null, { top: true, bottom: true });
  // The place a dragged transition would land on, marked with the footprint it
  // would take while it is in flight.
  const [jointDrop, setJointDrop] = useDropPreview<Anchor | null>(null);
  // A transition tile from the panel is over the timeline, and which style it
  // carries: the row lights every place a drop could play, the same as a bar
  // drag does, each zone sized and placed the way that style lands.
  const [xTileDrag, setXTileDrag] = useState<TransitionStyle | null>(null);
  // The browser needs the accept and the cursor from a `dragover` handler
  // itself. Everything else the handler decides — the layout reads that find
  // the row and the time, the ripple, the preview state — waits for the next
  // animation frame, and a burst of dragover events between two frames paints
  // once, from the last position. The thread stays clear while the drag is
  // in flight, so the release is handled the moment it comes.
  const previewFrame = useRef<number | null>(null);
  const previewNext = useRef<(() => void) | null>(null);
  const schedulePreview = useCallback((paint: () => void) => {
    previewNext.current = paint;
    if (previewFrame.current !== null) return;
    previewFrame.current = requestAnimationFrame(() => {
      previewFrame.current = null;
      const run = previewNext.current;
      previewNext.current = null;
      run?.();
    });
  }, []);
  // A drop, a leave or an end clears the previews; a paint still queued from
  // the last dragover would put one back, so it is dropped with them.
  const cancelPreview = useCallback(() => {
    if (previewFrame.current !== null) cancelAnimationFrame(previewFrame.current);
    previewFrame.current = null;
    previewNext.current = null;
  }, []);
  useEffect(() => cancelPreview, [cancelPreview]);
  // An empty timeline starts incoming footage at zero.
  const dropTimeAt = (clientX: number) => (total <= 0 ? 0 : Math.max(0, timeAt(clientX)));
  // Every drag ends here, wherever it was released: the landing previews and
  // the placement hold clear on the browser's own `dragend`, which fires for
  // a drop the timeline took, a release elsewhere, and an escape alike. An
  // OS file drag has no source in the page, so no `dragend` follows it; its
  // release is the window's `drop`, which ends it the same way. No preview
  // can outlive its drag and sit on the rows into the next one.
  useEffect(() => {
    const end = () => {
      cancelPreview();
      setAssetDrop(null);
      endCrossDrag();
      setAudioDrop(null);
      setDropType(null);
      setElementDrop(null);
      setJointDrop(null);
      setXTileDrag(null);
    };
    window.addEventListener("dragend", end, true);
    // Bubble phase: the timeline's own drop runs first and stashes the file
    // landing off the rows before they clear.
    window.addEventListener("drop", end);
    return () => {
      window.removeEventListener("dragend", end, true);
      window.removeEventListener("drop", end);
    };
  }, [cancelPreview, setAssetDrop, endCrossDrag, setAudioDrop, setElementDrop, setJointDrop]);
  // The landing an OS file release resolved to, handed to the editor's file
  // drop through `registerFileLanding`. Stashed by this surface's own drop,
  // which runs first; a release the surface never saw resolves from the
  // geometry at the moment of asking.
  const fileLanding = useRef<{ at: number; place: TrackTarget; audioRow: number } | null>(null);
  const footerRef = useRef<HTMLElement>(null);
  useEffect(
    () =>
      registerFileLanding((x, y) => {
        const stashed = fileLanding.current;
        fileLanding.current = null;
        if (stashed) return stashed;
        // The surface that takes the drop is the region a file lands in, the
        // ruler and the reach past the stack included.
        const surface = footerRef.current;
        if (!surface) return null;
        const r = surface.getBoundingClientRect();
        if (y < r.top || y > r.bottom || x < r.left || x > r.right) return null;
        return { at: dropTimeAt(x), place: resolveDropTrack(y), audioRow: audioRowAt(y) };
      }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [resolveDropTrack, audioRowAt]
  );
  // A transition bar mid-drag, drawn where the pointer has it.
  // A drag past the top edge opens a row there, pushing the stack down by one
  // for as long as it is aimed that way.
  // A group drag aims every member at its own row, so the band opens as many
  // rows past either end as the set needs.
  const overlaySlots = laneDragSlots(laneDrag, "overlay");
  const audioSlots = laneDragSlots(laneDrag, "audio");
  const videoSlots = laneDragSlots(laneDrag, "video");
  const cueSlots = laneDragSlots(laneDrag, "cue");
  const rowsAbove = (slots: LaneDrag[]) => Math.max(0, ...slots.map((d) => -d.targetRow));
  const lastRow = (slots: LaneDrag[]) => Math.max(-1, ...slots.map((d) => d.targetRow));
  const topRowShift = Math.max(rowsAbove(overlaySlots), elementDrop?.row === -1 ? 1 : 0) * TEXT_H;
  const audioTopShift = Math.max(rowsAbove(audioSlots), audioDrop?.row === -1 ? 1 : 0) * AUDIO_ROW;

  // Scrub with auto-scroll when the pointer nears the viewport edges.
  //
  // Both boxes are measured once, at the press. Reading a rect forces the
  // browser to lay the page out, and a drag that measured per event paid for
  // two layouts before it could work out what time the pointer was over.
  const scrub = (e: React.PointerEvent) => {
    const s = useEditor.getState();
    if (s.playing) s.setPlaying(false);
    const el = scrollRef.current;
    const innerLeft = innerRef.current?.getBoundingClientRect().left ?? 0;
    const view = el?.getBoundingClientRect() ?? null;
    // The inner box travels with the scroller, so an auto-scroll shifts what
    // a given screen x means; tracking the shift keeps the measurement true
    // without re-reading the layout.
    const scroll0 = el?.scrollLeft ?? 0;
    const at = (clientX: number) =>
      Math.max(0, (clientX - innerLeft + ((el?.scrollLeft ?? 0) - scroll0)) / pps);
    useEditor.getState().seek(at(e.clientX));
    startDrag(e, {
      onMove: (_dx, _dy, ev) => {
        if (el && view) {
          if (ev.clientX > view.right - 36) el.scrollLeft += 14;
          else if (ev.clientX < view.left + 36) el.scrollLeft -= 14;
        }
        useEditor.getState().seek(at(ev.clientX));
      },
    });
  };

  // A press on empty track space: a click deselects and moves the playhead;
  // a drag sweeps a rubber-band that selects every bar it touches — the same
  // blue band the projects home uses. ⇧/⌘ keeps the prior selection under it.
  const [marquee, setMarquee] = useState<{
    left: number;
    top: number;
    width: number;
    height: number;
  } | null>(null);
  const deselectIfSelf = (e: React.PointerEvent) => {
    if (e.target !== e.currentTarget) return;
    const st = useEditor.getState();
    if (st.playing) st.setPlaying(false);
    st.seek(Math.max(0, timeAt(e.clientX)));
    const additive = additiveClick(e);
    const base = additive
      ? st.multiSelection.filter((m): m is NonNullable<Selection> => !!m)
      : [];
    const startX = e.clientX;
    const startY = e.clientY;
    let sweeping = false;
    startDrag(e, {
      onMove: (dx, dy, ev) => {
        if (!sweeping && Math.hypot(dx, dy) < 4) return;
        sweeping = true;
        const r = {
          left: Math.min(startX, ev.clientX),
          top: Math.min(startY, ev.clientY),
          width: Math.abs(ev.clientX - startX),
          height: Math.abs(ev.clientY - startY),
        };
        setMarquee(r);
        const hit = [...base];
        const seen = new Set(hit.map((m) => `${m.kind}:${m.id}`));
        scrollRef.current?.querySelectorAll<HTMLElement>("[data-tl-sel]").forEach((el) => {
          const b = el.getBoundingClientRect();
          const overlaps =
            b.left < r.left + r.width &&
            b.right > r.left &&
            b.top < r.top + r.height &&
            b.bottom > r.top;
          if (!overlaps) return;
          const tag = el.dataset.tlSel!;
          const cut = tag.indexOf(":");
          const kind = tag.slice(0, cut) as NonNullable<Selection>["kind"];
          const id = tag.slice(cut + 1);
          if (seen.has(tag)) return;
          seen.add(tag);
          hit.push({ kind, id });
        });
        useEditor.getState().setMultiSelection(hit);
      },
      onUp: (_dx, _dy, moved) => {
        setMarquee(null);
        if (!moved && !additive) useEditor.getState().select(null);
      },
    });
  };

  // Zoom that keeps a chosen time pinned under a chosen viewport x.
  const pendingAnchor = useRef<{ t: number; px: number } | null>(null);
  useLayoutEffect(() => {
    const el = scrollRef.current;
    const a = pendingAnchor.current;
    if (el && a) {
      el.scrollLeft = Math.max(0, PAD_SIDE + a.t * pps - a.px);
      pendingAnchor.current = null;
    }
  }, [pps]);

  const zoomTo = useCallback((next: number, anchorT?: number, anchorPx?: number) => {
    const el = scrollRef.current;
    const cur = useEditor.getState();
    const floor = el ? zoomFloor(el.clientWidth, projectDuration(cur)) : ZOOM_MIN;
    const clamped = Math.max(floor, Math.min(ZOOM_MAX, next));
    if (Math.abs(clamped - cur.pxPerSec) < 0.01) return;
    if (el) {
      const t = anchorT ?? playheadAt();
      const px = anchorPx ?? PAD_SIDE + t * cur.pxPerSec - el.scrollLeft;
      pendingAnchor.current = { t, px };
    }
    cur.setPxPerSec(clamped);
  }, []);

  const fit = useCallback(() => {
    const el = scrollRef.current;
    const dur = projectDuration(useEditor.getState());
    if (!el || dur <= 0) return;
    zoomTo(fitZoom(el.clientWidth, dur), 0, PAD_SIDE);
  }, [zoomTo]);

  // The editing tools, as the toolbar button and its menu row both invoke them.
  const split = useCallback(() => {
    useEditor.getState().splitAtPlayhead(skimAt() ?? undefined);
  }, []);
  const addText = useCallback(() => useEditor.getState().addOverlay(), []);
  const deleteSelection = useCallback(() => useEditor.getState().deleteSelection(), []);

  // Trackpad pinch / cmd+wheel zooms at the cursor; vertical wheel pans.
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const onWheel = (e: WheelEvent) => {
      if (e.ctrlKey || e.metaKey) {
        e.preventDefault();
        const rect = el.getBoundingClientRect();
        const px = e.clientX - rect.left;
        const cur = useEditor.getState().pxPerSec;
        const t = (el.scrollLeft + px - PAD_SIDE) / cur;
        zoomTo(cur * Math.exp(-e.deltaY * 0.012), t, px);
      } else if (Math.abs(e.deltaY) > Math.abs(e.deltaX)) {
        // When the tracks overflow vertically, let the wheel scroll them;
        // otherwise map vertical wheel to horizontal panning (the timeline is
        // mostly wide).
        if (el.scrollHeight <= el.clientHeight) {
          e.preventDefault();
          el.scrollLeft += e.deltaY;
        }
      }
    };
    el.addEventListener("wheel", onWheel, { passive: false });
    return () => el.removeEventListener("wheel", onWheel);
  }, [zoomTo]);

  // Track the viewport width so `contentW` can fill it end-to-end.
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const measure = () => {
      setViewportW(el.clientWidth);
      publishStripView(el);
    };
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  // Timeline-scoped keys: = / - zoom around the playhead, Home/End jump.
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      // The editor's rule decides, plus one of this row's own: Home and End
      // belong to a slider or a scrub bar that holds the keyboard.
      const target = e.target instanceof HTMLElement ? e.target : null;
      const s = useEditor.getState();
      if (shortcutDecline(e, { exportOpen: s.exportOpen }) || target?.tagName === "INPUT") return;
      // All four are bare keys. Held with a modifier they are the window's own
      // — ctrl+- and ctrl+= zoom the page, ctrl+Home and ctrl+End jump to its
      // ends — and answering those here would move two things at once.
      const bare = !e.metaKey && !e.ctrlKey && !e.altKey;
      if (!bare) return;
      if (e.key === "=" || e.key === "+") {
        e.preventDefault();
        zoomTo(s.pxPerSec * 1.3);
      } else if (e.key === "-" || e.key === "_") {
        e.preventDefault();
        zoomTo(s.pxPerSec / 1.3);
      } else if (e.key === "Home") {
        e.preventDefault();
        s.seek(0);
      } else if (e.key === "End") {
        e.preventDefault();
        s.seek(projectDuration(s));
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [zoomTo]);

  // Drop an asset onto the timeline: every kind lands free-form at time `t`
  // (sliding to its lane's next free slot); audio targets the hovered audio
  // row, one past the last row opening a new track; clip media past the video
  // stack's edges opens a new video track.
  const placeAssetAt = (
    assetId: string,
    type: "video" | "audio" | "image",
    t: number,
    audioRow = 0,
    place: TrackTarget = TRACK_ZERO,
    elementRow = 0
  ) => {
    const s = useEditor.getState();
    const sticker = stickerOf(s.assets.find((a) => a.id === assetId));
    if (sticker) {
      landOnRow("overlay", elementRow, (lane) => useEditor.getState().addSticker({
        assetId,
        ...(isLottieAsset(sticker) ? { lottie: true } : {}),
        at: t,
        lane,
      }));
      return;
    }
    if (isClipMedia(type)) {
      // A track drop lands at the pointer, rippling later clips right, so a
      // drop into a leading gap or between clips lands there.
      s.addVideoFromAsset(assetId, place, t);
    } else {
      landOnRow("audio", audioRow, (lane) =>
        useEditor.getState().addAudioFromAsset(assetId, t, { lane })
      );
    }
  };

  /** How much timeline one asset takes when it lands. */
  const laidLength = (asset: { type: string; duration: number }) =>
    asset.type === "image" ? STILL_SECONDS : asset.duration || STILL_SECONDS;

  /** Where the next asset of each kind lands. Video and audio run on their own
   * rows, so a group holding both lays two runs side by side; an element sits
   * at the pointer and takes no room from either. */
  const runCursor = (t: number, atElement: number) => {
    const at = { clip: t, audio: t };
    return (asset: MediaAsset, sticker: boolean) => {
      if (sticker) return atElement;
      const lane = isClipMedia(asset.type) ? "clip" : "audio";
      const start = at[lane];
      at[lane] = start + laidLength(asset);
      return start;
    };
  };

  /** Lay a carried run down in order, each item after the last — a single
   * card is a run of one, so every media drop takes this path. Each item is
   * landed in the project first (a copy, a download, or nothing at all), and
   * an item that fails leaves the rest of the run alone. `only` narrows the
   * run to what the row under the pointer accepts. */
  const placeCarriedAt = async (
    projectId: string,
    items: CarriedMedia[],
    t: number,
    atElement: number,
    audioRow = 0,
    place: TrackTarget = TRACK_ZERO,
    elementRow = 0,
    only?: (asset: MediaAsset) => boolean
  ) => {
    const next = runCursor(t, atElement);
    // One clip released on a block fills it: the footage takes the block's
    // place and its length, and the block goes with it.
    const block = blockUnder(items, t, place);
    for (const item of items) {
      try {
        const asset = await item.land(projectId);
        // The landing outlived a project switch: the asset belongs to the
        // project it was landed in.
        if (useEditor.getState().projectId !== projectId) return;
        if (isLinkedAssetType(asset.type)) continue;
        if (only && !only(asset)) continue;
        const sticker = !!stickerOf(asset);
        if (block && !sticker && isClipMedia(asset.type)) {
          useEditor.getState().replaceClipAsset(block.id, asset.id);
          continue;
        }
        placeAssetAt(asset.id, asset.type, next(asset, sticker), audioRow, place, elementRow);
      } catch (err) {
        reportSwallowed("[cut] drop failed", err, item.name);
      }
    }
  };

  /** What a video row takes: the clips, and none of the sound or elements a
   * mixed selection may also be carrying. */
  const clipsOnly = (asset: MediaAsset) => isClipMedia(asset.type) && !stickerOf(asset);

  /** The block a single carried clip would fill at this point.
   * A run of several clips inserts as a run — one block holds one shot. */
  const blockUnder = (items: { kind?: string }[], t: number, place: TrackTarget) => {
    // Only the clips count: one video dragged alongside its music is still one
    // shot, and both drop handlers have to agree on that or the same gesture
    // fills the block from one row and inserts beside it from another.
    if (items.filter((i) => isClipMedia(i.kind)).length !== 1 || place.kind !== "track" || place.track !== 0)
      return null;
    const cur = useEditor.getState();
    return blockClipAt(cur.clips, cur.assets, t);
  };

  // The video the drag carries — project media, a library clip, a stock clip
  // or an image (which lands as a still) — with the ghost its landing
  // segment paints. A sound or a sticker is no video.
  const draggedVideo = (e: React.DragEvent): { duration: number; ghost: DropGhost } | null => {
    const first = carriedMedia(e)[0];
    return first?.ghost ? { duration: first.duration, ghost: first.ghost } : null;
  };

  // Drop targets for the upper tracks and between-track seams: dragging a
  // video onto a lane adds it there; near a row's edge it aims at the seam and
  // opens a fresh track at that z-level. The pointer resolves through
  // `resolveDropTrack` — the same resolver internal clip drags use — so every
  // media flavor lands by one rule.
  const overlayDropHandlers = {
    onDragOver: (e: React.DragEvent) => {
      const vid = draggedVideo(e);
      if (!vid) return;
      e.preventDefault();
      e.stopPropagation();
      e.dataTransfer.dropEffect = "copy";
      const x = e.clientX;
      const y = e.clientY;
      // Read off the event now: the preview runs a frame later, with the
      // event long gone.
      const clips = carriedMedia(e).filter((item) => isClipMedia(item.kind)).length;
      schedulePreview(() => {
        setAssetDrop(null);
        setDropType("video"); // keep the insertion zones lit however the drag entered
        previewCross(resolveDropTrack(y), Math.max(0, timeAt(x)), vid.duration, vid.ghost, clips);
      });
    },
    onDragLeave: (e: React.DragEvent) => {
      if (e.currentTarget.contains(e.relatedTarget as Node | null)) return;
      cancelPreview();
      endCrossDrag();
    },
    onDrop: (e: React.DragEvent) => {
      // A sticker crossing a video row is still headed for the element rows,
      // and OS files belong to the timeline's own drop, which stashes their
      // landing for the editor's import and clears every preview; both pass
      // through here untouched. A LUT lands on a clip, which the footer's
      // drop resolves.
      if (hasElementDrag(e) || draggedSticker() || draggedFiles(e) || draggedLut(e)) return;
      e.preventDefault();
      e.stopPropagation();
      cancelPreview();
      const place = resolveDropTrack(e.clientY);
      const t = Math.max(0, timeAt(e.clientX));
      endCrossDrag();
      setDropType(null);
      // The whole carried run, read before the drag is cleared; the row
      // takes the clips in it and leaves the rest.
      const carried = carriedMedia(e).filter((item) => isClipMedia(item.kind));
      const projectId = useEditor.getState().projectId;
      clearAssetDrag();
      if (carried.length > 0 && projectId)
        void placeCarriedAt(projectId, carried, t, t, 0, place, undefined, clipsOnly);
    },
  };

  // Drag the panel's top border to resize; the border itself stays as-is,
  // only an invisible grab strip sits on top of it.
  const resize = (e: React.PointerEvent) => {
    const h0 = useEditor.getState().timelineH;
    startDrag(e, {
      onMove: (_dx, dy) => {
        useEditor.getState().setTimelineH(h0 - dy);
      },
    });
  };

  // The landing preview on a video row while the drag targets it. External
  // media paints the segment itself; an internal drag paints the plain slot —
  // the same chrome as the lane slots — since the dragged clip is its own ghost.
  const trackSlot = (place: TrackTarget, h: number) =>
    samePlacement(overlayDrop?.target ?? null, place) ? (
      overlayDrop!.ghost ? (
        <GhostClip ghost={overlayDrop!.ghost} t={overlayDrop!.t} len={overlayDrop!.len} h={h} pps={pps} />
      ) : (
        <div
          className="tl-drop-slot pointer-events-none absolute top-0.5 rounded-[2.5px] bg-[#0a84ff]/10 shadow-[inset_0_0_0_1.5px_rgba(10,132,255,0.4)] transition-[left] duration-150 ease-out"
          style={{
            left: overlayDrop!.t * pps,
            width: Math.max(10, overlayDrop!.len * pps - CLIP_GAP),
            height: h,
          }}
        />
      )
    ) : null;

  // Only empty space gets the menu: a right-click on an item sits on a
  // footprint, so the gap lookup misses and the event falls through to the
  // browser.
  const openGapMenu = (lane: LaneRef) => (e: React.MouseEvent) => {
    const gap = laneGapAt(useEditor.getState(), lane, timeAt(e.clientX));
    if (!gap) return;
    e.preventDefault();
    setGapMenu({ x: e.clientX, y: e.clientY, lane, gap });
  };

  // Audio and title rows stack inside one container, so the row comes from
  // where the pointer landed and the display row maps back to the lane the
  // items actually carry.
  const openStackedGapMenu =
    (kind: "audio" | "overlay", rowH: number, used: number[]) => (e: React.MouseEvent) => {
      const top = e.currentTarget.getBoundingClientRect().top;
      const index = used[Math.floor((e.clientY - top) / rowH)];
      if (index === undefined) return;
      openGapMenu({ kind, index })(e);
    };

  // The span the open gap menu would cut, tinted red on its own row.
  const gapHighlight = (lane: LaneRef, h: number, top = 0) =>
    gapMenu && sameLane(gapMenu.lane, lane) ? (
      <div
        className="pointer-events-none absolute z-10 rounded-[2.5px] bg-red-500/15"
        style={{
          left: gapMenu.gap.start * pps,
          width: Math.max(2, gapMenu.gap.len * pps - CLIP_GAP),
          height: h,
          top: top + 2,
        }}
      />
    ) : null;

  const insertionLine = (top: number, key?: number) => (
    <div key={key} data-tl-insertion="" className="pointer-events-none absolute inset-x-0 z-30 h-0.5 bg-[#0a84ff]" style={{ top }} />
  );
  const insertionMarks = (slots: LaneDrag[], h: number, shift: number, external?: number) =>
    [...new Set([...slots.map((slot) => slot.targetRow), ...(external === undefined ? [] : [external])])]
      .filter((row) => !Number.isInteger(row))
      .map((row) => insertionLine(Math.ceil(row) * h + shift - 1, row));
  const videoInsertion = (row: number, track: number) => row > 0 && (
    videoSlots.some((slot) => slot.targetRow === row - 0.5) ||
    (overlayDrop?.target.kind === "insert" && overlayDrop.target.level === track + 1)
  ) ? insertionLine(-4) : null;

  // The would-be new video track, one row past the stack's edge — the same
  // grown-row experience as the audio and title lanes. It mounts only while
  // the drag is out there, and it grows away from the stack (the top one
  // carries the rows below it down with the pointer's own ghost), so the row
  // the drag came from stays where it was. Dropping here opens a brand-new
  // track at z-level `level`.
  // A group drag can carry members several rows past the edge; each row it
  // reaches mounts, nearest the stack last on top and first below.
  const newTrackRow = (level: number) => {
    const place: TrackTarget = { kind: "insert", level };
    const edge = level === 0 ? videoRowCount : -1;
    const reach = level === 0 ? lastRow(videoSlots) - videoRowCount + 1 : rowsAbove(videoSlots);
    const aimed =
      reach > 0 ||
      (dropType === "video" && samePlacement(overlayDrop?.target ?? null, place));
    if (!aimed) return null;
    const rows = Array.from({ length: Math.max(1, reach) }, (_, i) => (level === 0 ? edge + i : edge - (reach - 1 - i)));
    return rows.map((row) => (
      <div key={row} className="relative mt-1.5" style={{ height: OVERLAY_H }}>
        {laneRail(OVERLAY_H - 2)}
        {row === edge && trackSlot(place, OVERLAY_H - 4)}
        {videoSlots.filter((d) => d.targetRow === row).map((d) => (
          <LaneSlot key={d.id} drag={d} pps={pps} top={2} barH={OVERLAY_H - 4} className={VIDEO_SLOT} />
        ))}
      </div>
    ));
  };


  return (
    <footer
      ref={footerRef}
      className="relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border bg-card select-none"
      style={{ height: timelineH }}
      // The floating object ghost (`setObjectDragImage`) hands over to this
      // surface's own landing previews while a drag is over it.
      data-segment-drop
      onDragOver={(e) => {
        // A LUT is a grade, so its landing is the clip under the pointer:
        // lit while the drag is over it, and none of the slot previews.
        if (draggedLut(e)) {
          e.preventDefault();
          e.dataTransfer.dropEffect = "copy";
          cancelPreview();
          setAssetDrop(null);
          setOverlayDrop(null);
          setAudioDrop(null);
          setDropType(null);
          const target = clipIdAt(e.clientX, e.clientY);
          setLutTarget((cur) => (cur === target ? cur : target));
          return;
        }
        // A template materializes as a whole arrangement, so it accepts the
        // drop without a single-clip landing preview.
        if (hasTemplateDrag(e)) {
          e.preventDefault();
          e.dataTransfer.dropEffect = "copy";
          cancelPreview();
          setAssetDrop(null);
          setOverlayDrop(null);
          setAudioDrop(null);
          setDropType(null);
          return;
        }
        // OS files: the editor's window-level drop imports them, and asks
        // this surface where they land. The browser withholds their bytes
        // until the release, so the landing paints as the plain slot at a
        // nominal length; the placed clip fills in once it is measured.
        const files = draggedFiles(e);
        if (files) {
          e.preventDefault();
          e.dataTransfer.dropEffect = "copy";
          const x = e.clientX;
          const y = e.clientY;
          const len =
            files.count * (files.kind === "image" ? STILL_SECONDS : FILE_SLOT_SECONDS);
          schedulePreview(() => {
            setElementDrop(null);
            setJointDrop(null);
            setXTileDrag(null);
            if (files.kind === "audio") {
              setDropType("audio");
              setAudioDrop({ row: audioRowAt(y), t: dropTimeAt(x), len });
              setAssetDrop(null);
              setOverlayDrop(null);
              return;
            }
            setDropType("video");
            setAudioDrop(null);
            setAssetDrop(null);
            // The slot paints on the row the drop resolves to — the one under
            // the pointer, or the new track past the stack — the same way an
            // asset drag previews across the rows.
            previewCross(resolveDropTrack(y), dropTimeAt(x), len);
          });
          return;
        }
        const carried = carriedMedia(e);
        const element = hasElementDrag(e) ? draggingElement() : null;
        if (carried.length === 0 && !element) return;
        e.preventDefault();
        e.dataTransfer.dropEffect = "copy";
        // What the event carries is read now — the drag data is only readable
        // while the handler runs — and the preview paints from it on the next
        // frame (`schedulePreview`).
        const x = e.clientX;
        const y = e.clientY;
        // An element — a sticker, or a shape or effect from a panel — lands on
        // the element rows, so none of the clip previews apply to it.
        if (element || draggedSticker()) {
          // The band paints the bar being carried; a "move" cursor keeps the
          // copy badge off it.
          e.dataTransfer.dropEffect = "move";
          schedulePreview(() => {
            setAssetDrop(null);
            setOverlayDrop(null);
            setAudioDrop(null);
            setDropType(null);
            // An empty band has no rows to hit; the drag opens the first one,
            // where the drop will land.
            const row =
              !element || element.kind !== "transition"
                ? overlayRowAt(y)
                : null;
            // The pointer's own time, not `dropTimeAt`: an empty timeline pins
            // clip drops to 0, but an element rides wherever it is held.
            const bandTop = overlayRef.current?.getBoundingClientRect().top;
            setElementDrop(
              row !== null
                ? {
                    row,
                    t: Math.max(0, timeAt(x)),
                    y:
                      bandTop !== undefined
                        ? y - bandTop - (TEXT_H - 6) / 2
                        : row * TEXT_H + 2,
                  }
                : null
            );
            setXTileDrag(element?.kind === "transition" ? element.style : null);
            setJointDrop(
              element?.kind === "transition" ? nearestAnchor(Math.max(0, timeAt(x))) : null
            );
          });
          return;
        }
        // Preview where the grabbed item would land: a video on its row, a
        // sound free-form on its lane. Every tile carries the same shape,
        // whether or not the item is in the project yet.
        const type = carried[0]?.kind;
        const duration = carried[0]?.duration ?? 0;
        // What the ghost paints: the source's frames, from wherever it lives.
        const ghost = draggedVideo(e)?.ghost;
        schedulePreview(() => {
          setElementDrop(null);
          setJointDrop(null);
          setXTileDrag(null);
          // A still rides the video tracks: reveal their guides and new-track rows.
          setDropType(isClipMedia(type) ? "video" : type ?? null);
          if (type === "audio") {
            // Preview which audio row the sound would land on.
            setAudioDrop({ row: audioRowAt(y), t: dropTimeAt(x), len: duration });
            setAssetDrop(null);
            return;
          }
          setAudioDrop(null);
          if (!isClipMedia(type) || !duration) {
            setAssetDrop(null);
            return;
          }
          // Past the stack's edges the drop opens a new track: preview it in
          // the would-be new row instead of track 0.
          const place = resolveDropTrack(y);
          if (place.kind === "insert") {
            setAssetDrop(null);
            setOverlayDrop({ target: place, t: dropTimeAt(x), len: duration, ghost });
            return;
          }
          setOverlayDrop(null);
          // Over a block the drop fills it, so the ghost takes the block's
          // own span — its start, its length, nothing rippling.
          const cur = useEditor.getState();
          const block = blockUnder(carried, Math.max(0, timeAt(x)), place);
          if (block) {
            setAssetDrop({ t: block.start, len: clipLen(block), ghost, shifts: [] });
            return;
          }
          // Preview the true landing spot: a drop at the pointer inserts here,
          // rippling later clips right, so the ghost sits where the segment will
          // actually land — a box under the pointer that lands minutes away lies.
          const { start, shifts } = rippleInsert(track0Clips(cur.clips), dropTimeAt(x), duration);
          setAssetDrop({ t: start, len: duration, ghost, shifts });
        });
      }}
      onDragLeave={(e) => {
        if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {
          cancelPreview();
          setLutTarget(null);
          setAssetDrop(null);
          endCrossDrag();
          setAudioDrop(null);
          setDropType(null);
          setElementDrop(null);
          setJointDrop(null);
          setXTileDrag(null);
        }
      }}
      onDrop={(e) => {
        cancelPreview();
        // A LUT dropped on a clip becomes that clip's grade LUT — the whole
        // selection's when the clip is selected. The clip never moves.
        const lut = draggedLut(e);
        if (lut) {
          e.preventDefault();
          const target = lutTarget ?? clipIdAt(e.clientX, e.clientY);
          setLutTarget(null);
          clearAssetDrag();
          if (!target) return;
          const st = useEditor.getState();
          const picked = st.multiSelection
            .filter((m): m is { kind: "clip"; id: string } => !!m && m.kind === "clip")
            .map((m) => m.id);
          const ids = picked.includes(target) ? picked : [target];
          st.beginHistoryBatch();
          try {
            for (const id of ids) {
              const clip = st.clips.find((c) => c.id === id);
              if (!clip) continue;
              st.updateClip(id, {
                grade: normalizeGrade({ ...clip.grade, lut: { id: lut, amount: clip.grade?.lut?.amount } }),
              });
            }
          } finally {
            st.endHistoryBatch();
          }
          return;
        }
        // OS files: the window-level drop in the editor imports them and
        // reads the landing resolved here, before the previews (and the new
        // row a drag past the stack opened) clear under it.
        if (draggedFiles(e)) {
          fileLanding.current = {
            at: dropTimeAt(e.clientX),
            place: resolveDropTrack(e.clientY),
            audioRow: audioRowAt(e.clientY),
          };
        }
        // Resolve the hovered rows before the previews (and their rows) clear.
        const audioRow = audioRowAt(e.clientY);
        const elementRow = overlayRowAt(e.clientY);
        setElementDrop(null);
        setJointDrop(null);
        setXTileDrag(null);
        const videoPlace = resolveDropTrack(e.clientY);
        setAssetDrop(null);
        endCrossDrag();
        setAudioDrop(null);
        setDropType(null);
        const t = dropTimeAt(e.clientX);

        // Everything the drag is carrying — one card, or the whole marquee
        // selection it was grabbed from — read before the drag is cleared.
        const carried = carriedMedia(e);
        const tpl = draggingTemplate();
        const element = hasElementDrag(e) ? draggingElement() : null;
        const projectId = useEditor.getState().projectId;
        clearAssetDrag();
        clearElementDrag();
        // Elements land at the pointer's own time, not `dropTimeAt`, which
        // pins everything to 0 on an empty timeline — a clip starts the film
        // there, but an element lands where it was dropped.
        const atElement = Math.max(0, timeAt(e.clientX));
        if (element) {
          e.preventDefault();
          if (element.kind === "transition") dropTransitionAt(t, element.style);
          else landOnRow("overlay", elementRow, (lane) => {
            const aim = { at: atElement, lane };
            if (element.kind === "shape") useEditor.getState().addShape(element.shape, aim);
            else useEditor.getState().addEffect(element.effect, aim);
          });
          return;
        }
        if (tpl && projectId) {
          e.preventDefault();
          if (tpl.scope === "project") void addProjectTemplateToTimeline(projectId, tpl.template, t);
          else
            void addTemplateToProject(projectId, tpl.template, t).catch((err: unknown) =>
              reportSwallowed("[cut] template drop failed", err)
            );
          return;
        }
        if (carried.length > 0 && projectId) {
          e.preventDefault();
          void placeCarriedAt(projectId, carried, t, atElement, audioRow, videoPlace, elementRow);
        }
      }}
    >
      <div
        className="tl-resize absolute inset-x-0 top-0 z-30 h-1.5 cursor-row-resize"
        title={tr("resize")}
        onPointerDown={resize}
      />
      {/* Three tracks with the transport in the middle, so playback sits centred
          on the timeline and holds its place whatever flanks it. The editing
          tools and the zoom both fold into one menu on the right when the bar
          runs out of room: which of them is on screen may change with the
          window, but the play controls never do. */}
      <div
        ref={barRef}
        className="relative grid h-11 shrink-0 grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center border-b border-border"
      >
        {/* Clipped, so a tool can never reach the transport however the
            measurement below lands: the overlap stops being something to get
            right and becomes something that cannot be drawn. */}
        <div className="col-start-1 row-start-1 ml-2.5 flex min-w-0 items-center gap-0.5 overflow-hidden">
          <TimelinePicker />
          {!barTight && (
            <TimelineTools
              split={split}
              addText={addText}
              deleteSelection={deleteSelection}
              selectionCount={multiSelection.length}
            />
          )}
        </div>

        {/* Measure the contextual icons even when they fold into the menu. */}
        <div aria-hidden className="invisible pointer-events-none absolute flex items-center gap-0.5">
          <div ref={toolsBareRef} className="flex items-center gap-0.5">
            <TimelinePicker />
            <TimelineTools
              split={split}
              addText={addText}
              deleteSelection={deleteSelection}
              selectionCount={multiSelection.length}
            />
          </div>
        </div>

        <div ref={transportRef} className="col-start-2 row-start-1 flex items-center">
          <Transport total={total} />
        </div>

        <div className="col-start-3 row-start-1 mr-2.5 flex min-w-0 items-center justify-end gap-2 overflow-hidden">
          <div
            ref={zoomRef}
            className={cn(
              "flex items-center gap-2",
              barTight && "invisible absolute right-0 pointer-events-none"
            )}
          >
            <GuidesMenu />
            <Slider
              className="data-horizontal:w-28"
              min={0}
              max={100}
              step={0.1}
              value={zoomToSlider(pps, zoomMin)}
              aria-label={tr("zoom")}
              onValueChange={(v) => zoomTo(sliderToZoom(Number(v), zoomMin))}
            />
            <Button variant="ghost" size="sm" title={tr("fitTitle")} onClick={fit}>
              {tr("fit")}
            </Button>
            <HideTimelineButton />
          </div>
          {barTight && <GuidesMenu />}
          {barTight && (
            <TimelineToolsMenu
              pps={pps}
              zoomMin={zoomMin}
              zoomTo={zoomTo}
              fit={fit}
              split={split}
              addText={addText}
              deleteSelection={deleteSelection}
              selectionCount={multiSelection.length}
            />
          )}
        </div>
      </div>

      {/* Rubber-band overscroll translates the scroller's content and
          background wholesale, so the wrapper behind it paints the resting
          picture the bounce reveals: the card-white ruler band (with its
          baseline) over the track gray. The scroller stays transparent — the
          underlay IS the timeline's surface. */}
      <div
        className="relative min-h-0 flex-1 bg-muted"
        onPointerEnter={() => setTrackHover(true)}
        onPointerLeave={() => setTrackHover(false)}
      >
      <div className="pointer-events-none absolute inset-0 overflow-hidden">
        <div ref={rulerUnderlayRef} className="absolute inset-x-0 top-0">
          <RestingSurface railYs={railYs} empty={total <= 0} timelineH={timelineH} />
        </div>
      </div>
      <RulerBand />
      {total <= 0 && <EmptyTimelineNote />}
      {marquee && (
        <div
          className="pointer-events-none fixed z-50 rounded-[3px] border-2 border-[#0a84ff]"
          style={marquee}
        />
      )}
      {/* Where the carried row will sit once it lands. The rows have already
          closed up around the slot; the outline says it is the one. */}
      {rowDrag && rowDrag.to !== rowDrag.from && (
        <div
          className="pointer-events-none fixed z-50 rounded-md border border-dashed border-[#0a84ff]/70 bg-[#0a84ff]/5"
          style={{
            top: landingBox(rowDrag).top,
            height: landingBox(rowDrag).h,
            left: rowDrag.left,
            width: rowDrag.width,
          }}
        />
      )}
      <div
        ref={scrollRef}
        data-tl-scroll
        className="tl-scroll relative h-full overflow-auto overscroll-y-none"
      >
        {/* The side padding paints as timeline surface, so it scrubs like it:
            a press in the left strip reads as a negative time and seek clamps
            it to 0. */}
        <div
          className="relative flex min-h-full min-w-full flex-col"
          style={{ width: contentW + PAD_SIDE * 2 }}
          onPointerDown={deselectIfSelf}
        >
          <div
            ref={innerRef}
            className="tl-content relative flex-1"
            style={{ width: contentW, marginLeft: PAD_SIDE, paddingBottom: "calc(0.5rem + var(--host-inset-bottom, 0px))" }}
            onPointerDown={deselectIfSelf}
          >
          {/* An empty project reads as a stack of resting tracks: the same
              hairline rails the video rows draw, repeating to the bottom. */}
          {total <= 0 && (
            <div
              className="pointer-events-none absolute bottom-0"
              style={{
                top: RULER_H,
                left: -PAD_SIDE,
                right: -PAD_SIDE,
                background: REST_RAILS,
              }}
            />
          )}
          {/* Pinned over the vertical scroll: the rows slide under the band,
              the way the timeline runs under the gutter. The band paints its
              own surface pad to pad, and the playhead cap rides in it so the
              time being pointed at can always be grabbed. */}
          <div className="sticky top-0 z-50" style={{ height: RULER_H }}>
            <div
              className="absolute top-0 border-b border-border bg-card"
              style={{ height: RULER_H, left: -PAD_SIDE, width: contentW + PAD_SIDE * 2 }}
            />
            <Ruler pps={pps} width={contentW} onScrub={scrub} />
            <PlayheadCap pps={pps} onScrub={scrub} />
          </div>

          {/* Elements ride above the clip stack, the way they sit over the
              picture. New effects open the top row; a drag moves any of them
              to any row. */}
          {(overlays.length > 0 || elementDrop !== null) && (
            <div
              ref={overlayRef}
              data-tl-trows=""
              className="relative mt-1.5"
              style={{
                height:
                  Math.max(
                    overlayLanes.count,
                    // An in-flight element drag aimed under the band opens
                    // the rows it will land on.
                    lastRow(overlaySlots) + 1,
                    // A panel drag over an empty band opens the first row for
                    // its landing preview.
                    elementDrop !== null ? elementDrop.row + 1 : 0
                  ) *
                    TEXT_H +
                  topRowShift,
              }}
              onPointerDown={deselectIfSelf}
              onContextMenu={openStackedGapMenu("overlay", TEXT_H, overlayLanes.used)}
            >
              {Array.from(
                {
                  length:
                    Math.max(overlayLanes.count, (elementDrop?.row ?? -1) + 1, lastRow(overlaySlots) + 1) +
                    topRowShift / TEXT_H,
                },
                (_, r) => laneRail((r + 1) * TEXT_H - 4, r)
              )}
              {rowMarks(overlayLanes.count, TEXT_H, topRowShift)}
              {insertionMarks(overlaySlots, TEXT_H, topRowShift, elementDrop?.row)}
              {overlayLanes.used.map((lane, r) => (
                <Fragment key={`tgap-${lane}`}>
                  {gapHighlight(
                    { kind: "overlay", index: lane },
                    TEXT_H - 6,
                    stackedRowTop("overlay", r, TEXT_H) + topRowShift
                  )}
                </Fragment>
              ))}
              {elementDrop !== null &&
                (() => {
                  const el = draggingElement();
                  const family = el?.kind === "effect" ? "effect" : "element";
                  const sticker = el ? null : draggedSticker();
                  const chip =
                    el?.kind === "shape" ? (
                      <>
                        {(() => {
                          const Icon = SHAPE_CHIP_ICONS[el.shape];
                          return <Icon className="mr-1 size-2.5 shrink-0" />;
                        })()}
                        {shapeLabel(el.shape)}
                      </>
                    ) : el?.kind === "effect" ? (
                      <>
                        <EffectChipIcon effect={el.effect} />
                        {effectLabel(el.effect)}
                      </>
                    ) : (
                      <>
                        {sticker && !isLottieAsset(sticker) ? (
                          // eslint-disable-next-line @next/next/no-img-element -- project media URL
                          <img
                            src={sticker.url}
                            alt=""
                            className="mr-1 size-4 shrink-0 object-contain"
                          />
                        ) : (
                          <Sticker className="mr-1 size-2.5 shrink-0" />
                        )}
                        {tr("sticker")}
                      </>
                    );
                  return (
                    <>
                      <div
                        className={cn(
                          "pointer-events-none absolute inset-x-0 rounded-[3px] border border-dashed",
                          FAMILY_STYLE[family].row
                        )}
                        style={{ top: elementDrop.row * TEXT_H + 2 + topRowShift, height: TEXT_H - 6 }}
                      />
                      {/* The slot the drop takes on its row... */}
                      <div
                        className={cn(
                          "pointer-events-none absolute rounded-[3px]",
                          FAMILY_STYLE[family].slot
                        )}
                        style={{
                          top: elementDrop.row * TEXT_H + 2 + topRowShift,
                          height: TEXT_H - 6,
                          left: elementDrop.t * pps,
                          width: Math.max(14, ELEMENT_DROP_SECONDS * pps - CLIP_GAP),
                        }}
                      />
                      {/* ...and the bar itself carried at the pointer, the
                          way a bar drag's ghost rides. */}
                      <div
                        className={cn(
                          "pointer-events-none absolute z-20 flex items-center overflow-hidden rounded-[3px] opacity-80 shadow-2xl",
                          FAMILY_STYLE[family].bar
                        )}
                        style={{
                          top: elementDrop.y,
                          height: TEXT_H - 6,
                          left: elementDrop.t * pps,
                          width: Math.max(14, ELEMENT_DROP_SECONDS * pps - CLIP_GAP),
                        }}
                      >
                        <span className="pointer-events-none flex min-w-0 items-center truncate px-2 text-[10.5px] font-medium text-white">
                          {chip}
                        </span>
                      </div>
                    </>
                  );
                })()}
              {overlaySlots.map((d) => (
                <LaneSlot
                  key={d.id}
                  drag={d}
                  pps={pps}
                  top={d.targetRow * TEXT_H + 2 + topRowShift}
                  barH={TEXT_H - 6}
                  className={cn("rounded-[3px]", FAMILY_STYLE[slotFamily(d.id)].slot)}
                />
              ))}
              {overlays.map((o) => {
                const homeRow = overlayLanes.rowOf.get(o.lane ?? 0) ?? 0;
                const drag = laneDragFor(laneDrag, "overlay", o.id);
                return (
                  <TextBar
                    key={o.id}
                    overlay={o}
                    pps={pps}
                    top={stackedRowTop("overlay", homeRow, TEXT_H) + topRowShift}
                    homeRow={homeRow}
                    rowMove={
                      rowDrag?.band === "overlay"
                        ? homeRow === rowDrag.from
                          ? "lift"
                          : "part"
                        : null
                    }
                    rows={overlayRowBoxes}
                    selected={selKeys.has(`overlay:${o.id}`)}
                    drag={drag}
                    parting={laneDragParts(laneDrag, "overlay", o.id)}
                    onDrag={setLaneDrag}
                    onSnap={setSnapX}
                    onMenu={setBarMenu}
                  />
                );
              })}
            </div>
          )}

          {/* Transitions: free bars on their own row. Each plays the cut or
              clip edge it lines up with, and sits parked anywhere else. */}
          {(transitions.length > 0 || jointDrop !== null || xTileDrag) && (
            <div
              data-tl-xrows=""
              className="relative mt-1.5"
              style={{ height: TEXT_H }}
              onPointerDown={deselectIfSelf}
            >
              {laneRail(TEXT_H - 4, "xrail")}
              {xTileDrag &&
                // While a transition is in flight, every place it could play
                // lights up in the timeline's usual drop-zone dress: one slot
                // per cut and open edge, each the size the bar would take
                // there.
                anchors.map((a) => {
                  const style = xTileDrag ?? "crossfade";
                  const len = anchorLen(a, style);
                  return (
                    <div
                      key={`xzone-${a.kind}-${a.clipId}`}
                      className="pointer-events-none absolute rounded-[3px] bg-[#0a84ff]/10 shadow-[inset_0_0_0_1.5px_rgba(10,132,255,0.4)]"
                      style={{
                        ...barBox({ start: anchorBarStart(a, len, style), seconds: len, style }, a.kind),
                        top: 2,
                        height: TEXT_H - 6,
                      }}
                    />
                  );
                })}
              {jointDrop &&
                (() => {
                  // The zone the drop is aimed at burns brighter than the rest.
                  const style = xTileDrag ?? "crossfade";
                  const len = anchorLen(jointDrop, style);
                  return (
                    <div
                      className="pointer-events-none absolute rounded-[3px] bg-[#0a84ff]/25 shadow-[inset_0_0_0_1.5px_rgba(10,132,255,0.85)]"
                      style={{
                        ...barBox(
                          { start: anchorBarStart(jointDrop, len, style), seconds: len, style },
                          jointDrop.kind
                        ),
                        top: 2,
                        height: TEXT_H - 6,
                      }}
                    />
                  );
                })()}
              {transitions.map((live) => {
                const x = live;
                const drag = laneDragFor(laneDrag, "transition", x.t.id);
                const Icon = TRANSITION_ICONS[x.t.style];
                const playing = !!x.role;
                const label = barLabel(x);
                return (
                  <div
                    key={x.t.id}
                    role="button"
                    tabIndex={0}
                    title={tr("transitionTitle", { name: label, seconds: x.t.seconds.toFixed(1) })}
                    className={cn(
                      "tl-xfade-bar group absolute flex cursor-grab items-center gap-1 overflow-hidden rounded-[3px] px-1.5 text-[10.5px] font-medium text-white shadow-[inset_0_0_0_1px_rgba(0,0,0,0.1)]",
                      // A parked bar reads muted: it is on the row but playing
                      // nothing until a boundary lines up with it.
                      playing ? "bg-[#2B6FD4]" : "bg-muted-foreground/50",
                      x.t.hidden && "opacity-40 grayscale",
                      selKeys.has(`transition:${x.t.id}`) && SELECTED_SHADOW,
                      // Mid-drag it rides over the zone it would land on, so
                      // the marked room stays readable underneath.
                      drag && "opacity-75"
                    )}
                    style={{
                      ...barBox(drag ? { ...x.t, start: drag.ghostX / pps } : x.t, x.role?.kind ?? "cut"),
                      top: 2,
                      height: TEXT_H - 6,
                    }}
                    data-tl-sel={`transition:${x.t.id}`}
                    onPointerDown={(e) => moveTransition(e, x)}
                    onContextMenu={(e) => {
                      e.preventDefault();
                      setBarMenu({ x: e.clientX, y: e.clientY, id: x.t.id, transition: true });
                    }}
                  >
                    <Icon className="size-2.5 shrink-0" />
                    <span className="truncate">{label}</span>
                    <HideChip
                      hidden={!!x.t.hidden}
                      small
                      className="top-1/2 right-2 -translate-y-1/2"
                      onToggle={() =>
                        useEditor
                          .getState()
                          .updateTransition(x.t.id, { hidden: !x.t.hidden || undefined })
                      }
                    />
                    {(["l", "r"] as const).map((side) => (
                      <span
                        key={side}
                        title={tr("dragToTrim")}
                        className={cn(trimHandle, side === "l" ? "tl-trim-l left-0" : "tl-trim-r right-0")}
                        onPointerDown={(e) => trimTransition(e, x, side)}
                      />
                    ))}
                  </div>
                );
              })}
            </div>
          )}

          {/* A drag carried above the stack opens a new top layer: the row
              grows in here and folds away when the drag comes back down. */}
          {newTrackRow(topInsertLevel)}
          {aboveTracks.map((track, row) => {
            const trackSpans = overlayTrackSpans.get(track) ?? [];
            const railH = railFor(trackSpans);
            const rowH = videoRowH(trackSpans);
            const lifted = rowDrag?.band === "video" && rowDrag.from === row;
            return (
            <div
              key={`ov-${track}`}
              className={cn(
                "relative mt-1.5",
                rowDrag?.band === "video" && !lifted && "transition-transform duration-150 ease-out",
                lifted && "pointer-events-none z-20 opacity-90 drop-shadow-2xl"
              )}
              style={{
                height: rowH + railH,
                transform: videoRowShift(row) ? `translateY(${videoRowShift(row)}px)` : undefined,
              }}
              data-tl-vrow={track}
              onPointerDown={deselectIfSelf}
              onContextMenu={openGapMenu({ kind: "video", index: track })}
              {...overlayDropHandlers}
            >
              {videoInsertion(row, track)}
              {laneRail(rowH - 2 + railH)}
              {gapHighlight({ kind: "video", index: track }, rowH - 4)}
              {videoSlots.filter((d) => d.targetRow === row).map((d) => (
                <LaneSlot key={d.id} drag={d} pps={pps} top={2} barH={rowH - 4} className={VIDEO_SLOT} />
              ))}
              {trackSpans.map((span) => (
                <ClipView
                  key={span.clip.id}
                  span={span}
                  mention={clipMentions.get(span.clip.id)}
                  pps={pps}
                  selected={selKeys.has(`clip:${span.clip.id}`)}
                  lutTarget={lutTarget === span.clip.id}
                  drag={laneDragFor(laneDrag, "video", span.clip.id)}
                  parting={laneDragParts(laneDrag, "video", span.clip.id) || videoDragActive}
                  partAt={dropPartAt.get(span.clip.id)}
                  homeRow={row}
                  rows={videoRowBoxes}
                  onDrag={setLaneDrag}
                  onSnap={setSnapX}
                  onFrameMenu={openFrameMenu}
                />
              ))}
              {trackSlot({ kind: "track", track }, rowH - 4)}
            </div>
            );
          })}

          {/* An empty track 0 disappears like any other empty track. It
              renders while it has clips, while the whole project is empty
              (the first drop target), for the length of an external media
              drag, or once a drag targets it. An empty one that no row shows
              is reached by carrying the clip under the stack: the new-track
              row below opens track 0 again. */}
          {(spans.length > 0 ||
            total <= 0 ||
            dropType === "video" ||
            samePlacement(overlayDrop?.target ?? null, TRACK_ZERO)) && (
          <div
            className={cn(
              "relative mt-1.5",
              rowDrag?.band === "video" &&
                (rowDrag.from === aboveTracks.length
                  ? "pointer-events-none z-20 opacity-90 drop-shadow-2xl"
                  : "transition-transform duration-150 ease-out")
            )}
            style={{
              height: rowH0 + rail0,
              transform: videoRowShift(aboveTracks.length)
                ? `translateY(${videoRowShift(aboveTracks.length)}px)`
                : undefined,
            }}
            data-tl-vrow={0}
            onPointerDown={deselectIfSelf}
            onContextMenu={openGapMenu({ kind: "video", index: 0 })}
          >
            {videoInsertion(aboveTracks.length, 0)}
            {spans.length > 0 && laneRail(rowH0 - 2 + rail0)}
            {gapHighlight({ kind: "video", index: 0 }, rowH0 - 4)}
            {trackSlot(TRACK_ZERO, rowH0 - 4)}
            {videoSlots.filter((d) => d.targetRow === aboveTracks.length).map((d) => (
              <LaneSlot key={d.id} drag={d} pps={pps} top={2} barH={rowH0 - 4} className={VIDEO_SLOT} />
            ))}
            {assetDrop &&
              (assetDrop.ghost ? (
                <GhostClip ghost={assetDrop.ghost} t={assetDrop.t} len={assetDrop.len} h={rowH0 - 4} pps={pps} />
              ) : (
                <div
                  className="tl-drop-slot pointer-events-none absolute top-0.5 rounded-[2.5px] bg-[#0a84ff]/10 shadow-[inset_0_0_0_1.5px_rgba(10,132,255,0.4)] transition-[left] duration-150 ease-out"
                  style={{
                    left: assetDrop.t * pps,
                    width: Math.max(10, assetDrop.len * pps - CLIP_GAP),
                    height: rowH0 - 4,
                  }}
                />
              ))}
            {spans.map((span) => (
              <ClipView
                key={span.clip.id}
                span={span}
                mention={clipMentions.get(span.clip.id)}
                pps={pps}
                selected={selKeys.has(`clip:${span.clip.id}`)}
                lutTarget={lutTarget === span.clip.id}
                drag={laneDragFor(laneDrag, "video", span.clip.id)}
                parting={laneDragParts(laneDrag, "video", span.clip.id) || videoDragActive}
                partAt={dropPartAt.get(span.clip.id)}
                homeRow={aboveTracks.length}
                rows={videoRowBoxes}
                onDrag={setLaneDrag}
                onSnap={setSnapX}
                onFrameMenu={openFrameMenu}
              />
            ))}
          </div>
          )}

          {/* A drag carried under the stack grows it downward — nothing above
              moves. Dropping here opens a new track 0: the whole stack
              renumbers up and the spine (ripple, transitions) transplants onto
              the drop. */}
          {newTrackRow(bottomInsertLevel)}

          {(audioClips.length > 0 || audioDrop !== null) && (
            <div
              ref={audioRef}
              data-tl-arows=""
              className="relative mt-1.5"
              style={{
                height:
                  Math.max(
                    audioLanes.count,
                    // An in-flight audio drag aimed under the band opens the
                    // row it will land on.
                    lastRow(audioSlots) + 1,
                    (audioDrop?.row ?? -1) + 1
                  ) *
                    AUDIO_ROW -
                  ROW_GAP +
                  audioTopShift,
              }}
              onPointerDown={deselectIfSelf}
              onContextMenu={openStackedGapMenu("audio", AUDIO_ROW, audioLanes.used)}
            >
              {Array.from(
                {
                  length:
                    Math.max(audioLanes.count, (audioDrop?.row ?? -1) + 1, lastRow(audioSlots) + 1) +
                    audioTopShift / AUDIO_ROW,
                },
                (_, r) => laneRail(r * AUDIO_ROW + AUDIO_H - 2, r)
              )}
              {rowMarks(audioLanes.count, AUDIO_ROW, audioTopShift)}
              {insertionMarks(audioSlots, AUDIO_ROW, audioTopShift, audioDrop?.row)}
              {audioLanes.used.map((lane, r) => (
                <Fragment key={`agap-${lane}`}>
                  {gapHighlight(
                    { kind: "audio", index: lane },
                    AUDIO_H - 4,
                    stackedRowTop("audio", r, AUDIO_ROW) + audioTopShift
                  )}
                </Fragment>
              ))}
              {audioDrop && (
                <div
                  className="tl-audio-drop-slot pointer-events-none absolute rounded-[2.5px] border-[1.5px] border-dashed border-emerald-500/80 bg-emerald-500/10 transition-[left] duration-150 ease-out"
                  style={{
                    left: audioDrop.t * pps,
                    top: audioDrop.row * AUDIO_ROW + 2 + audioTopShift,
                    width: Math.max(10, audioDrop.len * pps - CLIP_GAP),
                    height: AUDIO_H - 4,
                  }}
                />
              )}
              {audioSlots.map((d) => (
                <LaneSlot
                  key={d.id}
                  drag={d}
                  pps={pps}
                  top={d.targetRow * AUDIO_ROW + 2 + audioTopShift}
                  barH={AUDIO_H - 4}
                  className="rounded-[2.5px] bg-emerald-500/10 shadow-[inset_0_0_0_1.5px_rgba(16,185,129,0.5)]"
                />
              ))}
              {audioClips.map((a) => {
                const homeRow = audioLanes.rowOf.get(a.lane ?? 0) ?? 0;
                const drag = laneDragFor(laneDrag, "audio", a.id);
                return (
                  <AudioView
                    key={a.id}
                    clip={a}
                    asset={assets.find((x) => x.id === a.assetId)}
                    mention={audioMentions.get(a.id)}
                    pps={pps}
                    top={stackedRowTop("audio", homeRow, AUDIO_ROW) + audioTopShift}
                    homeRow={homeRow}
                    rowMove={
                      rowDrag?.band === "audio"
                        ? homeRow === rowDrag.from
                          ? "lift"
                          : "part"
                        : null
                    }
                    rows={audioRowBoxes}
                    selected={selKeys.has(`audio:${a.id}`)}
                    drag={drag}
                    parting={laneDragParts(laneDrag, "audio", a.id)}
                    onDrag={setLaneDrag}
                    onSnap={setSnapX}
                  />
                );
              })}
            </div>
          )}

          {subtitles.showOnTimeline && subtitles.cues.length > 0 && (
            <div
              data-tl-srows=""
              className="tl-sub-track relative mt-1.5"
              style={{ height: subtitleLaneCount(subtitles) * SUB_H }}
              onPointerDown={deselectIfSelf}
            >
              {/* Cue lanes are fixed language tracks that may be empty; only
                  the occupied ones read as rows. */}
              {[...new Set(subtitles.cues.map((c) => c.lane ?? 0))].map((lane) =>
                laneRail((lane + 1) * SUB_H - 3, lane)
              )}
              {cueSlots.map((d) => (
                <LaneSlot
                  key={d.id}
                  drag={d}
                  pps={pps}
                  top={d.targetRow * SUB_H + 1}
                  barH={SUB_H - 4}
                  className="rounded-[2.5px] bg-amber-400/15 shadow-[inset_0_0_0_1.5px_rgba(245,158,11,0.55)]"
                />
              ))}
              {subtitles.cues.map((c) => (
                <SubBar
                  key={c.id}
                  cue={c}
                  dimmed={laneHidden(subtitles, c.lane ?? 0)}
                  pps={pps}
                  top={(c.lane ?? 0) * SUB_H}
                  homeRow={c.lane ?? 0}
                  selected={selKeys.has(`cue:${c.id}`)}
                  drag={laneDragFor(laneDrag, "cue", c.id)}
                  parting={laneDragParts(laneDrag, "cue", c.id)}
                  onDrag={setLaneDrag}
                  onSnap={setSnapX}
                />
              ))}
            </div>
          )}

            {snapX !== null && (
              <div
                className="pointer-events-none absolute top-0 bottom-0 z-20 w-px bg-[#ff2d55]"
                style={{ left: snapX }}
              />
            )}
            <HoverLine
              scrollRef={scrollRef}
              innerRef={innerRef}
              pps={pps}
              hold={frameMenu !== null}
            />
            <Playhead pps={pps} total={total} scrollRef={scrollRef} onScrub={scrub} />
          </div>
        </div>
      </div>
      {/* The gutter: the strip of surface at the left edge, held out of the
          scroll so the timeline runs under it instead of carrying it away.
          It is the width of the content's left pad, so at rest it sits over
          empty surface and the timeline looks no different — but the column
          is now a fixed place on screen, which is what per-track controls
          need. It paints the resting surface (rails following vertical
          scroll, the ruler band pinned like the live one) and passes
          presses through to the scrubbing surface beneath; controls will take
          their own pointer events when they land. Its face shows only once
          the timeline has scrolled: at rest the underlay behind the scroller
          paints the same pixels, and staying clear lets a clip at 0 keep the
          left side of its selection ring. */}
      <div
        ref={gutterFaceRef}
        className="pointer-events-none absolute inset-y-0 left-0 z-40 overflow-hidden bg-muted opacity-0 transition-opacity duration-150 data-scrolled:opacity-100"
        style={{ width: PAD_SIDE }}
      >
        <div ref={gutterRef} className="absolute inset-0">
          <RestingSurface railYs={railYs} empty={total <= 0} timelineH={timelineH} />
        </div>
        <RulerBand />
      </div>
      {/* Cast off the gutter's right edge alone, once the timeline has scrolled
          — that shadow is the whole tell that clips are running underneath
          rather than stopping there. A blurred box-shadow on the gutter would
          spill over its top and bottom too, so the edge draws its own strip:
          the same height as the gutter, starting where it ends. */}
      <div
        ref={gutterShadowRef}
        className="pointer-events-none absolute inset-y-0 z-40 w-2 bg-gradient-to-r from-black/20 to-transparent opacity-0 transition-opacity duration-150 data-scrolled:opacity-100"
        style={{ left: PAD_SIDE }}
      />
      {/* Track-wide toggles in the gutter column: an eye (and a speaker, when
          the track carries sound) per video track, a speaker per soundtrack
          lane. Resting toggles show while the pointer is over the track area;
          one whose track has anything off stays visible so the strip reads as
          the enabled/disabled readout. */}
      <div
        // Clipped below the ruler band, so a toggle scrolled to the top slides
        // under the band instead of riding up over it and the toolbar.
        className="pointer-events-none absolute bottom-0 left-0 z-50 overflow-hidden"
        style={{ width: PAD_SIDE, top: RULER_H }}
      >
        <div ref={gutterCtlRef} className="absolute inset-x-0 bottom-0" style={{ top: -RULER_H }}>
          {/* Each row's gutter cell is the handle for the row itself: press and
              carry it to another place in its own band. Drawn before the
              toggles so an eye or a speaker still takes its own press. */}
          {gutterYs.video.map(({ track, y, h }, row) => {
            const t = trackState.get(track);
            return (
              <RowGrip
                key={`vgrip-${track}`}
                top={y}
                height={h}
                barH={(t && t.sound === 0 ? VIDEO_H - WAVE_H : VIDEO_H) - 4}
                enabled={gutterYs.video.length > 1}
                onGrab={gripRow("video", row)}
              />
            );
          })}
          {gutterYs.textTop !== null &&
            overlayLanes.used.map((lane, r) => (
              <RowGrip
                key={`tgrip-${lane}`}
                top={gutterYs.textTop! + stackedRowTop("overlay", r, TEXT_H)}
                height={TEXT_H}
                barH={TEXT_H - 6}
                enabled={overlayLanes.count > 1}
                onGrab={gripRow("overlay", r)}
              />
            ))}
          {gutterYs.audioTop !== null &&
            audioLanes.used.map((lane, r) => (
              <RowGrip
                key={`agrip-${lane}`}
                top={gutterYs.audioTop! + stackedRowTop("audio", r, AUDIO_ROW)}
                height={AUDIO_H}
                barH={AUDIO_H - 4}
                enabled={audioLanes.count > 1}
                onGrab={gripRow("audio", r)}
              />
            ))}
          {gutterYs.video.map(({ track, y }, row) => {
            const t = trackState.get(track);
            if (!t) return null;
            // Centered on the clip band, which is shorter on a row that draws
            // no sound.
            const bandH = t.sound > 0 ? VIDEO_H : VIDEO_H - WAVE_H;
            const rows: React.ReactNode[] = [
              <GutterToggle
                key={`v-${track}-hide`}
                kind="hide"
                off={t.hidden === t.total}
                partial={t.hidden > 0}
                reveal={trackHover}
                top={y + (t.sound > 0 ? bandH / 2 - 22 : bandH / 2 - 8)}
                onGrab={gripRow("video", row)}
                onToggle={() =>
                  useEditor.getState().setTrackHidden(track, t.hidden !== t.total)
                }
              />,
            ];
            if (t.sound > 0)
              rows.push(
                <GutterToggle
                  key={`v-${track}-mute`}
                  kind="mute"
                  off={t.muted === t.sound}
                  partial={t.muted > 0}
                  reveal={trackHover}
                  top={y + bandH / 2 + 6}
                  onGrab={gripRow("video", row)}
                  onToggle={() =>
                    useEditor.getState().setTrackMuted(track, t.muted !== t.sound)
                  }
                />
              );
            return rows;
          })}
          {gutterYs.audioTop !== null &&
            audioLanes.used.map((lane, r) => {
              const t = audioLaneState.get(lane);
              if (!t) return null;
              return (
                <GutterToggle
                  key={`a-${lane}`}
                  kind="mute"
                  off={t.hidden === t.total}
                  partial={t.hidden > 0}
                  reveal={trackHover}
                  top={gutterYs.audioTop! + stackedRowTop("audio", r, AUDIO_ROW) + AUDIO_H / 2 - 8}
                  onGrab={gripRow("audio", r)}
                  onToggle={() =>
                    useEditor.getState().setAudioLaneHidden(lane, t.hidden !== t.total)
                  }
                />
              );
            })}
          {gutterYs.textTop !== null &&
            overlayLanes.used.map((lane, r) => {
              const t = textLaneState.get(lane);
              if (!t) return null;
              return (
                <GutterToggle
                  key={`t-${lane}`}
                  kind="hide"
                  off={t.hidden === t.total}
                  partial={t.hidden > 0}
                  reveal={trackHover}
                  top={gutterYs.textTop! + stackedRowTop("overlay", r, TEXT_H) + TEXT_H / 2 - 8}
                  onGrab={gripRow("overlay", r)}
                  onToggle={() =>
                    useEditor.getState().setTextLaneHidden(lane, t.hidden !== t.total)
                  }
                />
              );
            })}
          {gutterYs.xTop !== null && transitions.length > 0 && (
            <GutterToggle
              kind="hide"
              off={transitions.every((x) => x.t.hidden)}
              partial={transitions.some((x) => x.t.hidden)}
              reveal={trackHover}
              top={gutterYs.xTop + TEXT_H / 2 - 8}
              onToggle={() =>
                useEditor.getState().setTransitionsHidden(!transitions.every((x) => x.t.hidden))
              }
            />
          )}
          {gutterYs.subTop !== null &&
            Array.from({ length: subtitleLaneCount(subtitles) }, (_, lane) => {
              const off = laneHidden(subtitles, lane);
              return (
                <GutterToggle
                  key={`s-${lane}`}
                  kind="hide"
                  off={off}
                  partial={false}
                  reveal={trackHover}
                  top={gutterYs.subTop! + lane * SUB_H + SUB_H / 2 - 8}
                  onToggle={() => {
                    const s = useEditor.getState();
                    s.pushHistory();
                    s.setSubtitleTrackMeta(lane, { hidden: off ? undefined : true });
                  }}
                />
              );
            })}
        </div>
      </div>
      </div>
      {/* Subtle valid-target hint while an OS media drag is over the window:
          a tint and inset ring over the track area, under the toolbar. */}
      {fileDropHint && (
        <div className="pointer-events-none absolute inset-x-0 top-11 bottom-0 z-40 bg-[#0a84ff]/5 ring-2 ring-[#0a84ff]/30 ring-inset" />
      )}
      <DropdownMenu open={gapMenu !== null} onOpenChange={(o) => !o && setGapMenu(null)}>
        {gapMenu && (
          <DropdownMenuContent
            className="min-w-44"
            sideOffset={0}
            anchor={{ getBoundingClientRect: () => new DOMRect(gapMenu.x, gapMenu.y, 0, 0) }}
          >
            <DropdownMenuItem
              onClick={() => {
                useEditor.getState().removeLaneGap(gapMenu.lane, gapMenu.gap.start);
                setGapMenu(null);
              }}
            >
              <Scissors className="size-3.5 text-muted-foreground" /> {tr("removeEmptySpace")}
            </DropdownMenuItem>
          </DropdownMenuContent>
        )}
      </DropdownMenu>
      <DropdownMenu open={barMenu !== null} onOpenChange={(o) => !o && setBarMenu(null)}>
        {barMenu &&
          (() => {
            // The same menu over either kind of bar: an element on the title
            // rows, or a transition on its own row.
            const o = barMenu.transition
              ? (transitions.find((x) => x.t.id === barMenu.id)?.t ?? null)
              : (overlays.find((x) => x.id === barMenu.id) ?? null);
            if (!o) return null;
            return (
              <DropdownMenuContent
                className="min-w-44"
                sideOffset={0}
                anchor={{ getBoundingClientRect: () => new DOMRect(barMenu.x, barMenu.y, 0, 0) }}
              >
                {barMenu.key !== undefined && (
                  <DropdownMenuItem
                    onClick={() => {
                      const s = useEditor.getState();
                      s.pushHistory();
                      s.removeOverlayKey(barMenu.id, barMenu.key!);
                      setBarMenu(null);
                    }}
                  >
                    <Diamond className="size-3.5 text-muted-foreground" /> {tr("removeKeyframe")}
                  </DropdownMenuItem>
                )}
                <DropdownMenuItem
                  onClick={() => {
                    const s = useEditor.getState();
                    const hidden = !o.hidden || undefined;
                    if (barMenu.transition) s.updateTransition(barMenu.id, { hidden });
                    else s.updateOverlay(barMenu.id, { hidden: hidden ?? false });
                    setBarMenu(null);
                  }}
                >
                  {o.hidden ? (
                    <>
                      <Eye className="size-3.5 text-muted-foreground" /> {tr("show")}
                    </>
                  ) : (
                    <>
                      <EyeOff className="size-3.5 text-muted-foreground" /> {tr("hide")}
                    </>
                  )}
                </DropdownMenuItem>
              </DropdownMenuContent>
            );
          })()}
      </DropdownMenu>
      {/* Exports hover over the corner, after the tracks so they paint above
          the playhead and the ruler. */}
      <ExportsDock placement="timeline" />
      {frameMenu && (
        <div
          className="fixed inset-0 z-50"
          onPointerDown={() => setFrameMenu(null)}
          onContextMenu={(e) => {
            e.preventDefault();
            setFrameMenu(null);
          }}
        >
          <FrameBubble x={frameMenu.x} y={frameMenu.y}>
            {(flip) => (
              <>
                <div className="rounded-lg border bg-popover p-1 text-popover-foreground shadow-md">
                  <button
                    className="flex w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-left text-sm whitespace-nowrap hover:bg-accent hover:text-accent-foreground"
                    onClick={() => {
                      void sendFrameToChat(
                        { ...refFromAsset(frameMenu.asset), t: frameMenu.srcT },
                        frameMenu.from
                      );
                      setFrameMenu(null);
                    }}
                  >
                    <Fullscreen className="size-3.5 text-muted-foreground" /> {tr("captureFrame")}
                  </button>
                  <button
                    className="flex w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-left text-sm whitespace-nowrap hover:bg-accent hover:text-accent-foreground"
                    onClick={() => {
                      void copyRefImage({
                        ...refFromAsset(frameMenu.asset),
                        t: frameMenu.srcT,
                      }).catch(() => {});
                      setFrameMenu(null);
                    }}
                  >
                    <Copy className="size-3.5 text-muted-foreground" /> {tr("copyFrame")}
                  </button>
                </div>
                {/* Drawn after the bubble so the diamond's inner half covers
                    its border along the notch, leaving one seamless outline. */}
                <div
                  className={cn(
                    "pointer-events-none absolute size-2.5 -translate-y-1/2 rotate-45 bg-popover",
                    flip
                      ? "right-[2px] rounded-tr-[2px] border-t border-r"
                      : "left-[2px] rounded-bl-[2px] border-b border-l"
                  )}
                  style={{ top: "var(--bubble-tip)" }}
                />
              </>
            )}
          </FrameBubble>
        </div>
      )}
    </footer>
  );
}

/**
 * A snug bubble beside the held marker line, speech-balloon style: its tapered
 * tip sits on the side edge facing the line, apex touching it at the grab
 * point. The bubble hangs to the line's right and flips left near the window
 * edge; it slides along the line to stay inside a short window, and the tip
 * stays on the grab point as it slides.
 */
function FrameBubble({
  x,
  y,
  children,
}: {
  x: number;
  y: number;
  children: (flip: boolean) => React.ReactNode;
}) {
  const el = useRef<HTMLDivElement>(null);
  const [place, setPlace] = useState({ top: y, flip: false, tip: "50%" });
  useLayoutEffect(() => {
    const node = el.current;
    if (!node) return;
    const pad = 8;
    const h = node.offsetHeight;
    const w = node.offsetWidth;
    const top = Math.min(Math.max(y, pad + h / 2), window.innerHeight - pad - h / 2);
    setPlace({
      top,
      flip: x + w + pad > window.innerWidth,
      // Where the tip meets the line, measured inside a bubble that may have
      // slid away from it.
      tip: `${Math.min(Math.max(y - (top - h / 2), 10), h - 10)}px`,
    });
  }, [x, y]);
  return (
    <div
      ref={el}
      className={cn("absolute -translate-y-1/2", place.flip ? "pr-[6px]" : "pl-[6px]")}
      style={{
        top: place.top,
        ["--bubble-tip" as string]: place.tip,
        ...(place.flip ? { right: window.innerWidth - x } : { left: x }),
      }}
      onPointerDown={(e) => e.stopPropagation()}
    >
      {children(place.flip)}
    </div>
  );
}

/**
 * The skimmer: a line that follows the mouse over the timeline. It marks
 * where Split (⌘B / S) will cut; clicking still moves the playhead itself.
 */
function HoverLine({
  scrollRef,
  innerRef,
  pps,
  hold,
}: {
  scrollRef: React.RefObject<HTMLDivElement | null>;
  innerRef: React.RefObject<HTMLDivElement | null>;
  pps: number;
  /** The frame-grab menu owns the skim: the skimmer neither moves nor clears
   * it, and the line darkens — the marker is the skimmer, held. */
  hold: boolean;
}) {
  const skimTime = useSkim();
  useEffect(() => () => setSkim(null), []);
  // A drag fires no pointer events, so a drop leaves the pointer over the
  // timeline with the skimmer wherever it was before the drag began. The drop
  // is the pointer's position: the skimmer moves there, so ⌘B cuts the clip
  // that just landed, and the keyboard comes to the editor with it.
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const land = (e: DragEvent) => {
      const inner = innerRef.current;
      if (!inner) return;
      const t = (e.clientX - inner.getBoundingClientRect().left) / useEditor.getState().pxPerSec;
      if (!hold) setSkim(Math.max(0, t));
      keyboardToEditor();
    };
    el.addEventListener("drop", land, { capture: true });
    return () => el.removeEventListener("drop", land, { capture: true });
  }, [scrollRef, innerRef, hold]);
  useEffect(() => {
    const el = scrollRef.current;
    if (!el || hold) return;
    // The inner box only moves when the timeline scrolls or zooms, so its left
    // edge is read once per gesture instead of once per pointer event — the
    // read forces a layout, and a scrub issues hundreds of them.
    let left = 0;
    let measured = false;
    const remeasure = () => {
      measured = false;
    };
    const move = (e: PointerEvent) => {
      const inner = innerRef.current;
      // The skimmer is a paused affordance: while the cut is playing the
      // picture belongs to the playhead, wherever the pointer happens to rest.
      if (!inner || e.buttons || useEditor.getState().playing) return setSkim(null);
      if (!measured) {
        left = inner.getBoundingClientRect().left;
        measured = true;
      }
      const t = (e.clientX - left) / useEditor.getState().pxPerSec;
      setSkim(Math.max(0, t));
    };
    const leave = () => {
      remeasure();
      setSkim(null);
    };
    el.addEventListener("scroll", remeasure, { passive: true });
    el.addEventListener("pointermove", move);
    el.addEventListener("pointerleave", leave);
    return () => {
      el.removeEventListener("scroll", remeasure);
      el.removeEventListener("pointermove", move);
      el.removeEventListener("pointerleave", leave);
    };
  }, [scrollRef, innerRef, hold]);
  if (skimTime === null) return null;
  return (
    <div
      className={cn(
        "tl-hover-line pointer-events-none absolute top-0 bottom-0 z-30 w-px will-change-transform",
        hold ? "bg-foreground/70" : "bg-foreground/30"
      )}
      style={{ transform: `translateX(${skimTime * pps}px)` }}
    />
  );
}

function useSplitEnabled() {
  const clips = useEditor((s) => s.clips);
  const hasBaseClips = useMemo(() => clips.some((clip) => clip.track === 0), [clips]);
  return useEditor((s) => {
    if (s.readOnly) return false;
    if (s.multiSelection.length) return s.multiSelection.some((item) => item && canSplitItem(item.kind));
    return s.selection ? canSplitItem(s.selection.kind) : hasBaseClips;
  });
}

function TimelineTools({
  split,
  addText,
  deleteSelection,
  selectionCount,
}: {
  split: () => void;
  addText: () => void;
  deleteSelection: () => void;
  selectionCount: number;
}) {
  const tr = useTranslations("timeline.toolbar");
  const splitEnabled = useSplitEnabled();
  const readOnly = useEditor((s) => s.readOnly);
  const magnet = useEditor((s) => s.magnet);
  const toggleMagnet = useEditor((s) => s.toggleMagnet);
  if (readOnly) return null;
  return (
    <>
      <TimelineActionButton label={tr("text")} tooltip={tr("textTooltip", { key: "T" })} onClick={addText}><Type /></TimelineActionButton>
      <SaveSelectionButton />
      <div role="separator" aria-orientation="vertical" className="mx-1 h-4 w-px shrink-0 bg-border" />
      <TimelineActionButton
        label={tr("magnet")}
        tooltip={magnet ? tr("magnetOn") : tr("magnetOff")}
        pressed={magnet}
        onClick={toggleMagnet}
      >
        <Magnet />
      </TimelineActionButton>
      {splitEnabled && (
        <TimelineActionButton label={tr("split")} tooltip={tr("splitTooltip")} onClick={split}><Scissors /></TimelineActionButton>
      )}
      {selectionCount > 0 && (
        <TimelineActionButton label={selectionCount > 1 ? tr("deleteCount", { count: selectionCount }) : tr("delete")} tooltip={tr("deleteTooltip", { key: "⌫" })} onClick={deleteSelection}><Trash2 /></TimelineActionButton>
      )}
      <TimelineGroupActions />
    </>
  );
}

/** Everything the toolbar drops when it runs out of room, listed. The zoom is
 * a row rather than an item — it is a control to work, not a command to pick,
 * so it keeps the slider and the menu stays open around it. */
function TimelineToolsMenu({
  pps,
  zoomMin,
  zoomTo,
  fit,
  split,
  addText,
  deleteSelection,
  selectionCount,
}: {
  pps: number;
  zoomMin: number;
  zoomTo: (next: number, anchorT?: number, anchorPx?: number) => void;
  fit: () => void;
  split: () => void;
  addText: () => void;
  deleteSelection: () => void;
  selectionCount: number;
}) {
  const tr = useTranslations("timeline.toolbar");
  const splitEnabled = useSplitEnabled();
  const save = useSaveSelection();
  const readOnly = useEditor((s) => s.readOnly);
  const magnet = useEditor((s) => s.magnet);
  const toggleMagnet = useEditor((s) => s.toggleMagnet);
  // Held open, because the zoom row is not a pick: dragging the slider has to
  // leave the menu standing, while Fit beside it closes as any command would.
  const [open, setOpen] = useState(false);
  return (
    <DropdownMenu open={open} onOpenChange={setOpen}>
      <DropdownMenuTrigger
        render={
          <Button variant="ghost" size="icon-sm" aria-label={tr("tools")} title={tr("tools")} />
        }
      >
        <MoreHorizontal />
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-56">
        {!readOnly && <DropdownMenuItem onClick={addText}><Type /> {tr("text")}</DropdownMenuItem>}
        {save.available && (
          <DropdownMenuItem disabled={save.state === "saving"} onClick={save.save}>
            {save.state === "done" ? <Check /> : <FolderPlus />}
            {save.state === "done" ? tr("saved") : tr("saveTemplate")}
          </DropdownMenuItem>
        )}
        {!readOnly && <DropdownMenuSeparator />}
        {!readOnly && (
          <DropdownMenuCheckboxItem checked={magnet} onCheckedChange={toggleMagnet}>
            <Magnet /> {tr("magnet")}
          </DropdownMenuCheckboxItem>
        )}
        {splitEnabled && <DropdownMenuItem onClick={split}><Scissors /> {tr("split")}</DropdownMenuItem>}
        {!readOnly && selectionCount > 0 && (
          <DropdownMenuItem onClick={deleteSelection}>
            <Trash2 /> {selectionCount > 1 ? tr("deleteCount", { count: selectionCount }) : tr("delete")}
          </DropdownMenuItem>
        )}
        <TimelineGroupActions menu />
        {!readOnly && <DropdownMenuSeparator />}
        {/* The zoom as it reads in the toolbar: the slider with Fit beside it. */}
        <div className="flex items-center gap-2 px-1.5 py-1">
          <div
            className="min-w-0 flex-1"
            // A press on the slider is a drag, not a pick — it must not reach
            // the menu, which would take it as a choice and close.
            onPointerDown={(e) => e.stopPropagation()}
            onClick={(e) => e.stopPropagation()}
          >
            <Slider
              min={0}
              max={100}
              step={0.1}
              value={zoomToSlider(pps, zoomMin)}
              aria-label={tr("zoom")}
              onValueChange={(v) => zoomTo(sliderToZoom(Number(v), zoomMin))}
            />
          </div>
          <Button
            variant="ghost"
            size="sm"
            className="shrink-0"
            title={tr("fitTitle")}
            onClick={() => {
              fit();
              setOpen(false);
            }}
          >
            {tr("fit")}
          </Button>
        </div>
        <DropdownMenuSeparator />
        <DropdownMenuItem onClick={() => useEditor.getState().setTimelineOpen(false)}>
          <PanelBottomClose /> {tr("hideTimeline")}
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

/** Folds the timeline away under the preview; the button over the canvas
 * brings it back. */
function HideTimelineButton() {
  const tr = useTranslations("timeline.toolbar");
  return (
    <Button
      variant="ghost"
      size="icon-sm"
      aria-label={tr("hideTimeline")}
      title={tr("hideTimeline")}
      onClick={() => useEditor.getState().setTimelineOpen(false)}
    >
      <PanelBottomClose />
    </Button>
  );
}

/** Saving the selection as a template: the state behind both the toolbar
 * button and the menu row that replaces it. */
function useSaveSelection() {
  const multiSelection = useEditor((s) => s.multiSelection);
  const readOnly = useEditor((s) => s.readOnly);
  const [state, setState] = useState<"idle" | "saving" | "done">("idle");
  const save = () => {
    const s = useEditor.getState();
    const input = s.selectionTemplate();
    if (!input) return;
    s.addTemplate(input);
    setState("done");
    setTimeout(() => setState("idle"), 1800);
  };
  return { available: !readOnly && multiSelection.length > 0, state, save };
}

function SaveSelectionButton() {
  const tr = useTranslations("timeline.toolbar");
  const { available, state, save } = useSaveSelection();
  if (!available) return null;
  return (
    <TimelineActionButton
      label={state === "done" ? tr("saved") : tr("saveTemplate")}
      tooltip={tr("saveTemplate")}
      disabled={state === "saving"}
      onClick={save}
    >
      {state === "saving" ? (
        <Loader2 className="animate-spin" />
      ) : state === "done" ? (
        <Check />
      ) : (
        <FolderPlus />
      )}
    </TimelineActionButton>
  );
}

/** The running time, on its own so the transport's buttons stay off the clock. */
function Timecode() {
  return <span className="tc-now">{formatTimecode(usePlayhead())}</span>;
}

/** Playback transport, centered in the timeline toolbar. */
function Transport({ total }: { total: number }) {
  const tr = useTranslations("timeline.toolbar");
  const playing = useEditor((s) => s.playing);
  const hasClips = total > 0;

  const toggle = () => {
    const s = useEditor.getState();
    if (!s.playing && playheadAt() >= total - 0.01) s.seek(0);
    s.setPlaying(!s.playing);
  };

  return (
    // In flow, in the toolbar's centre track: centred by the grid rather than
    // by being lifted out of it, so the tools beside it are laid out around
    // playback instead of underneath it.
    <div className="flex items-center gap-2">
      <Button
        variant="ghost"
        size="icon-sm"
        aria-label={tr("backToStart")}
        disabled={!hasClips}
        onClick={() => useEditor.getState().seek(0)}
      >
        <SkipBack className="fill-current" />
      </Button>
      <button
        className="grid size-8 place-items-center rounded-full bg-foreground text-background transition-transform hover:opacity-90 active:scale-95 disabled:opacity-40"
        title={tr("playPause")}
        disabled={!hasClips}
        onClick={toggle}
        data-tour="play"
      >
        {playing ? (
          <Pause className="size-4 fill-current stroke-none" />
        ) : (
          <Play className="ml-0.5 size-4 fill-current stroke-none" />
        )}
      </button>
      <div className="flex min-w-30 items-baseline gap-1.5 font-mono text-xs tabular-nums">
        <Timecode />
        <span className="text-muted-foreground">/</span>
        <span className="text-muted-foreground">{formatTimecode(total)}</span>
      </div>
    </div>
  );
}


function Ruler({
  pps,
  width,
  onScrub,
}: {
  pps: number;
  width: number;
  onScrub: (e: React.PointerEvent) => void;
}) {
  const steps = [0.5, 1, 2, 5, 10, 15, 30, 60];
  const step = steps.find((s) => s * pps >= 64) ?? 120;
  const count = Math.ceil(width / (step * pps));
  const ticks = Array.from({ length: count }, (_, i) => i * step);
  return (
    <div className="relative cursor-ew-resize" style={{ height: RULER_H }} onPointerDown={onScrub}>
      {ticks.map((t) => (
        <div
          key={t}
          className="absolute top-0 bottom-0 border-l border-foreground/15 pl-1.5"
          style={{ left: t * pps }}
        >
          <span className="font-mono text-[9.5px] leading-6 text-muted-foreground select-none">
            {formatTime(t)}
          </span>
        </div>
      ))}
    </div>
  );
}

function Playhead({
  pps,
  total,
  scrollRef,
  onScrub,
}: {
  pps: number;
  total: number;
  scrollRef: React.RefObject<HTMLDivElement | null>;
  onScrub: (e: React.PointerEvent) => void;
}) {
  const playing = useEditor((s) => s.playing);
  const ref = useRef<HTMLDivElement>(null);

  // Follow the playhead while playing, but yield to the user: any manual
  // scroll pauses following, which resumes after 5s of scroll idle. The
  // follow's own writes are told apart from user scrolls by matching the
  // scroll-event echo against the value it just wrote.
  const manualUntil = useRef(0);
  const followWrote = useRef<number | null>(null);
  // Following pages rather than pans: the playhead runs across the view and at
  // the edge the view turns to the next page, the playhead at its left margin.
  // The turn is a short eased glide written from the same playhead callback
  // and re-aimed each frame at where the playhead is now, so it lands with the
  // playhead at the margin however far it moved during the glide.
  const glide = useRef<{ from: number; t0: number } | null>(null);
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const onScroll = () => {
      if (followWrote.current !== null && Math.abs(el.scrollLeft - followWrote.current) < 1) {
        followWrote.current = null;
        return;
      }
      followWrote.current = null;
      glide.current = null;
      manualUntil.current = performance.now() + 5000;
    };
    el.addEventListener("scroll", onScroll);
    return () => el.removeEventListener("scroll", onScroll);
  }, [scrollRef]);

  // The marker is one transform. Rendering a component sixty times a second to
  // write one style property costs a reconcile per frame and moves the same
  // pixel, so the subscription writes it directly and the scroll-follow rides
  // along in the same callback.
  useEffect(() => {
    const move = () => {
      const el = ref.current;
      if (!el) return;
      const x = playheadAt() * pps;
      el.style.transform = `translateX(${x}px)`;
      const scroller = scrollRef.current;
      if (!scroller || !playing) return;
      if (performance.now() < manualUntil.current) return;
      const sx = x + PAD_SIDE; // playhead position in scroll coordinates
      const view = scroller.clientWidth;
      // The trailing pad is room to drop clips into, so following stops once
      // the last frame reaches the right edge: a project that fits the
      // viewport never scrolls, and the end of a long one lands flush.
      const maxFollow = Math.max(0, total * pps + PAD_SIDE * 2 - view);
      const margin = () => Math.min(maxFollow, Math.max(0, sx - FOLLOW_MARGIN));
      const write = (left: number) => {
        scroller.scrollLeft = left;
        followWrote.current = scroller.scrollLeft; // read back: the browser clamps
      };
      const now = performance.now();
      if (glide.current) {
        const p = Math.min(1, (now - glide.current.t0) / FOLLOW_GLIDE_MS);
        const eased = p < 0.5 ? 4 * p * p * p : 1 - Math.pow(-2 * p + 2, 3) / 2;
        write(glide.current.from + (margin() - glide.current.from) * eased);
        if (p >= 1) glide.current = null;
        return;
      }
      if (sx < scroller.scrollLeft + 24 || sx > scroller.scrollLeft + view - FOLLOW_MARGIN) {
        const want = margin();
        if (Math.abs(want - scroller.scrollLeft) <= 0.5) return;
        if (reducedMotion()) write(want);
        else glide.current = { from: scroller.scrollLeft, t0: now };
      }
    };
    glide.current = null;
    move();
    return subscribePlayhead(move);
  }, [pps, total, playing, scrollRef]);

  return (
    <div
      ref={ref}
      // Over the gutter as well as the clips: at 0 the playhead stands on the
      // gutter's own edge. The clips pass under the gutter; the time it is
      // showing does not. The grab cap lives in the pinned ruler.
      // will-change: the line moves sixty times a second; its own compositor
      // layer keeps each move off the tracks layer's paint, where a machine
      // that falls behind leaves ghost lines at old positions.
      className="pointer-events-none absolute top-0 bottom-0 left-0 z-50 w-[1.5px] bg-[#0a84ff] shadow-[0_0_8px_rgba(10,132,255,0.6)] will-change-transform"
    />
  );
}

/** The playhead's grab cap, riding the pinned ruler band — the side padding
 * is there so it is never clipped at 0. */
function PlayheadCap({
  pps,
  onScrub,
}: {
  pps: number;
  onScrub: (e: React.PointerEvent) => void;
}) {
  const ref = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const move = () => {
      if (ref.current) ref.current.style.transform = `translateX(${playheadAt() * pps}px)`;
    };
    move();
    return subscribePlayhead(move);
  }, [pps]);
  return (
    <div
      ref={ref}
      className="tl-playhead-cap absolute top-0 left-[-7px] h-5 w-4 cursor-ew-resize will-change-transform"
      onPointerDown={onScrub}
    >
      <div className="mx-auto h-3 w-2.5 rounded-t-[3px] bg-[#0a84ff] [clip-path:polygon(0_0,100%_0,100%_58%,50%_100%,0_58%)]" />
    </div>
  );
}


/**
 * One video clip's box, on track 0 or on an upper track. Every video track
 * draws the same bar — filmstrip, chips, keys, trim grips — and the row it
 * sits on decides the two things that differ: the spine carries the chat
 * mention and the detach-audio action, and the lane gestures are keyed to it.
 * Full-frame upper clips (`scale === 1`) read as a stacked composite; smaller
 * ones are picture-in-picture. Hidden clips gray out.
 */
function ClipView({
  span,
  mention,
  pps,
  selected,
  lutTarget,
  drag,
  parting,
  partAt,
  homeRow,
  rows,
  onDrag,
  onSnap,
  onFrameMenu,
}: {
  span: ClipSpan;
  /** The clip's chat mention token ("@c2"), shown on hover so the user can
   * point the assistant at this exact segment. Track 0 only — the spine is
   * what the assistant addresses. */
  mention?: string;
  pps: number;
  selected: boolean;
  /** A carried LUT is held over this clip: it lights as the drop's target. */
  lutTarget?: boolean;
  /** This clip's live drag when it is the one being carried (ghost mode). */
  drag: LaneDrag | null;
  /** Another clip on this row is dragging: animate this one's parting shifts. */
  parting: boolean;
  /** The start this clip previews at while a hovering drop parts its row. */
  partAt?: number;
  /** The clip's display row in the stack, and the stack's rows read live. */
  homeRow: number;
  rows: () => RowBox[];
  onDrag: (d: LaneDrag | null) => void;
  onSnap: (x: number | null) => void;
  /** Right-click: offer the frame under the pointer to the chat composer. */
  onFrameMenu: (
    e: React.MouseEvent,
    grab: { asset: MediaAsset; srcT: number; from: FrameGrabOrigin }
  ) => void;
}) {
  const tr = useTranslations("timeline.clip");
  const { clip, asset } = span;
  const spine = clip.track === 0;
  const loading = useEditor((s) => s.loadingMedia.has(asset.fileName));
  const baking = useMatteBakes((s) => s.jobs[clip.id]?.status === "running" || s.jobs[cardMatteKey(clip.id)]?.status === "running");
  const rt = retimeOf(clip);
  // Every box is its clip's whole footprint. Clips never overlap — a
  // transition is a render-time blend at the cut, drawn as the bar above the
  // tracks — so a box's width is the clip's own length, whatever joins it.
  const w = Math.max(10, span.len * pps);
  // The box is drawn a gutter narrower than the footprint, so everything laid
  // out inside it — the strip, the dots — measures against this, not `w`.
  const barW = Math.max(10, w - CLIP_GAP);
  // The source seconds at the box's edges: a reversed clip opens on `out`.
  const filmIn = headSrc(clip);
  const filmOut = tailSrc(clip);

  const startFrame = useEdgeFrame(asset, filmIn, `${clip.id}:in`);
  const endFrame = useEdgeFrame(asset, filmOut, `${clip.id}:out`);
  const stripFailed = useSyncExternalStore(
    subscribeStripStatus,
    () => stripFailedFor(asset.id),
    () => false
  );
  const boxRef = useRef<HTMLDivElement>(null);
  // The clip's own sound, drawn in the box's band under the picture. Muting —
  // detach included — greys the band, so the clip's shape holds still and its
  // waveform stays readable (a detached copy draws on the soundtrack row too).
  // A recording bound to the video is what plays, so it is what draws, moved
  // onto the video's clock.
  const hasWave = hasSoundBand(asset, span.sound?.asset);
  const waveAsset = span.sound?.asset ?? asset;
  const waveOff = span.sound?.offset ?? 0;
  // Bumped as tile captures land, so the memo re-plans and picks them up.
  const [filmGen, onTileFrame] = useReducer((x: number) => x + 1, 0);
  // The strip draws the stretch of the box the scroller shows. The box's
  // left in scroll coordinates is where it is drawn, behind the content's
  // side padding.
  const boxLeft = PAD_SIDE + (drag ? drag.ghostX : (partAt ?? span.start) * pps);
  const view = useStripView(boxLeft, w);
  const offscreen = view.hi <= view.lo;
  const filmstrip = useMemo(
    () =>
      filmstripFrames(
        asset,
        filmIn,
        w,
        pps,
        rt,
        FILM_H,
        26,
        { start: startFrame, end: endFrame },
        view
      ),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [asset, filmIn, w, pps, rt, startFrame, endFrame, filmGen, view]
  );
  useTileFrames(boxRef, clip.id, asset, filmstrip, filmIn, w, pps, rt.key, onTileFrame);

  // The move gesture is the shared lane behavior: parting, snapping, and
  // retracking across the stack's rows.
  const ui = { pps, rows, homeRow, visStart: span.start, onDrag, onSnap };

  return (
    <>
    <div
      className={cn(
        "tl-clip group absolute top-0.5 cursor-grab overflow-hidden rounded-[2.5px] bg-black shadow-[inset_0_0_0_1px_rgba(0,0,0,0.12)]",
        selected && SELECTED_SHADOW,
        lutTarget && "tl-clip-lut-target z-10 shadow-[inset_0_0_0_2px_#0a84ff]",
        clip.hidden && "opacity-40 grayscale",
        drag
          ? "tl-clip-ghost pointer-events-none cursor-grabbing opacity-80 shadow-2xl"
          : parting && "transition-[left] duration-150 ease-out"
      )}
      style={{
        left: drag ? drag.ghostX : (partAt ?? span.start) * pps,
        top: drag ? 2 + drag.ghostY : undefined,
        width: barW,
        height: hasWave ? VIDEO_H - 4 : FILM_H,
        // Inline so it beats SELECTED_SHADOW's z-10 class on the same element.
        zIndex: drag ? 20 : undefined,
      }}
      ref={boxRef}
      data-tl-sel={`clip:${clip.id}`}
      onPointerDown={(e) => {
        // The grid sits on the source, so a muted clip takes a beat the same
        // as a playing one — the same test the Beats row and the snapping use.
        if (e.altKey && !assetIsSilent(asset)) {
          addBeatAt(e, asset, clip, pps);
          return;
        }
        startLaneMove(e, "video", clip.id, ui);
      }}
      onContextMenu={(e) => {
        if (asset.type !== "video") return;
        const rect = e.currentTarget.getBoundingClientRect();
        onFrameMenu(e, {
          asset,
          srcT: rt.srcAt((e.clientX - rect.left) / pps),
          from: { x: e.clientX, top: rect.top, height: rect.height },
        });
      }}
    >
      <div className="pointer-events-none absolute inset-x-0 top-0" style={{ height: FILM_H }}>
        <Filmstrip frames={filmstrip} grade={clip.grade} failed={stripFailed} hidden={offscreen} block={asset?.block} />
      </div>
      <MissingChip assetId={asset.id} />
      {clip.grade?.lut && (
        // The LUT badge: the file mark, small, where the clip's chrome sits.
        // eslint-disable-next-line @next/next/no-img-element
        <img
          src={LUT_MARK_ICON}
          alt={tr("lut")}
          className="tl-clip-lut pointer-events-none absolute top-1 left-1 z-4 size-3.5 drop-shadow-[0_0_1px_rgba(0,0,0,0.6)]"
        />
      )}
      {hasWave && (
        <div
          className={cn(
            "tl-clip-wave pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-b",
            clip.muted
              ? "from-[#9a9d9c] to-[#828785]"
              : "from-[#59c09d] to-[#43b18d]"
          )}
          style={{ height: WAVE_H }}
        >
          <WaveformCanvas asset={waveAsset} from={clip.in + waveOff} to={clip.out + waveOff} w={barW} h={WAVE_H - 4} map={rt.uniform && !rt.reverse ? undefined : (px) => rt.srcAt(px / pps) + waveOff} className="inset-x-0 inset-y-0.5" />
          {/* A split edit: the edge whose sound runs past the picture. */}
          {(span.soundLead ?? 0) > 0 && <div className="tl-clip-split absolute inset-y-0 left-0 w-0.5 bg-white/80" />}
          {(span.soundTail ?? 0) > 0 && <div className="tl-clip-split absolute inset-y-0 right-0 w-0.5 bg-white/80" />}
        </div>
      )}
      {selected && (
        // A blue wash over the whole clip so a multi-selection reads at a
        // glance, not just from the thin border.
        <div className="pointer-events-none absolute inset-0 z-[1] bg-[#0a84ff]/25" />
      )}
      {baking && !drag && (
        // The bake announces itself where the hover controls live, so it
        // yields to them: gone while the pointer is on the clip, back when it
        // leaves. A clip too narrow for the word keeps the spinner and "C…".
        <span className="tl-cutting-chip pointer-events-none absolute top-1 left-1 z-2 flex items-center gap-1 rounded-[5px] bg-black/65 px-1.5 py-px font-mono text-[10px] text-white transition-opacity group-hover:opacity-0">
          <Loader2 className="size-2.5 shrink-0 animate-spin" />
          {barW >= 96 ? tr("cutting") : tr("cuttingShort")}
        </span>
      )}
      {clip.name && !baking && !drag && (
        // A clip the person named wears it over the film, where the hover
        // controls live: it steps aside for the mention chip as they arrive.
        <span
          className={cn(
            "tl-name-chip pointer-events-none absolute top-1 left-1 z-2 max-w-[calc(100%-8px)] truncate rounded-[5px] bg-black/65 px-1.5 py-px text-[10px] text-white transition-opacity",
            mention && !loading && "group-hover:opacity-0"
          )}
        >
          {clip.name}
        </span>
      )}
      {mention &&
        (drag ? (
          <span className="tl-dur-chip pointer-events-none absolute top-1 left-1 z-2 rounded-[5px] bg-black/65 px-1.5 py-px font-mono text-[10px] tabular-nums text-white">
            {(Math.round(span.len * 10) / 10).toFixed(1)}s
          </span>
        ) : loading ? null : (
          <span className="tl-mention-chip pointer-events-none absolute top-1 left-1 z-2 rounded-[5px] bg-black/65 px-1.5 py-px font-mono text-[10px] text-white opacity-0 transition-opacity group-hover:opacity-100">
            {mention}
          </span>
        ))}
      {loading && <LoadingChip />}
      {asset.type === "video" && !loading && (
        <MuteChip
          muted={clip.muted}
          className="bottom-1 left-1"
          onToggle={() => useEditor.getState().updateClip(clip.id, { muted: !clip.muted })}
        />
      )}
      {!rt.uniform ? (
        <span
          className="tl-speed-chip absolute right-[30px] bottom-1 z-2 rounded-[5px] bg-black/70 px-1 py-px font-mono text-[9.5px] tabular-nums text-white"
          title={tr("speedCurve", { rate: +rt.rate.toFixed(2) })}
        >
          ∿ {+rt.rate.toFixed(1)}×
        </span>
      ) : (
        rt.rate !== 1 && (
          <span
            className="tl-speed-chip absolute right-[30px] bottom-1 z-2 rounded-[5px] bg-black/70 px-1 py-px font-mono text-[9.5px] tabular-nums text-white"
            title={tr("speed", { rate: rt.rate })}
          >
            {+rt.rate.toFixed(2)}×
          </span>
        )
      )}
      {!loading && (
        <HideChip
          hidden={!!clip.hidden}
          className="bottom-1 right-2"
          onToggle={() => useEditor.getState().updateClip(clip.id, { hidden: !clip.hidden })}
        />
      )}
      {!loading && (
        <ClipMenu asset={asset} clip={clip}>
          {spine && asset.type === "video" ? (
            <DropdownMenuItem
              disabled={clip.muted}
              onClick={() => {
                const s = useEditor.getState();
                s.select({ kind: "clip", id: clip.id });
                s.detachAudio();
                void ensurePeaks(asset);
              }}
            >
              <AudioLines /> {tr("detachAudio")}
            </DropdownMenuItem>
          ) : null}
        </ClipMenu>
      )}
      <ClipStrokeMarks clip={clip} spanStart={span.start} retime={rt} pps={pps} barW={barW} />
      {/* Keys sit on the bar where they fall — pose and mask tracks both —
          so the animation is visible without opening the inspector. */}
      {(clip.kf ?? []).map((k) => (
        <KeyMarker
          key={k.t}
          item={{ id: clip.id, start: span.start, end: span.start + span.len }}
          kind="clip"
          t={k.t}
          pps={pps}
          width={barW}
        />
      ))}
      {/* Drawn wherever the source has a grid: on the band when there is one,
          along the bar's bottom edge when the clip plays silent. Every edge
          snaps to them either way. */}
      <BeatDots asset={asset} lo={clip.in} hi={clip.out} retime={rt} pps={pps} w={barW} />
      <span
        className={cn(trimFor(barW), "tl-trim-l left-0")}
        onPointerDown={(e) => startLaneTrim(e, "video", clip.id, "l", ui)}
      />
      <span
        className={cn(trimFor(barW), "tl-trim-r right-0")}
        onPointerDown={(e) => startLaneTrim(e, "video", clip.id, "r", ui)}
      />
    </div>
    <ClipMaskKeyStrip
      clip={clip}
      start={span.start}
      len={span.len}
      pps={pps}
      w={w}
      boxH={hasWave ? VIDEO_H - 4 : FILM_H}
      hidden={!!drag}
    />
    <ClipSpeedRail
      retime={rt}
      start={span.start}
      pps={pps}
      w={w}
      view={view}
      boxH={hasWave ? VIDEO_H - 4 : FILM_H}
      hidden={!!drag || offscreen || !!clip.mask?.kf?.length}
    />
    </>
  );
}

/** A curved clip's pace, drawn on the rail under its box: the rate through
 * the clip's own timeline on a log scale, 1× as the dashed midline, so a
 * ramp reads at a glance without opening the editor. It shares the rail with
 * the mask keys and yields to them. */
function ClipSpeedRail({
  retime,
  start,
  pps,
  w,
  view,
  boxH,
  hidden,
}: {
  retime: Retime;
  start: number;
  pps: number;
  w: number;
  /** The stretch of the box the scroller shows — the sketch is drawn for
   * that slice, so a long clip at a deep zoom costs what is on screen. */
  view: { lo: number; hi: number };
  boxH: number;
  hidden: boolean;
}) {
  if (hidden || retime.uniform) return null;
  const barW = Math.max(10, w - CLIP_GAP);
  const from = Math.max(0, Math.min(barW, view.lo));
  const to = Math.max(from, Math.min(barW, view.hi));
  if (to - from < 1) return null;
  const h = 14;
  const lo = Math.log10(SPEED_CURVE_MIN);
  const hi = Math.log10(SPEED_CURVE_MAX);
  const yOf = (rate: number) => (1 - (Math.log10(rate) - lo) / (hi - lo)) * (h - 2) + 1;
  const step = 3;
  const pts: string[] = [];
  for (let x = from; x <= to; x += step) {
    pts.push(`${(x - from).toFixed(1)},${yOf(retime.rateAt(Math.min(retime.len, x / pps))).toFixed(1)}`);
  }
  const lastX = (to - from).toFixed(1);
  pts.push(`${lastX},${yOf(retime.rateAt(Math.min(retime.len, to / pps))).toFixed(1)}`);
  const mid = yOf(1).toFixed(1);
  const width = to - from;
  return (
    <div
      className="pointer-events-none absolute z-5"
      style={{ left: start * pps + from, top: boxH + 3, width, height: h + 2 }}
    >
      <svg width={width} height={h + 2} className="overflow-visible">
        <line x1={0} y1={mid} x2={width} y2={mid} stroke="currentColor" strokeOpacity={0.25} strokeDasharray="3 3" />
        <polyline
          points={`0,${h} ${pts.join(" ")} ${lastX},${h}`}
          fill="#0a84ff"
          fillOpacity={0.18}
          stroke="none"
        />
        <polyline points={pts.join(" ")} fill="none" stroke="#0a84ff" strokeWidth={1.5} strokeLinejoin="round" />
      </svg>
    </div>
  );
}

/** The clip's brush-stroke frames, as red tabs hanging from the bar's top
 * edge while its brush session is open. A stroke lives on the one frame it
 * was drawn on — the stage overlay shows it only there — so each tab points
 * at a frame that carries paint, and clicking one parks the playhead on it.
 * Tabs, not diamonds or dots: diamonds are keyframes (interpolated values,
 * which seeds aren't) and dots are the beat grid on the bottom edge. */
function ClipStrokeMarks({
  clip,
  spanStart,
  retime,
  pps,
  barW,
}: {
  clip: VideoClip;
  spanStart: number;
  retime: Retime;
  pps: number;
  barW: number;
}) {
  const tr = useTranslations("timeline.clip");
  const open = useBrushUi((s) => s.clipId === clip.id);
  const seeds = clip.removal?.seeds;
  if (!open || clip.removal?.mode !== "custom") return null;
  const times = Array.from(new Set((seeds?.paint ?? []).map((s) => s.t))).filter(
    (t) => t >= clip.in - 0.05 && t <= clip.out + 0.05
  );
  if (times.length === 0) return null;
  return (
    <>
      {times.map((t) => (
        <span
          key={`s${t}`}
          className="tl-stroke-mark pointer-events-auto absolute top-0 z-5 flex h-3 w-3.5 cursor-pointer justify-center"
          style={{
            left: Math.min(barW - 4, Math.max(4, retime.tAt(t) * pps)),
            transform: "translateX(-50%)",
          }}
          title={tr("brushStroke")}
          onPointerDown={(e) => {
            e.stopPropagation();
            e.preventDefault();
            useEditor.getState().seek(spanStart + retime.tAt(t));
          }}
        >
          <span
            className="h-0 w-0"
            style={{
              borderLeft: "4px solid transparent",
              borderRight: "4px solid transparent",
              borderTop: "5px solid #ff2244",
            }}
          />
        </span>
      ))}
    </>
  );
}

/** The clip's mask keys, on a thin rail under its box: a hairline spanning
 * the clip's width with a diamond on it per key. The bar itself clips its
 * children (rounded corners), so the rail is a sibling that follows the
 * clip's own left edge. It hides while the clip rides a drag ghost and comes
 * back where the clip lands. */
function ClipMaskKeyStrip({
  clip,
  start,
  len,
  pps,
  w,
  boxH,
  hidden,
}: {
  clip: VideoClip;
  start: number;
  len: number;
  pps: number;
  w: number;
  /** The clip box's height, which the rail hangs under — shorter on a clip
   * with no sound band. */
  boxH: number;
  hidden: boolean;
}) {
  if (hidden || !clip.mask?.kf?.length) return null;
  const barW = Math.max(10, w - CLIP_GAP);
  return (
    <div
      className="pointer-events-none absolute z-5"
      style={{
        left: start * pps,
        // A hair below the bar's bottom edge, deep enough that the diamonds —
        // the picked one's ring included — never touch the clip's box.
        top: boxH + 3,
        width: barW,
        height: 16,
      }}
    >
      <div className="absolute inset-x-0 top-1/2 h-[2px] -translate-y-1/2 rounded-full bg-[#ff9f0a]/45" />
      {clip.mask.kf.map((k) => (
        <KeyMarker
          key={`m${k.t}`}
          item={{ id: clip.id, start, end: start + len }}
          kind="clip"
          track="mask"
          t={k.t}
          pps={pps}
          width={barW}
        />
      ))}
    </div>
  );
}

/** Render just this timeline item through the normal export pipeline: a
 * one-clip cut using source settings, trimmed and paced like the segment on
 * the timeline, landing in the project's exports folder and the dock like any
 * full export. */
function exportSegment(asset: MediaAsset, clip: VideoClip | AudioClip) {
  const s = useEditor.getState();
  if (!s.projectId) return;
  // AudioClip has no `track`; a hidden segment still renders when exported alone.
  const doc: ExportDoc =
    "track" in clip
      ? {
          aspect: s.aspect,
          assets: [asset],
          clips: [{ ...clip, start: 0, track: 0, hidden: undefined }],
          audioClips: [],
          overlays: [],
          subtitles: emptySubtitles(),
        }
      : {
          aspect: s.aspect,
          assets: [asset],
          clips: [],
          audioClips: [{ ...clip, start: 0, hidden: undefined }],
          overlays: [],
          subtitles: emptySubtitles(),
        };
  const settings = originalSettings(s.aspect, doc.clips, doc.assets, doc);
  void useExports.getState().start(s.projectId, doc, settings, s.projectName);
}

/** The "⋮" menu on a timeline item. Every item gets the same filing pair —
 * move its asset into the Media panel (drop the `origin` tag) or copy it into
 * the shared library — plus a solo export, and slots item-specific actions
 * above them via `children`. */
function ClipMenu({
  asset,
  clip,
  children,
}: {
  asset: MediaAsset;
  clip: VideoClip | AudioClip;
  children?: ReactNode;
}) {
  const tr = useTranslations("timeline.clip");
  const caps = useCutCaps();
  return (
    <DropdownMenu>
      <DropdownMenuTrigger
        render={
          <button
            aria-label={tr("options")}
            className="tl-clip-menu absolute top-1 right-2 z-4 grid size-[18px] place-items-center rounded-[5px] bg-black/55 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-black/75"
            onPointerDown={(e) => e.stopPropagation()}
          />
        }
      >
        <EllipsisVertical className="size-3" />
      </DropdownMenuTrigger>
      <DropdownMenuContent align="start" className="w-44">
        {children}
        {children != null && <DropdownMenuSeparator />}
        <DropdownMenuItem
          onClick={() =>
            // Clearing the origin files it into Media; a chat-owned asset also
            // sheds its thread so deleting the chat won't touch it.
            useEditor.getState().updateAsset(asset.id, { origin: undefined, chatId: undefined })
          }
        >
          <Clapperboard /> {tr("addToMedia")}
        </DropdownMenuItem>
        <DropdownMenuItem
          onClick={() => {
            const projectId = useEditor.getState().projectId;
            if (!projectId) return;
            void saveAssetToLibrary(projectId, asset).catch(() => {
              // Library write failed; nothing to roll back.
            });
          }}
        >
          <FolderPlus /> {tr("addToLibrary")}
        </DropdownMenuItem>
        <DropdownMenuItem onClick={() => exportSegment(asset, clip)}>
          <ArrowDownToLine /> {tr("exportSegment")}
        </DropdownMenuItem>
        <DropdownMenuItem
          disabled={!!asset.upload}
          onClick={() => {
            // The source file whole, as it was imported — the trimmed version
            // is what "Export segment" renders.
            const projectId = useEditor.getState().projectId;
            if (projectId) downloadMedia(projectId, asset);
          }}
        >
          <Download /> {tr("download")}
        </DropdownMenuItem>
        {caps.revealInFinder && (
          <DropdownMenuItem
            onClick={() => {
              const projectId = useEditor.getState().projectId;
              if (!projectId) return;
              void revealMedia(projectId, asset.fileName).catch(() => {});
            }}
          >
            <FolderOpen /> {tr("showInFinder")}
          </DropdownMenuItem>
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

/** What the drag ghost knows about the media under the cursor — enough to
 * tile the segment at the source's aspect before the asset exists in the
 * project. */
/** What the landing preview draws: the media the drop would lay down. A
 * project asset is itself. A library clip, a stock clip, or an image ref is
 * not in the project yet, so the drag carries what it knows about the source
 * and the ghost stands an asset up from it. Every field is a primitive or a
 * stable store reference, so the preview state dedupes by value and a still
 * pointer re-renders nothing. */
type DropGhost =
  | { asset: MediaAsset }
  | {
      url: string;
      kind: "video" | "image";
      name: string;
      duration: number;
      width?: number;
      height?: number;
      /** One known frame — the card's cover — to paint every tile with until
       * the true frame at each tile's moment lands. */
      poster?: string;
    };

/** The asset a ghost renders as: the project's own, or one stood up from the
 * drag. A stood-up video carries its poster as a one-thumb strip, so the
 * planner paints the whole box with a real frame at once and the tile reader
 * swaps each tile to its true frame as those land; an image is its own strip.
 * Stood up once per source, so the tile reader's plan holds while the ghost
 * slides. */
const ghostAssets = new Map<string, MediaAsset>();
function ghostAsset(ghost: DropGhost, len: number): MediaAsset {
  if ("asset" in ghost) return ghost.asset;
  const key = `${ghost.kind}|${ghost.url}|${ghost.poster ?? ""}|${len}`;
  const hit = ghostAssets.get(key);
  if (hit) return hit;
  const strip =
    ghost.kind === "image"
      ? { thumbs: [ghost.url], thumbStep: len }
      : ghost.poster
        ? { thumbs: [ghost.poster], thumbStep: Math.max(1, ghost.duration) }
        : {};
  const asset: MediaAsset = {
    id: `ghost:${ghost.url}`,
    fileName: ghost.url,
    name: ghost.name,
    type: ghost.kind,
    url: ghost.url,
    duration: ghost.kind === "image" ? len : ghost.duration,
    width: ghost.width,
    height: ghost.height,
    ...strip,
  };
  ghostAssets.set(key, asset);
  return asset;
}

/** The landing preview: the clip the drop would lay down, drawn by the same
 * pieces a placed clip is drawn with. The strip planner runs over the asset's
 * own thumbs; the tiles it lacks come from the edge-frame reader behind the
 * play, the same reads the placed clip would make and keep; the sound band
 * draws the asset's peaks. So what slides along the row is what will be there
 * after the release, at the cost of one more clip on the row — and the plan
 * depends on the source and the zoom alone, so sliding moves the box on the
 * compositor and plans nothing. */
function GhostClip({
  ghost,
  t,
  len,
  h,
  pps,
}: {
  ghost: DropGhost;
  /** Where the segment lands, timeline seconds. */
  t: number;
  len: number;
  /** The row's bar height: the box never draws past its row. */
  h: number;
  pps: number;
}) {
  const asset = ghostAsset(ghost, len);
  const w = Math.max(10, len * pps);
  const barW = Math.max(10, w - CLIP_GAP);
  const rt = retimeOf({ in: 0, out: len });
  const hasWave = hasSoundBand(asset);
  const boxH = Math.min(h, hasWave ? VIDEO_H - 4 : FILM_H);
  const boxRef = useRef<HTMLDivElement>(null);
  // Bumped as tile captures land, so the memo re-plans and picks them up.
  const [filmGen, onTileFrame] = useReducer((x: number) => x + 1, 0);
  const boxLeft = PAD_SIDE + t * pps;
  const view = useStripView(boxLeft, w);
  const filmstrip = useMemo(
    () => filmstripFrames(asset, 0, w, pps, rt, FILM_H, 26, undefined, view),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [asset, w, pps, rt, filmGen, view]
  );
  useTileFrames(boxRef, "drop-ghost", asset, filmstrip, 0, w, pps, rt.key, onTileFrame);
  // A source with no strip and no cover has nothing to plan tiles from until
  // one frame is in hand. The placed clip reads its head frame ahead of the
  // play; the ghost asks for the same frame behind it, and the plan takes it
  // from the cache the moment it lands.
  const seedless = filmstrip.length === 0 && asset.type === "video" && !!asset.url;
  useEffect(() => {
    if (!seedless) return;
    let live = true;
    void requestEdgeFrame("drop-ghost:head", previewUrl(asset), 0, undefined, { background: true }).then(
      (src) => {
        if (live && src) onTileFrame();
      }
    );
    return () => {
      live = false;
    };
  }, [seedless, asset]);
  // Reads still queued for a ghost that left the row are let go; frames that
  // landed stay cached, and the clip the drop lays down opens on them.
  useEffect(() => () => dropEdgeFrames("drop-ghost:"), []);
  return (
    <div
      ref={boxRef}
      className="tl-clip tl-clip-ghost pointer-events-none absolute top-0.5 left-0 z-20 overflow-hidden rounded-[2.5px] bg-black opacity-80 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.12)] transition-transform duration-100 ease-out"
      style={{ transform: `translateX(${t * pps}px)`, width: barW, height: boxH }}
    >
      <div className="pointer-events-none absolute inset-x-0 top-0" style={{ height: FILM_H }}>
        <Filmstrip frames={filmstrip} hidden={view.hi <= view.lo} />
      </div>
      {hasWave && boxH > FILM_H && (
        <div
          className="tl-clip-wave pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-b from-[#59c09d] to-[#43b18d]"
          style={{ height: WAVE_H }}
        >
          <WaveformCanvas asset={asset} from={0} to={len} w={barW} h={WAVE_H - 4} className="inset-x-0 inset-y-0.5" />
        </div>
      )}
      <span className="tl-dur-chip pointer-events-none absolute top-1 left-1 z-2 rounded-[5px] bg-black/65 px-1.5 py-px font-mono text-[10px] tabular-nums text-white">
        {(Math.round(len * 10) / 10).toFixed(1)}s
      </span>
    </div>
  );
}

/** What an OS drag carries, read off the item kinds the browser exposes
 * mid-drag: clip media rides the video rows, sound the audio rows. The count
 * sizes the placeholder, one nominal clip per file. */
function draggedFiles(e: React.DragEvent): { kind: "video" | "image" | "audio"; count: number } | null {
  const dt = e.dataTransfer;
  if (!dt || !Array.from(dt.types).includes("Files") || hasRefDrag(e)) return null;
  const items = Array.from(dt.items ?? []).filter((i) => i.kind === "file");
  const types = items.map((i) => i.type);
  // A type the OS withholds counts as a video: that is what a drop of it
  // usually turns out to be, and the wrong placeholder costs one re-plan.
  const clip = types.filter((t) => !t || /^(video|image)\//.test(t));
  if (clip.length) {
    return { kind: clip.every((t) => t.startsWith("image/")) ? "image" : "video", count: clip.length };
  }
  const audio = types.filter((t) => t.startsWith("audio/"));
  return audio.length ? { kind: "audio", count: audio.length } : null;
}

/** The length an OS video file's landing slot shows before the file is measured. */
const FILE_SLOT_SECONDS = 5;

/** The one frame a clip has before its strip is sampled: the capture taken for
 * its left edge, or any frame already read off this source. */
function seedThumb(
  asset: MediaAsset,
  filmIn: number,
  edges?: { start: string | null; end: string | null }
): string[] {
  if (asset.type !== "video") return [];
  const seed = edges?.start ?? peekEdgeFrame(previewUrl(asset), filmIn);
  return seed ? [seed] : [];
}

/**
 * The scroller's window, for the strips: where the view starts in scroll
 * coordinates and how wide it is, published once per frame from the
 * scroller's own scroll and resize. Every clip box reads its own slice of it
 * through `useStripView`, quantized to chunks, so a scroll re-renders a strip
 * only when the window crosses into tiles it has not drawn, and a box off
 * screen draws none.
 */
const stripView = { left: 0, width: 0 };
const stripViewListeners = new Set<() => void>();
let stripViewFrame = 0;
function publishStripView(el: HTMLElement) {
  const left = el.scrollLeft;
  const width = el.clientWidth;
  if (left === stripView.left && width === stripView.width) return;
  stripView.left = left;
  stripView.width = width;
  if (stripViewFrame) return;
  stripViewFrame = requestAnimationFrame(() => {
    stripViewFrame = 0;
    for (const fn of stripViewListeners) fn();
  });
}
function subscribeStripView(fn: () => void) {
  stripViewListeners.add(fn);
  return () => {
    stripViewListeners.delete(fn);
    // The window is one module's memory of one scroller. With the last strip
    // gone — the editor closed, another project opening — a pending frame has
    // nobody to tell, and the measurement belongs to a scroller that no longer
    // exists: the next editor would plan its first paint against it.
    if (stripViewListeners.size === 0) {
      if (stripViewFrame) cancelAnimationFrame(stripViewFrame);
      stripViewFrame = 0;
      stripView.left = 0;
      stripView.width = 0;
    }
  };
}
/** The strip plans and draws in stretches this wide on either side of the
 * view, on boundaries this wide: a scroll inside the stretch changes
 * nothing, and the next stretch is drawn before it comes into view. */
const STRIP_VIEW_CHUNK = 512;

/** Before the scroller has measured — the first render, and the server's —
 * a strip draws this much of its box from the left: a screen's worth, so
 * the first paint is bounded and the measured window replaces it a frame
 * later. */
const STRIP_VIEW_UNMEASURED = 4096;

/** The slice of a box its strip draws, px from the box's left: the
 * scroller's window plus a chunk each side, on chunk boundaries, clamped to
 * the box. Empty (`hi <= lo`) for a box off screen. */
function useStripView(boxLeft: number, w: number): { lo: number; hi: number } {
  const snapshot = () => {
    if (!stripView.width) return `0:${Math.min(w, STRIP_VIEW_UNMEASURED)}`;
    const c = STRIP_VIEW_CHUNK;
    const lo = Math.max(0, Math.floor((stripView.left - boxLeft) / c - 1) * c);
    const hi = Math.min(w, Math.ceil((stripView.left + stripView.width - boxLeft) / c + 1) * c);
    return hi > lo ? `${lo}:${hi}` : "0:0";
  };
  const key = useSyncExternalStore(subscribeStripView, snapshot, snapshot);
  return useMemo(() => {
    const [lo, hi] = key.split(":").map(Number);
    return { lo, hi };
  }, [key]);
}

/** Sample a clip's filmstrip tiles across the stretch of its box in view.
 * Tiles sit on a source-time grid: the strip holds still while a trimmed
 * edge sweeps across it, hiding frames under the handle (the box's overflow
 * clips the partial tiles at each end). Tiles keep the asset's aspect at
 * every zoom; only the ones inside `view` are planned, so a long clip zoomed
 * in costs a screen's worth. The clip's first and last tiles pin to the
 * segment's exact boundary frames once captured; middle tiles show the
 * nearest pre-sampled thumb until each one's true frame at its own moment
 * lands (see `planFilmstrip`). */
function filmstripFrames(
  asset: MediaAsset | undefined,
  filmIn: number,
  w: number,
  pps: number,
  retime: Retime,
  tileH: number,
  minTileW: number,
  edges?: { start: string | null; end: string | null },
  view?: { lo: number; hi: number }
): FilmTile[] {
  if (!asset) return [];
  // A blocked-out shot has no frames to tile: the strip paints its colour.
  if (asset.block) return [];
  // Before the pre-sampled strip exists — a fresh import, a library clip
  // dropped a moment ago — the clip still has a frame in hand: the one read
  // for its left edge. Standing that in as a one-thumb strip paints the whole
  // box with the picture at once, and every tile asks for its own true frame,
  // so the strip sharpens in place instead of sitting black until the sheet
  // lands.
  const thumbs = asset.thumbs?.length && asset.thumbStep ? asset.thumbs : seedThumb(asset, filmIn, edges);
  if (!thumbs.length) return [];
  const thumbStep =
    asset.thumbs?.length && asset.thumbStep ? asset.thumbStep : Math.max(asset.duration, 1);
  const frames = planFilmstrip({
    thumbs,
    thumbStep,
    duration: asset.duration,
    aspect: (asset.width ?? 16) / Math.max(1, asset.height ?? 9),
    filmIn,
    w,
    pps,
    speed: retime.rate,
    retime,
    tileH,
    minTileW,
    cuts: asset.sceneCuts,
    exactFrame: asset.type === "video" ? (t) => peekEdgeFrame(previewUrl(asset), t) : undefined,
    view,
  });
  // The window may start past the clip's first tile or end before its last;
  // only the tiles at the clip's own edges wear the edge frames.
  if (edges?.start && frames.length && frames[0].left <= 0.5) {
    frames[0] = { ...frames[0], src: edges.start };
  }
  const last = frames.length - 1;
  if (edges?.end && frames.length > 1 && frames[last].left + frames[last].width >= w - 0.5) {
    frames[last] = { ...frames[last], src: edges.end };
  }
  return frames;
}

/** How far past the scroller's view a tile still gets its true frame, so a
 * small scroll shows captured tiles at once. */
const TILE_CAPTURE_MARGIN = 240;

/** Capture the true frames a zoomed strip's tiles ask for. The plan names a
 * capture time on each tile the pre-sampled strip is too coarse for; this
 * effect requests the ones inside the scroller's view (plus a margin) through
 * the edge reader's background lane and re-renders as they land. Scroll fills
 * in newly visible tiles; a zoom or trim re-aims the same per-tile slots, so
 * superseded captures fall away on their own. */
function useTileFrames(
  boxRef: React.RefObject<HTMLDivElement | null>,
  clipId: string,
  asset: MediaAsset | undefined,
  tiles: FilmTile[],
  filmIn: number,
  w: number,
  pps: number,
  /** The clip's map, as a key: a changed rate re-plans the tiles. */
  mapKey: string,
  onFrame: () => void
) {
  // The landed-frame re-render hands this hook a fresh `tiles` array with the
  // same geometry; the ref keeps that from re-running the capture effect,
  // while scroll and the effect body always read the newest plan.
  const tilesRef = useRef(tiles);
  useEffect(() => {
    tilesRef.current = tiles;
  });
  const wanted = tiles.length > 0;
  useEffect(() => {
    const box = boxRef.current;
    const url = asset?.type === "video" ? previewUrl(asset) : null;
    if (!box || !url || !wanted) return;
    const scroller = box.closest("[data-tl-scroll]") as HTMLElement | null;
    let live = true;
    let scheduled = false;
    let bumping = false;
    // One request per capture time per plan: a failed read stays quiet until
    // a zoom or trim re-plans, and a scroll walk re-asks for nothing.
    const asked = new Set<string>();
    const landed = () => {
      if (bumping) return;
      bumping = true;
      requestAnimationFrame(() => {
        bumping = false;
        if (live) onFrame();
      });
    };
    const request = () => {
      scheduled = false;
      if (!live) return;
      let lo = 0;
      let hi = w;
      if (scroller) {
        const boxR = box.getBoundingClientRect();
        const view = scroller.getBoundingClientRect();
        lo = view.left - boxR.left - TILE_CAPTURE_MARGIN;
        hi = view.right - boxR.left + TILE_CAPTURE_MARGIN;
      }
      tilesRef.current.forEach((t) => {
        if (t.exact) return;
        if (t.left + t.width < lo || t.left > hi) return;
        const key = `${t.id}:${t.wantT.toFixed(2)}`;
        if (asked.has(key)) return;
        asked.add(key);
        void requestEdgeFrame(`${clipId}:tile:${t.id}`, url, t.wantT, undefined, {
          background: true,
        }).then((src) => {
          if (live && src) landed();
        });
      });
    };
    const schedule = () => {
      if (scheduled) return;
      scheduled = true;
      requestAnimationFrame(request);
    };
    schedule();
    scroller?.addEventListener("scroll", schedule, { passive: true });
    return () => {
      live = false;
      scroller?.removeEventListener("scroll", schedule);
    };
    // Geometry names the plan; `tiles` itself rides the ref above.
  }, [boxRef, clipId, asset, wanted, filmIn, w, pps, mapKey, onFrame]);
}

/** The exact source frame at a clip edge. Returns null (the nearest sampled
 * thumb shows instead) until the capture lands; a changed edge time falls back
 * immediately so a trim drag never shows a stale exact frame. */
function useEdgeFrame(asset: MediaAsset | undefined, time: number, slot: string) {
  const url = asset?.type === "video" ? previewUrl(asset) : null;
  const id = url ? `${url}#${time.toFixed(2)}` : "";
  const cached = url ? peekEdgeFrame(url, time) : null;
  const [frame, setFrame] = useState<{ id: string; src: string } | null>(null);
  useEffect(() => {
    if (!url || cached) return;
    let live = true;
    void requestEdgeFrame(slot, url, time).then((src) => {
      if (live && src) setFrame({ id, src });
    });
    return () => {
      live = false;
    };
  }, [url, time, slot, id, cached]);
  return cached ?? (frame?.id === id ? frame.src : null);
}

/** A clip box's thumbnail strip, washed with the clip's color grade: the same
 * CSS filter the preview uses plus the warm tint as a multiply blend, so the
 * strip tracks the grade with no thumbnail regeneration (thumbs live on the
 * shared asset; the wash is per clip). `isolate` keeps the blend inside the
 * strip. */
function Filmstrip({
  frames,
  grade,
  failed,
  hidden,
  block,
}: {
  frames: { src: string; left: number; width: number }[];
  grade?: ColorGrade;
  /** The clip is a shot with nothing in it yet: the strip is a flat slab in
   * the block's own color, and the clip's label above it says what belongs
   * there. Nothing is loading, so nothing pulses. */
  block?: { label: string; color?: string };
  /** The strip's last generation attempt failed: hold a still placeholder.
   * An endless pulse reads as loading forever, and animating a clip-width
   * element burns paint time for the life of the timeline. */
  failed?: boolean;
  /** The box is off screen: nothing to draw, and nothing to animate. */
  hidden?: boolean;
}) {
  // The filmstrip is a 40px always-on surface: the grade renders as a CSS
  // approximation (exact for the scalar sliders and the preset's scalars;
  // curves/wheels/hue bands show in the preview and exports).
  const { filter, tint } = gradeCssApprox(grade);
  if (hidden) return <div className="tl-filmstrip pointer-events-none absolute inset-0" />;
  // No thumbs yet — the media is still streaming into the browser store. A
  // placeholder slab fills the box until the strip can draw real frames.
  if (!frames.length) {
    if (block) {
      return (
        <div
          className="tl-filmstrip-block pointer-events-none absolute inset-0"
          style={{ background: block.color || BLOCK_COLOR }}
        />
      );
    }
    if (failed) {
      return (
        <div className="tl-filmstrip-failed pointer-events-none absolute inset-0 bg-[var(--skeleton)]" />
      );
    }
    // Both states cover the clip box's black with an opaque neutral slab, so a
    // clip waiting on thumbnails reads as a placeholder against the timeline's
    // chrome.
    return (
      <Skeleton className="tl-filmstrip-skeleton pointer-events-none absolute inset-0 rounded-none" />
    );
  }
  return (
    <div
      className="tl-filmstrip pointer-events-none absolute inset-0 isolate"
      style={{ filter: filter || undefined }}
    >
      {frames.map((f, k) => (
        // A tile keeps the width the plan gave it: the strip's grid is wider
        // than a short clip's box, and the base stylesheet's `max-width: 100%`
        // would squeeze that tile down to the box and leave the clip's black
        // showing beside it.
        // eslint-disable-next-line @next/next/no-img-element
        <img
          key={k}
          src={f.src}
          alt=""
          draggable={false}
          className="absolute top-0 h-full max-w-none object-cover"
          style={{ left: f.left, width: f.width }}
        />
      ))}
      {tint && (
        <div className="absolute inset-0" style={{ backgroundColor: tint, mixBlendMode: "multiply" }} />
      )}
    </div>
  );
}

/** A track-wide toggle pinned in the gutter column. Rests invisible until the
 * pointer is over the track area; while anything on its track is off it stays
 * visible on its own, the off glyph fading to say "some segments" versus the
 * full-strength "whole track". A click always turns the whole track off, and
 * the next click turns every segment back on — individually disabled segments
 * included. */
/** One row's gutter cell, and the handle for the whole row: pressing it picks
 * the row up and carries it to another place in its own band. A band with a
 * single row has no reorder in it, so the cell stays out of the way and the
 * gutter scrubs there as it always did. */
function RowGrip({
  top,
  height,
  barH,
  enabled,
  onGrab,
}: {
  top: number;
  height: number;
  /** The band's bar height, so the hover surface lines up with the bars on
   * the row instead of the row box they sit inside. */
  barH: number;
  enabled: boolean;
  onGrab: (e: React.PointerEvent) => void;
}) {
  const tr = useTranslations("timeline.clip");
  if (!enabled) return null;
  return (
    <div
      title={tr("reorderRow")}
      className="group pointer-events-auto absolute inset-x-0 cursor-grab"
      style={{ top, height }}
      onPointerDown={onGrab}
    >
      <span
        className="pointer-events-none absolute inset-x-0 bg-foreground/10 opacity-0 transition-opacity group-hover:opacity-100"
        style={{ top: 2, height: barH }}
      />
    </div>
  );
}

function GutterToggle({
  kind,
  off,
  partial,
  reveal,
  top,
  onToggle,
  onGrab,
}: {
  kind: "hide" | "mute";
  off: boolean;
  partial: boolean;
  reveal: boolean;
  top: number;
  onToggle: () => void;
  /** Grab the row this toggle rides. A press that travels is a row drag; one
   * that does not is a click on the toggle and nothing more. */
  onGrab?: (e: React.PointerEvent) => void;
}) {
  const tr = useTranslations("timeline.clip");
  const active = off || partial;
  const title =
    kind === "hide"
      ? off
        ? tr("showTrack")
        : tr("hideTrack")
      : off
        ? tr("unmuteTrack")
        : tr("muteTrack");
  const Icon = kind === "hide" ? (active ? EyeOff : Eye) : active ? VolumeX : Volume2;
  return (
    <button
      type="button"
      title={title}
      aria-label={title}
      className={cn(
        "tl-track-toggle pointer-events-auto absolute left-[3px] grid size-4 place-items-center transition-opacity",
        active ? "text-foreground" : "text-muted-foreground hover:text-foreground",
        active
          ? partial && !off
            ? "opacity-60 hover:opacity-100"
            : "opacity-100"
          : reveal
            ? "opacity-100"
            : "pointer-events-none opacity-0"
      )}
      style={{ top }}
      onPointerDown={(e) => {
        e.stopPropagation();
        if (!onGrab || e.button !== 0) return;
        const x = e.clientX;
        const y = e.clientY;
        const drop = () => {
          window.removeEventListener("pointermove", travel);
          window.removeEventListener("pointerup", drop);
          window.removeEventListener("pointercancel", drop);
        };
        // Once the press has travelled it belongs to the row, so the gesture
        // hands over from the press's own point and the click never lands.
        const travel = (ev: PointerEvent) => {
          if (Math.abs(ev.clientX - x) <= 3 && Math.abs(ev.clientY - y) <= 3) return;
          drop();
          onGrab(e);
        };
        window.addEventListener("pointermove", travel);
        window.addEventListener("pointerup", drop);
        window.addEventListener("pointercancel", drop);
      }}
      onClick={onToggle}
    >
      <Icon className="size-3" />
    </button>
  );
}

function HideChip({
  hidden,
  onToggle,
  className,
  small,
}: {
  hidden: boolean;
  onToggle: () => void;
  className?: string;
  /** The element bars are low; the chip steps down to fit them. */
  small?: boolean;
}) {
  const tr = useTranslations("timeline.clip");
  return (
    <button
      type="button"
      title={hidden ? tr("enable") : tr("disable")}
      aria-label={hidden ? tr("enable") : tr("disable")}
      className={cn(
        "tl-hide-chip absolute z-4 grid place-items-center rounded-[5px] bg-black/55 text-white transition-opacity hover:bg-black/75",
        small ? "size-[13px]" : "size-[18px]",
        hidden ? "opacity-100" : "opacity-0 group-hover:opacity-100",
        className
      )}
      onPointerDown={(e) => e.stopPropagation()}
      onClick={onToggle}
    >
      {hidden ? (
        <EyeOff className={small ? "size-2" : "size-3"} />
      ) : (
        <Eye className={small ? "size-2" : "size-3"} />
      )}
    </button>
  );
}

/** Corner chip for a timeline item whose media is still streaming into the
 * browser store. It sits where the hover controls live — the controls stay
 * off until the bytes land and the item scrubs, plays, and edits instantly. */
function LoadingChip() {
  return (
    <span className="tl-loading-chip pointer-events-none absolute bottom-1 left-1 z-4 grid size-[18px] place-items-center rounded-[5px] bg-black/55 text-white">
      <Loader2 className="size-3 animate-spin" />
    </span>
  );
}

/** Corner chip for a clip whose cloud file is not there (media.ts
 * missingMediaFor): an upload that never finished, or a file deleted from
 * under the project. The clip keeps its place and edits; nothing plays. */
function MissingChip({ assetId }: { assetId: string }) {
  const tr = useTranslations("timeline.clip");
  const missing = useSyncExternalStore(subscribeStripStatus, () => missingMediaFor(assetId), () => false);
  if (!missing) return null;
  return (
    <span className="tl-missing-chip pointer-events-none absolute right-1 bottom-1 z-4 rounded-[5px] bg-black/65 px-1.5 py-px text-[10px] whitespace-nowrap text-white">
      {tr("missingMedia")}
    </span>
  );
}

/** Hover chip that toggles a clip's own audio. Stays visible while the clip is
 * muted so unmuting is one click. */
function MuteChip({
  muted,
  onToggle,
  className,
}: {
  muted: boolean;
  onToggle: () => void;
  className?: string;
}) {
  const tr = useTranslations("timeline.clip");
  return (
    <button
      type="button"
      title={muted ? tr("unmute") : tr("mute")}
      aria-label={muted ? tr("unmute") : tr("mute")}
      className={cn(
        "tl-mute-chip absolute z-4 grid size-[18px] place-items-center rounded-[5px] bg-black/55 text-white transition-opacity hover:bg-black/75",
        muted ? "opacity-100 bg-black/70" : "opacity-0 group-hover:opacity-100",
        className
      )}
      onPointerDown={(e) => e.stopPropagation()}
      onClick={onToggle}
    >
      {muted ? <VolumeX className="size-3" /> : <Volume2 className="size-3" />}
    </button>
  );
}

/** A wave canvas's intrinsic width cap. A deep zoom puts a long song at
 * 100k+ px, far past the browser's canvas limit — one capped, CSS-stretched
 * canvas turns blocky there, so the strip is drawn as a run of tiles this
 * wide, each 1:1 with the pixel grid. */
const WAVE_TILE_W = 4096;

/** Waveform bars for the slice of `asset` between source times `from` and
 * `to`, across a `w`px bar. Each bar folds the max of every peak bucket it
 * covers, so a zoomed-out strip keeps its transients. */
function WaveformCanvas({
  asset,
  from,
  to,
  w,
  h,
  map,
  className,
}: {
  asset: MediaAsset;
  from: number;
  to: number;
  w: number;
  h: number;
  /** Source second at a pixel across the strip, for a clip whose rate changes
   * through the footage; absent, the strip runs linearly from `from` to `to`. */
  map?: (px: number) => number;
  className?: string;
}) {
  const peaks = asset.peaks;
  // The strip is drawn against the clip's own loudest moment, so a quietly
  // recorded clip shows its shape instead of a flat line (lib/waveform.ts).
  const gain = useMemo(() => waveGain(peaks ?? []), [peaks]);
  if (!peaks?.length) return null;
  const width = Math.max(1, Math.round(w));
  const tiles: { left: number; tw: number }[] = [];
  for (let left = 0; left < width; left += WAVE_TILE_W)
    tiles.push({ left, tw: Math.min(WAVE_TILE_W, width - left) });
  return (
    <div className={cn("pointer-events-none absolute overflow-hidden", className)}>
      {tiles.map((t) => (
        <WaveTile
          key={t.left}
          peaks={peaks}
          gain={gain}
          duration={asset.duration}
          from={map ? map(t.left) : from + (to - from) * (t.left / width)}
          to={map ? map(t.left + t.tw) : from + (to - from) * ((t.left + t.tw) / width)}
          left={t.left}
          tw={t.tw}
          h={h}
        />
      ))}
    </div>
  );
}

/** One tile of a waveform strip. A tile on or near the screen paints in its
 * effect; one far down a zoomed-out-of-view stretch waits for the viewport to
 * approach, so a deep zoom books backing store only for what gets seen. */
function WaveTile({
  peaks,
  gain,
  duration,
  from,
  to,
  left,
  tw,
  h,
}: {
  peaks: number[];
  gain: number;
  duration: number;
  from: number;
  to: number;
  left: number;
  tw: number;
  h: number;
}) {
  const ref = useRef<HTMLCanvasElement>(null);
  useEffect(() => {
    const canvas = ref.current;
    if (!canvas) return;
    let drawn = false;
    const draw = () => {
      if (drawn) return;
      drawn = true;
      const dpr = Math.min(2, window.devicePixelRatio || 1);
      canvas.width = Math.round(tw * dpr);
      canvas.height = Math.round(h * dpr);
      const ctx = canvas.getContext("2d")!;
      ctx.scale(dpr, dpr);
      ctx.fillStyle = "rgba(255, 255, 255, 0.85)";
      const n = peaks.length;
      const bars = Math.max(1, Math.floor(tw / 3));
      const start = (from / duration) * n;
      const perBar = (((to - from) / duration) * n) / bars;
      for (let i = 0; i < bars; i++) {
        // A stretch the file does not hold (a bound recording that started
        // late or stopped early) draws nothing.
        if (start + (i + 1) * perBar <= 0 || start + i * perBar >= n) continue;
        const a = Math.max(0, Math.min(n - 1, Math.floor(start + i * perBar)));
        const b = Math.max(a + 1, Math.ceil(start + (i + 1) * perBar));
        let p = 0;
        for (let j = a; j < b && j < n; j++) if (peaks[j] > p) p = peaks[j];
        const bh = Math.max(1.5, Math.min(1, p * gain) * (h - 2));
        ctx.fillRect(i * 3, (h - bh) / 2, 2, bh);
      }
    };
    // On-screen tiles paint now — a zoom redraws with no flicker — and the
    // rest paint as the viewport nears them.
    const r = canvas.getBoundingClientRect();
    if (r.right > -WAVE_TILE_W && r.left < window.innerWidth + WAVE_TILE_W) {
      draw();
      return;
    }
    const io = new IntersectionObserver(
      (entries) => {
        if (entries.some((e) => e.isIntersecting)) {
          draw();
          io.disconnect();
        }
      },
      { rootMargin: `50% ${WAVE_TILE_W}px` }
    );
    io.observe(canvas);
    return () => io.disconnect();
  }, [peaks, gain, duration, from, to, tw, h]);
  return <canvas ref={ref} className="absolute top-0" style={{ left, width: tw, height: h }} />;
}

/** Rewrite one asset's beat grid by hand: sorted, deduped, clamped to the
 * source; an emptied grid clears. Beats live on the asset in source seconds,
 * so every clip showing the source follows the edit. Editing a dot makes the
 * grid the user's rather than the detector's, so the tempo goes with it
 * (types.ts AssetBeats) — the row reads "N beats" from there on. */
function writeBeats(assetId: string, edit: (beats: number[]) => number[]) {
  const s = useEditor.getState();
  const asset = s.assets.find((a) => a.id === assetId);
  if (!asset) return;
  const next = [
    ...new Set(
      edit(asset.beats?.beats ?? []).map(
        (t) => Math.round(Math.min(asset.duration, Math.max(0, t)) * 1000) / 1000
      )
    ),
  ].sort((a, b) => a - b);
  s.updateAsset(assetId, { beats: next.length ? { beats: next, bpm: 0 } : undefined });
}

/** ⌥-click on a clip bar drops a beat under the pointer, in source seconds. */
function addBeatAt(
  e: React.PointerEvent<HTMLElement>,
  asset: MediaAsset,
  clip: { in: number; out: number; speed?: number; speedCurve?: SpeedNode[]; reverse?: boolean },
  pps: number
) {
  e.preventDefault();
  e.stopPropagation();
  const rect = e.currentTarget.getBoundingClientRect();
  useEditor.getState().pushHistory();
  writeBeats(asset.id, (list) => [...list, retimeOf(clip).srcAt((e.clientX - rect.left) / pps)]);
}

/**
 * One beat on a clip bar: a yellow dot on the bottom edge where the music
 * hits. The grab is its own (startDrag stops the bar's gesture), so dragging
 * a dot retimes the beat — in source seconds, every clip of the asset
 * follows — and a double-click removes it.
 */
function BeatDot({
  assetId,
  duration,
  t,
  retime,
  pps,
  w,
  title,
}: {
  /** The dot's hint, resolved once by the row of dots. */
  title: string;
  assetId: string;
  /** The source's length, the drag's bound. */
  duration: number;
  /** The beat, source seconds. */
  t: number;
  /** The bar's own map from its footage onto the timeline. */
  retime: Retime;
  pps: number;
  /** Visible bar width, px, for parking the edge dots inside it. */
  w: number;
}) {
  return (
    <span
      className="tl-beat absolute bottom-0 z-5 grid h-3.5 w-3 cursor-ew-resize place-items-end justify-center pb-[3px]"
      style={{
        left: Math.min(w - 4, Math.max(4, retime.tAt(t) * pps)),
        transform: "translateX(-50%)",
      }}
      title={title}
      onPointerDown={(e) => {
        const s = useEditor.getState();
        let live = t;
        // The undo step opens on the first movement, so a stray grab that
        // never moves leaves nothing behind.
        let checkpointed = false;
        startDrag(e, {
          onMove: (dx) => {
            if (!checkpointed) {
              checkpointed = true;
              s.pushHistory();
            }
            // Rounded the way the grid stores, so the moved beat is found again.
            const next =
              Math.round(
                Math.min(duration, Math.max(0, retime.srcAt(retime.tAt(t) + dx / pps))) * 1000
              ) / 1000;
            const at = live;
            writeBeats(assetId, (list) => list.map((b) => (b === at ? next : b)));
            live = next;
          },
        });
      }}
      onDoubleClick={(e) => {
        e.stopPropagation();
        useEditor.getState().pushHistory();
        writeBeats(assetId, (list) => list.filter((b) => b !== t));
      }}
    >
      <span className="pointer-events-none size-[5px] rounded-full bg-[#ffd60a] shadow-[0_0_0_1px_rgba(0,0,0,0.4)]" />
    </span>
  );
}

/** The asset's beat grid across one clip bar — the dots inside the bar's
 * source window `from..to`. */
function BeatDots({
  asset,
  lo,
  hi,
  retime,
  pps,
  w,
}: {
  asset: MediaAsset;
  /** The stretch of source the clip holds, low second first. A clip that
   * plays backward holds the same stretch and shows it in the other order,
   * so the window it is picked out of reads the same way either way. */
  lo: number;
  hi: number;
  retime: Retime;
  pps: number;
  w: number;
}) {
  const tr = useTranslations("timeline.clip");
  const beats = asset.beats?.beats;
  if (!beats?.length) return null;
  const title = tr("beat");
  return (
    <>
      {beats
        .filter((b) => b >= lo && b <= hi)
        .map((b) => (
          <BeatDot
            key={b}
            assetId={asset.id}
            duration={asset.duration}
            t={b}
            retime={retime}
            pps={pps}
            w={w}
            title={title}
          />
        ))}
    </>
  );
}

function AudioView({
  clip,
  asset,
  mention,
  pps,
  top,
  homeRow,
  rows,
  selected,
  drag,
  parting,
  rowMove,
  onDrag,
  onSnap,
}: {
  clip: AudioClip;
  asset: MediaAsset | undefined;
  /** The clip's chat mention token ("@s1"), shown on hover so the user can
   * point the assistant at this exact sound. Absent when its asset is gone. */
  mention: string | undefined;
  pps: number;
  /** Home-row top in px; while carried the ghost adds the pointer's offset. */
  top: number;
  homeRow: number;
  /** The band's rows read live, for the drag's row resolution. */
  rows: () => RowBox[];
  selected: boolean;
  /** This bar's live drag when it is the one being carried (ghost mode). */
  drag: LaneDrag | null;
  /** Another sound is dragging: animate this bar's shifts as it parts. */
  parting: boolean;
  /** A row drag is running in this band: "lift" is the row being carried,
   * "part" a row sliding into the place it closes up into. */
  rowMove: "lift" | "part" | null;
  /** Publish (or clear) the in-flight drag so the slot and rows track it. */
  onDrag: (d: LaneDrag | null) => void;
  /** Paint (or clear) the snap guide at this stage-x pixel. */
  onSnap: (x: number | null) => void;
}) {
  const loading = useEditor((s) => (asset ? s.loadingMedia.has(asset.fileName) : false));
  // Detached from a video bound to a recording, the clip plays the recording,
  // so the bar draws it on the video's clock.
  const recording = useEditor((s) => {
    const id = asset?.soundFrom?.assetId;
    return id ? s.assets.find((a) => a.id === id && !assetIsSilent(a)) : undefined;
  });
  const waveOff = recording ? (asset?.soundFrom?.offset ?? 0) : 0;
  const len = clipLen(clip);
  const w = Math.max(10, len * pps);
  // The bar is drawn a gutter narrower than the footprint; what sits inside
  // it measures against that.
  const barW = Math.max(10, w - CLIP_GAP);
  const rt = retimeOf(clip);
  // The fade being dragged, held here rather than in the grip: the ramp line
  // and the waveform's clip both follow it, so all three move as one.
  const [liveFade, setLiveFade] = useState<{ side: "in" | "out"; v: number } | null>(null);
  const fadeIn = liveFade?.side === "in" ? liveFade.v : (clip.fadeIn ?? 0);
  const fadeOut = liveFade?.side === "out" ? liveFade.v : (clip.fadeOut ?? 0);
  // Both ramps stay inside the bar and clear of each other, even if an older
  // doc carries fades that outgrew a since-trimmed clip.
  const fadeInPx = Math.max(0, Math.min(barW, fadeIn * pps));
  const fadeOutPx = Math.max(0, Math.min(barW - fadeInPx, fadeOut * pps));

  if (!asset) return null;

  const ui = { pps, rows, homeRow, onDrag, onSnap };

  return (
    <div
      className={cn(
        "tl-audio-clip group absolute cursor-grab overflow-hidden rounded-[2.5px] bg-gradient-to-b from-emerald-500 to-emerald-600 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.1)]",
        selected && SELECTED_SHADOW,
        clip.hidden && "opacity-40 grayscale",
        drag
          ? "tl-audio-ghost pointer-events-none cursor-grabbing opacity-80 shadow-2xl"
          : parting && "transition-[left] duration-150 ease-out",
        rowMove === "lift"
          ? "pointer-events-none opacity-80 shadow-2xl"
          : rowMove === "part" && "transition-[top] duration-150 ease-out"
      )}
      style={{
        left: drag ? drag.ghostX : clip.start * pps,
        top: top + 2 + (drag ? drag.ghostY : 0),
        width: barW,
        height: AUDIO_H - 4,
        // Inline so it beats SELECTED_SHADOW's z-10 class on the same element.
        zIndex: drag || rowMove === "lift" ? 20 : undefined,
      }}
      data-tl-sel={`audio:${clip.id}`}
      onPointerDown={(e) => {
        if (e.altKey && !assetIsSilent(asset)) {
          addBeatAt(e, asset, clip, pps);
          return;
        }
        startLaneMove(e, "audio", clip.id, ui);
      }}
    >
      <div
        className="pointer-events-none absolute inset-0"
        style={{ clipPath: fadeClipPath(fadeInPx, fadeOutPx, barW) }}
      >
        <WaveformCanvas asset={recording ?? asset} from={clip.in + waveOff} to={clip.out + waveOff} w={barW} h={AUDIO_H - 8} map={rt.uniform && !rt.reverse ? undefined : (px) => rt.srcAt(px / pps) + waveOff} className="inset-x-0 inset-y-1" />
      </div>
      <BeatDots asset={asset} lo={clip.in} hi={clip.out} retime={rt} pps={pps} w={barW} />
      <FadeEnvelope inPx={fadeInPx} outPx={fadeOutPx} barW={barW} />
      <FadeGrip clip={clip} side="in" pps={pps} barW={barW} fade={fadeIn} live={liveFade?.side === "in"} onLive={setLiveFade} />
      <FadeGrip clip={clip} side="out" pps={pps} barW={barW} fade={fadeOut} live={liveFade?.side === "out"} onLive={setLiveFade} />
      <span
        className={cn(
          "pointer-events-none absolute top-[3px] left-2 text-[9.5px] whitespace-nowrap text-white/90 transition-opacity [text-shadow:0_1px_2px_rgba(0,0,0,0.35)]",
          // On hover the mention chip takes the corner, so step the name aside.
          mention && !drag && "group-hover:opacity-0"
        )}
      >
        {clipName(clip, asset)}
      </span>
      {mention && !drag && !loading && (
        <span className="tl-mention-chip pointer-events-none absolute top-1 left-1 z-2 rounded-[5px] bg-black/65 px-1.5 py-px font-mono text-[10px] text-white opacity-0 transition-opacity group-hover:opacity-100">
          {mention}
        </span>
      )}
      {loading && <LoadingChip />}
      <MissingChip assetId={asset.id} />
      {!loading && <ClipMenu asset={asset} clip={clip} />}
      {!loading && (
        <MuteChip
          muted={!!clip.hidden}
          className="bottom-1 left-1"
          onToggle={() => useEditor.getState().updateAudio(clip.id, { hidden: !clip.hidden })}
        />
      )}
      <span
        className={cn(trimFor(barW), "tl-trim-l left-0")}
        onPointerDown={(e) => startLaneTrim(e, "audio", clip.id, "l", ui)}
      />
      <span
        className={cn(trimFor(barW), "tl-trim-r right-0")}
        onPointerDown={(e) => startLaneTrim(e, "audio", clip.id, "r", ui)}
      />
    </div>
  );
}

/** Width of the fade grab zone at the ramp's inner end. */
const FADE_W = 14;

/** The ramp's height inside the bar: `TOP` is full volume, `BOT` is silence.
 * Both the drawn line and the waveform's clip measure from these, so the sound
 * always sits exactly under the line. They clear the waveform's own inset, so
 * an untouched end keeps its full peaks. */
const FADE_TOP_Y = 1;
const FADE_BOT_Y = AUDIO_H - 5;

/**
 * The bar's waveform clip: the region under the volume ramp. The envelope
 * climbs from silence to full across the fade in, holds, then falls back to
 * silence across the fade out — so the drawn sound is cut to the shape it
 * actually plays at. No fade leaves the waveform whole.
 */
function fadeClipPath(inPx: number, outPx: number, barW: number): string | undefined {
  if (inPx <= 0 && outPx <= 0) return undefined;
  const pts = [
    `0px ${FADE_BOT_Y}px`,
    `${inPx}px ${FADE_TOP_Y}px`,
    `${barW - outPx}px ${FADE_TOP_Y}px`,
    `${barW}px ${FADE_BOT_Y}px`,
    `${barW}px 100%`,
    `0px 100%`,
  ];
  return `polygon(${pts.join(", ")})`;
}

/** The ramp itself, drawn over the sound it cuts: up from the bottom-left
 * across the fade in, down to the bottom-right across the fade out. */
function FadeEnvelope({ inPx, outPx, barW }: { inPx: number; outPx: number; barW: number }) {
  if (inPx <= 0 && outPx <= 0) return null;
  return (
    <svg
      className="pointer-events-none absolute inset-0 z-2"
      width={barW}
      height={AUDIO_H - 4}
      style={{ filter: "drop-shadow(0 1px 1px rgba(0,0,0,0.55))" }}
      aria-hidden
    >
      <g fill="none" stroke="white" strokeOpacity={0.95} strokeWidth={1.5} strokeLinecap="round">
        {inPx > 0 && <path className="tl-fade-in" d={`M 0 ${FADE_BOT_Y} L ${inPx} ${FADE_TOP_Y}`} />}
        {outPx > 0 && (
          <path className="tl-fade-out" d={`M ${barW - outPx} ${FADE_TOP_Y} L ${barW} ${FADE_BOT_Y}`} />
        )}
      </g>
    </svg>
  );
}

/**
 * The grab at a ramp's full-volume end — a dot at the top, over a full-height
 * column so the drag is easy to catch. Dragging it sets the fade's length:
 * right from the head for the fade in, left from the tail for the fade out.
 * With no fade yet the dot waits at the clip's edge and shows on hover, so the
 * corner reads as a grip. It sits below the bar's chips (z-3, the trim
 * handles' layer) so a mute or a menu the ramp reaches still takes its own
 * click, and it writes the same field the Inspector's slider does, capped at
 * half the clip, as one undo step.
 */
function FadeGrip({
  clip,
  side,
  pps,
  barW,
  fade,
  live,
  onLive,
}: {
  clip: AudioClip;
  side: "in" | "out";
  pps: number;
  barW: number;
  /** The fade this grip shows, the in-flight value while it is the one dragging. */
  fade: number;
  live: boolean;
  onLive: (v: { side: "in" | "out"; v: number } | null) => void;
}) {
  const tr = useTranslations("timeline.clip");
  const px = Math.min(barW, fade * pps);
  // The grip keeps clear of the trim grab at its own end, so an edge grab still trims.
  const at = Math.max(TRIM_W + 2, px);
  const field = side === "in" ? "fadeIn" : "fadeOut";
  const edge = side === "in" ? "left" : "right";

  const grab = (e: React.PointerEvent) => {
    if (e.button !== 0) return;
    const s = useEditor.getState();
    if (s.readOnly) return;
    if (s.playing) s.setPlaying(false);
    s.select({ kind: "audio", id: clip.id });
    s.pushHistory();
    const f0 = (side === "in" ? clip.fadeIn : clip.fadeOut) ?? 0;
    const max = maxClipFade(clip);
    let v = f0;
    startDrag(e, {
      cursor: () => "ew-resize",
      onMove: (dx) => {
        const raw = side === "in" ? f0 + dx / pps : f0 - dx / pps;
        // Tenths, the step the Inspector's slider and its readout both use.
        v = Math.min(max, Math.max(0, Math.round(raw * 10) / 10));
        onLive({ side, v });
        useEditor.getState().updateAudioTransient(clip.id, { [field]: v > 0 ? v : undefined });
      },
      onUp: () => {
        onLive(null);
        useEditor.getState().updateAudioTransient(clip.id, { [field]: v > 0 ? v : undefined });
      },
    });
  };

  return (
    <>
      <span
        className={cn(
          "tl-fade-grip absolute inset-y-0 z-3 cursor-ew-resize",
          side === "in" ? "tl-fade-grip-in" : "tl-fade-grip-out"
        )}
        style={{ width: FADE_W, [edge]: at - FADE_W / 2 }}
        title={side === "in" ? tr("fadeIn") : tr("fadeOut")}
        onPointerDown={grab}
      >
        <span
          className={cn(
            "absolute top-px left-1/2 size-[7px] -translate-x-1/2 rounded-full bg-white shadow-[0_0_0_1px_rgba(0,0,0,0.45)] transition-opacity",
            // A set fade keeps its grip in view; an unset one only hints on hover.
            fade > 0 ? "opacity-90" : "opacity-0 group-hover:opacity-70",
            live && "opacity-100"
          )}
        />
      </span>
      {live && (
        <span
          className="pointer-events-none absolute top-1/2 z-5 -translate-y-1/2 rounded-[4px] bg-black/75 px-1 font-mono text-[10px] leading-4 text-white"
          style={{ [edge]: at + FADE_W / 2 }}
        >
          {fade.toFixed(1)}s
        </span>
      )}
    </>
  );
}

/** The keyframe diamond's grab square — wider than the diamond itself, since
 * a 6px target is not one. Paired with the `size-` on the marker below. */
const KEY_HIT = 14;

/**
 * One keyframe on an item's bar — an element's or a video clip's, on its
 * pose track (white diamond) or its mask's (amber): a diamond where the key
 * falls, dragged left and right to retime it. The grab is kept off the bar
 * underneath, so moving a key never moves the item it belongs to. `kind`
 * and `track` pick which store actions the gestures write.
 */
function KeyMarker({
  item,
  kind,
  track = "pose",
  t,
  pps,
  width,
  onMenu,
}: {
  item: { id: string; start: number; end: number };
  kind: "overlay" | "clip";
  track?: "pose" | "mask";
  t: number;
  pps: number;
  width: number;
  /** The bar's right-click menu; a key click carries its time, so the menu
   * offers to remove it. Absent (clip bars), the bar's own menu handles the
   * click and Delete removes the picked key. */
  onMenu?: (m: { x: number; y: number; id: string; key?: number }) => void;
}) {
  const tr = useTranslations("timeline.clip");
  const picked = useEditor(
    (s) =>
      !!s.selectedKey &&
      s.selectedKey.kind === kind &&
      s.selectedKey.track === track &&
      s.selectedKey.id === item.id &&
      s.selectedKey.t === t
  );
  // Park clear of the trim handles: a key dragged to the very end would
  // otherwise sit under one and stop being grabbable. Those last few pixels
  // cost some positional accuracy, which the bar's own edge already conveys.
  const inset = Math.min(TRIM_W + KEY_HIT / 2, Math.max(3, (width - 8) / 2));
  return (
    <span
      // Above the hover chips (z-4): a key parked at the bar's end must stay
      // grabbable — retiming lives only here, while hide/mute also live in
      // the inspector.
      className="tl-key pointer-events-auto absolute top-1/2 z-5 grid size-3.5 cursor-ew-resize place-items-center"
      style={{
        left: Math.min(width - inset, Math.max(inset, t * pps)),
        transform: "translate(-50%, -50%)",
      }}
      title={tr("key")}
      onContextMenu={
        onMenu
          ? (e) => {
              e.preventDefault();
              e.stopPropagation();
              onMenu({ x: e.clientX, y: e.clientY, id: item.id, key: t });
            }
          : undefined
      }
      onPointerDown={(e) => {
        const s = useEditor.getState();
        const select =
          kind === "overlay"
            ? track === "mask"
              ? s.selectOverlayMaskKey
              : s.selectOverlayKey
            : track === "mask"
              ? s.selectClipMaskKey
              : s.selectClipKey;
        const move =
          kind === "overlay"
            ? track === "mask"
              ? s.moveOverlayMaskKey
              : s.moveOverlayKey
            : track === "mask"
              ? s.moveClipMaskKey
              : s.moveClipKey;
        select(item.id, t);
        let live = t;
        // The undo step opens on the first movement, so a click that only
        // seeks does not leave one behind.
        let checkpointed = false;
        startDrag(e, {
          onMove: (dx) => {
            if (!checkpointed) {
              checkpointed = true;
              s.pushHistory();
            }
            const next = Math.max(0, t + dx / pps);
            move(item.id, live, next, { transient: true });
            live = Math.max(0, Math.min(next, Math.max(0.1, item.end - item.start)));
          },
          // A click that never moved reads as "show me this key": the playhead
          // goes there, and the inspector's rows follow it.
          onUp: (_dx, _dy, moved) => {
            if (!moved) s.seek(item.start + live);
          },
        });
      }}
    >
      <span
        className={cn(
          "pointer-events-none rotate-45 shadow-[0_0_0_1px_rgba(0,0,0,0.35)] transition-[width,height]",
          track === "mask" ? "bg-[#ff9f0a]" : "bg-white",
          picked ? "size-[9px] ring-[1.5px] ring-[#0a84ff]" : "size-[6px]"
        )}
      />
    </span>
  );
}

/** The sticker itself, small, at the head of its bar — a row of stickers reads
 * as which stickers they are. A Lottie has no still to show, so it keeps the
 * glyph. */
function StickerThumb({ overlay: o }: { overlay: StickerOverlay }) {
  const asset = useEditor((s) => (o.assetId ? s.assets.find((a) => a.id === o.assetId) : undefined));
  if (!asset || o.lottie) return <Sticker className="mr-1 size-2.5 shrink-0" />;
  return (
    // eslint-disable-next-line @next/next/no-img-element -- project media URL
    <img
      src={asset.url}
      alt=""
      loading="lazy"
      className="mr-1 size-4 shrink-0 object-contain"
    />
  );
}

function TextBar({
  overlay: o,
  pps,
  top,
  homeRow,
  rows,
  selected,
  drag,
  parting,
  rowMove,
  onDrag,
  onSnap,
  onMenu,
}: {
  overlay: Overlay;
  pps: number;
  top: number;
  homeRow: number;
  /** The band's rows read live, for the drag's row resolution. */
  rows: () => RowBox[];
  selected: boolean;
  /** A row drag is running in this band: "lift" is the row being carried,
   * "part" a row sliding into the place it closes up into. */
  rowMove: "lift" | "part" | null;
  /** This bar's live drag when it is the one being carried (ghost mode). */
  drag: LaneDrag | null;
  /** Another title is dragging: animate this bar's shifts as it parts. */
  parting: boolean;
  /** Publish (or clear) the in-flight drag so the slot and lanes track it. */
  onDrag: (d: LaneDrag | null) => void;
  /** Paint (or clear) the snap guide at this stage-x pixel. */
  onSnap: (x: number | null) => void;
  /** Open the bar's right-click menu; `key` set when it landed on a keyframe. */
  onMenu: (m: { x: number; y: number; id: string; key?: number }) => void;
}) {
  const tr = useTranslations("timeline.clip");
  const shapeLabel = useLabels("shape");
  const effectLabel = useLabels("effect");
  const w = Math.max(8, (o.end - o.start) * pps);
  // The bar is drawn a gutter narrower than the footprint; the keys on it
  // measure against that.
  const barW = Math.max(8, w - CLIP_GAP);
  const ui = { pps, rows, homeRow, onDrag, onSnap };
  // Per-kind chip content: a title shows its text, a shape its name behind a
  // shape glyph, a sticker its glyph and name.
  const ShapeIcon = SHAPE_CHIP_ICONS[o.kind === "shape" ? o.shape : "rect"];
  // The name the person gave it, else what it is in the page's language; a
  // title's own text is its name.
  const own = o.name?.trim();
  const name =
    own ||
    (o.kind === "shape"
      ? shapeLabel(o.shape)
      : o.kind === "effect"
        ? effectLabel(o.effect)
        : o.kind === "sticker"
          ? tr("sticker")
          : overlayName(o));
  const chip =
    o.kind === "shape" ? (
      <>
        <ShapeIcon className="mr-1 size-2.5 shrink-0" />
        {name}
      </>
    ) : o.kind === "sticker" ? (
      <>
        <StickerThumb overlay={o} />
        {name}
      </>
    ) : o.kind === "effect" ? (
      <>
        <EffectChipIcon effect={o.effect} />
        {name}
      </>
    ) : (
      name
    );

  return (
    <div
      className={cn(
        "tl-text-bar group absolute flex cursor-grab items-center overflow-hidden rounded-[3px] shadow-[inset_0_0_0_1px_rgba(0,0,0,0.1)]",
        FAMILY_STYLE[overlayFamily(o)].bar,
        o.hidden && "opacity-40 grayscale",
        selected && SELECTED_SHADOW,
        drag
          ? "tl-text-ghost pointer-events-none cursor-grabbing opacity-80 shadow-2xl"
          : parting && "transition-[left] duration-150 ease-out",
        rowMove === "lift"
          ? "pointer-events-none opacity-80 shadow-2xl"
          : rowMove === "part" && "transition-[top] duration-150 ease-out"
      )}
      style={{
        left: drag ? drag.ghostX : o.start * pps,
        top: top + 2 + (drag ? drag.ghostY : 0),
        width: barW,
        height: TEXT_H - 6,
        // Inline so it beats SELECTED_SHADOW's z-10 class on the same element.
        zIndex: drag || rowMove === "lift" ? 20 : undefined,
      }}
      data-tl-sel={`overlay:${o.id}`}
      onPointerDown={(e) => startLaneMove(e, "overlay", o.id, ui)}
      onContextMenu={(e) => {
        e.preventDefault();
        onMenu({ x: e.clientX, y: e.clientY, id: o.id });
      }}
    >
      <span
        className="pointer-events-none flex min-w-0 items-center truncate px-2 text-[10.5px] font-medium text-white"
        // A title's chip is set in its own typeface and color, so the row reads
        // like the picture. The other text properties stay the bar's own.
        style={isTextOverlay(o) ? { fontFamily: fontStack(o.font), color: o.color } : undefined}
      >
        {chip}
      </span>
      {/* Keys sit on the bar where they fall, so a track is visible without
          opening the inspector. */}
      {(o.kf ?? []).map((k) => (
        <KeyMarker key={k.t} item={o} kind="overlay" t={k.t} pps={pps} width={barW} onMenu={onMenu} />
      ))}
      {(o.mask?.kf ?? []).map((k) => (
        <KeyMarker key={`m${k.t}`} item={o} kind="overlay" track="mask" t={k.t} pps={pps} width={barW} />
      ))}
      <HideChip
        hidden={!!o.hidden}
        small
        className="top-1/2 right-2 -translate-y-1/2"
        onToggle={() => useEditor.getState().updateOverlay(o.id, { hidden: !o.hidden })}
      />
      <span
        className={cn(trimFor(barW), "tl-trim-l left-0")}
        onPointerDown={(e) => startLaneTrim(e, "overlay", o.id, "l", ui)}
      />
      <span
        className={cn(trimFor(barW), "tl-trim-r right-0")}
        onPointerDown={(e) => startLaneTrim(e, "overlay", o.id, "r", ui)}
      />
    </div>
  );
}

/** A subtitle cue on its track: click selects (⌫ deletes it), drag to retime,
 * edges to trim. Editing the words happens in the Subtitles panel. */
function SubBar({
  cue,
  dimmed,
  pps,
  top,
  homeRow,
  selected,
  drag,
  parting,
  onDrag,
  onSnap,
}: {
  cue: SubtitleCue;
  /** The cue's track is hidden — gray the bar like a hidden clip. */
  dimmed: boolean;
  pps: number;
  /** Rendered row top in px — one row per subtitle track (language). */
  top: number;
  homeRow: number;
  selected: boolean;
  /** This bar's live drag when it is the one being carried (ghost mode). */
  drag: LaneDrag | null;
  /** Another cue is dragging: animate this bar's shifts as it parts. */
  parting: boolean;
  onDrag: (d: LaneDrag | null) => void;
  onSnap: (x: number | null) => void;
}) {
  const w = Math.max(8, (cue.end - cue.start) * pps);
  // A cue never leaves its language row, so the band's rows go unread.
  const ui = { pps, rows: () => [], homeRow, onDrag, onSnap };

  return (
    <div
      className={cn(
        "tl-sub-bar group absolute flex cursor-grab items-center overflow-hidden rounded-[2.5px] bg-gradient-to-b from-amber-300 to-amber-400 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.12)]",
        dimmed && "opacity-40 grayscale",
        selected && SELECTED_SHADOW,
        drag
          ? "tl-sub-ghost pointer-events-none cursor-grabbing opacity-80 shadow-2xl"
          : parting && "transition-[left] duration-150 ease-out"
      )}
      style={{
        left: drag ? drag.ghostX : cue.start * pps,
        top: top + 1 + (drag ? drag.ghostY : 0),
        width: Math.max(8, w - CLIP_GAP),
        height: SUB_H - 4,
        // Inline so it beats SELECTED_SHADOW's z-10 class on the same element.
        zIndex: drag ? 20 : undefined,
      }}
      title={cue.text}
      data-tl-sel={`cue:${cue.id}`}
      onPointerDown={(e) => startLaneMove(e, "cue", cue.id, ui)}
    >
      <span className="pointer-events-none truncate px-1.5 text-[9.5px] font-medium text-amber-950/90">
        {cue.text}
      </span>
      <span
        className={cn(trimFor(w - CLIP_GAP), "tl-trim-l left-0")}
        onPointerDown={(e) => startLaneTrim(e, "cue", cue.id, "l", ui)}
      />
      <span
        className={cn(trimFor(w - CLIP_GAP), "tl-trim-r right-0")}
        onPointerDown={(e) => startLaneTrim(e, "cue", cue.id, "r", ui)}
      />
    </div>
  );
}

/** The landing-slot preview for an in-flight lane drag, drawn in the band's
 * own chrome; it tracks the coordinator's resolved slot, at the row top the
 * band resolves for it. */
function LaneSlot({
  drag,
  pps,
  top,
  barH,
  className,
}: {
  drag: LaneDrag;
  pps: number;
  top: number;
  barH: number;
  className: string;
}) {
  return (
    <div
      className={cn(
        "tl-lane-slot pointer-events-none absolute transition-[left] duration-150 ease-out",
        className
      )}
      style={{
        left: drag.slotStart * pps,
        top,
        width: Math.max(8, drag.len * pps - CLIP_GAP),
        height: barH,
      }}
    />
  );
}