Skip to content

Open source CapCut alternative.

TypeScript
205 KB
Raw Blame
"use client";

import { useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { AlignCenter, AlignHorizontalSpaceAround, AlignLeft, AlignRight, AlignVerticalSpaceAround, ChevronLeft, ChevronRight, Diamond, FlipHorizontal2, FlipVertical2, Frame, House, Italic, Link2, Link2Off, Loader2, type LucideIcon, Palette, PanelRightClose, PanelRightOpen, PanelTopClose, PenTool, Plus, Scissors, Smile, Sparkles, StretchHorizontal, Trash2, Type, User, Volume2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { EmojiPicker } from "@/cut/components/EmojiPicker";
import { FontPicker } from "@/cut/components/FontPicker";
import { ClipAnimationTiles, previewBar } from "@/cut/components/TransitionsPanel";
import { ClipEffectsSection } from "@/cut/components/ClipEffectsSection";
import { TrackRow } from "@/cut/components/TrackRow";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { Textarea } from "@/components/ui/textarea";
import {
  hasMaskKeys,
  hasOverlayAnim,
  hasOverlayKeys,
  KEY_EPSILON,
  keyIndexAt,
  dealsMarks,
  DOODLE_INKS,
  DOODLE_INKS_MAX,
  LETTER_SPACING_MAX,
  LETTER_SPACING_MIN,
  lineLikeShape,
  maskFrameAt,
  poseAt,
  keyPoseAt,
  TILT_MAX,
  type Mask,
  type MaskKey,
  type MaskKind,
  type OverlayKey,
  OVERLAY_ANIM_DEFAULT_SECONDS,
  edgeMaxSeconds,
  OVERLAY_ANIM_MIN_SECONDS,
  CARET_BLINKS_MAX,
  edgeMotion,
  edgeStagger,
  EDGE_STAGGER_MAX,
  EDGE_BLUR_MAX,
  EDGE_DISTANCE_MAX,
  EDGE_REEL_EM_MAX,
  EDGE_SETTLE_MAX,
  LINE_HEIGHT,
  REEL_DIRECTIONS,
  SLOT_PITCH,
  type ReelDirection,
  EASE_IDS,
  type EaseId,
  edgeOwnReach,
  edgePreset,
  type OverlayEdge,
  keepCaret,
  OVERLAY_HIT_DEFAULT_SECONDS,
  OVERLAY_HIT_MAX_SECONDS,
  OVERLAY_HIT_MIN_SECONDS,
  type OverlayCaret,
  type OverlayHit,
  normalizeSound,
  SOUND_COMPRESSOR_DEFAULT,
  SOUND_COMPRESSOR_RANGE,
  SOUND_EQ_BANDS,
  SOUND_EQ_DB_RANGE,
  SOUND_LIMITER_DEFAULT,
  SOUND_LIMITER_RANGE,
  SOUND_PRESETS,
  type ClipSound,
  ZOOM_LEVELS,
  ZOOM_RAMP_MAX,
  zoomRampOf,
  wordAccent,
  wordDim,
  wordEffect,
  wordKnobs,
  WORD_ACCENT_DEFAULT,
  WORD_POP_SCALE,
  WORD_SWELL_MAX,
  WORD_SWELL_MIN,
  wordSwell,
  type OverlayAnim,
  type OverlayAnimStyle,
  type OverlayLoopStyle,
  type WordEffectId,
  retimeOf,
  flatSpeedCurve,
  hasSpeedCurve,
  MASK_FEATHER_MAX,
  MASK_RADIUS_MAX,
  MASK_SHAPES,
  maskHasRadius,
  maskOutlinePathD,
  maskSizeAxes,
  penClosed,
  restingMaskFrame,
  AMOUNTLESS_EFFECTS,
  displayWords,
  CYCLE_HOLD_MAX,
  CYCLE_SCALE_MAX,
  CYCLE_SCALE_MIN,
  FONT_CYCLE_FACES_MAX,
  FONT_CYCLE_RATE,
  FONT_CYCLE_RATE_MAX,
  FONT_CYCLE_RATE_MIN,
  TEXT_WEIGHTS,
  LEAK_COURSES,
  type LeakCourse,
  GLITCH_KINDS,
  type GlitchKind,
  TEXT_TEXTURES,
  type TextTexture,
  type CycleFace,
  type OverlayFontCycle,
  type TextWeight,
} from "@donkeycut/effects-kit";
import { SHADOW, SHADOW_BLUR_MAX, SHADOW_OFFSET_MAX, STRIPE_GAP_MAX, STRIPE_LINE_MAX, STRIPE_LINE_MIN, STRIPES_DEFAULT, type FlashPulse, type ShadowSpec, type StripesPattern } from "@donkeycut/effects-kit";
import { BLOCK_COLOR } from "@/cut/lib/blockSource";
import { beatSwitches, clipBeatTimes, CYCLE_BEAT_STEPS, switchProblem, tidySwitches, timedFontCycle } from "@/cut/lib/fontCycleTiming";
import { bindRecording, unbindRecording } from "@/cut/lib/soundBind";
import { SPLIT_EDIT_MAX_S } from "@/cut/lib/soundSource";
import { clipLen, clipWindow, maxClipFade, useEditor, type EditorState } from "@/cut/lib/store";
import { PANEL_GLOBAL, usePanelState, useRememberedScroll } from "@/cut/lib/panelState";
import { playheadAt, usePreviewTime } from "@/cut/lib/playhead";
import { allFonts, CLIP_MAX_ZOOM, clipCovers, clipKeyed, clipPoseAt, clipZoom, contentRect } from "@/cut/lib/types";
import { AnimationTiles } from "@/cut/components/AnimationTiles";
import { LOOP_SPEED_MAX, LOOP_SPEED_MIN } from "@/cut/components/AnimationTiles.tools";
import { STICKER_W_MIN } from "@/cut/components/Inspector.tools";
import { TEXT_SIZE_MAX, TEXT_SIZE_MIN } from "@/cut/components/Timeline.tools";
import { FlashFadeRow, FlashPulseRows, type PulseWrite } from "@/cut/components/FlashPulseRows";
import { ColorField } from "@/cut/components/ColorField";
import { wordTimesFor } from "@/cut/lib/textWords";
import { NumberField } from "@/cut/components/NumberField";
import { playAnimPreview, stopAnimPreview } from "@/cut/lib/animPreview";
import { GenerateSubtitlesAudio } from "@/cut/components/VoicePicker";
import {
  parseNumberInput,
  parsePercentInput,
  parseSecondsInput,
  parseSpeedInput,
  parseTimeInput,
  ScrubValue,
} from "@/cut/components/ScrubValue";
import { ValueSlider } from "@/cut/components/ValueSlider";
import { PLATE_COLOR, PLATE_OPACITY, PLATE_RADIUS, plateFill } from "@/cut/lib/textRender";
import {
  deleteStylePreset,
  listStylePresets,
  saveStylePreset,
  styleMatches,
  updateStylePreset,
  type StylePreset,
} from "@/cut/lib/stylePresets";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { PICKED_RING } from "@/cut/lib/assetPick";
import {
  deleteSoundPreset,
  saveSoundPreset,
  soundPresetOf,
  type SoundPreset,
} from "@/cut/lib/soundPresets";
import { patchLibrary, refetchLibrary, useLibrary } from "@/cut/lib/queries";
import { TEXT_SIZES, writeTextStyle } from "@/cut/lib/textStyle";
import { formatTime } from "@/cut/lib/time";
import { cueSpot } from "@/cut/lib/subtitles";
import { cueEmphasis } from "@/cut/lib/captionEmphasis";
import {
  fontStack,
  frameOf,
  isEffectOverlay,
  isShapeOverlay,
  isTextOverlay,
  type ClipAnim,
  LAYOUTS,
  onFontsChanged,
  rectOf,
  regionLabel,
  SPEED_FLOOR,
  SPEED_MAX,
  SPEED_MIN,
  assetIsSilent,
  clampKeyPos,
  clampOverlayPos,
  type AudioClip,
  type BoxStyle,
  type ClipShadow,
  type FrameRect,
  type LayoutId,
  type EffectOverlay,
  type MediaAsset,
  overlayName,
  type Overlay,
  type Selection,
  type ShapeOverlay,
  type StickerOverlay,
  type SubtitleCue,
  type TextOverlay,
  type VideoClip,
  ANIM_DEFAULT_SECONDS,
  TRANSITION_MAX,
  type AnimStyle,
} from "@/cut/lib/types";
import { beatsBusyFor, detectAssetBeats, subscribeBeatsBusy } from "@/cut/lib/media";
import { reportSwallowed } from "@/cut/lib/report";
import {
  MOVE_STRENGTH_MAX,
  MOVE_STRENGTH_MIN,
  MOVE_STRENGTH_STEP,
} from "@/cut/lib/textMotion";
import { getPreviewCanvas } from "@/cut/lib/previewCanvas";
import { cn } from "@/lib/utils";
import { useDescribeError } from "@/i18n/describeError";
import { useLabels } from "@/i18n/labels";
import type { Messages } from "@/i18n/namespaces";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Field, ResetButton, Row, Section, SegGroup, SegToggle, Tip, useSliderCheckpoint, Value } from "@/cut/components/panelBits";
import { ColorPanel } from "@/cut/components/ColorPanel";
import { GroupPanel } from "@/cut/components/GroupPanel";
import { ClipMotionRows, ElementMotionRows } from "@/cut/components/MotionControls";
import { RemovalPanel } from "@/cut/components/RemovalPanel";
import { CameraCardSection } from "@/cut/components/CameraCardSection";
import { useMatteBakes } from "@/cut/lib/removal/bakeJobs";

/**
 * Whether the selection has a panel to show. Nothing selected or a transition
 * bar (the Transitions tab is its panel) leaves the panel out and the preview
 * takes the space. A subtitle cue opens its own small panel: its spot and its
 * emphasized words.
 */
export function useHasInspector() {
  return useEditor((s) => {
    if (s.readOnly || s.selection == null) return false;
    // Two or more items open the group panel over what they share, whatever
    // was clicked last; one item opens its own panel.
    if (s.multiSelection.filter((m) => m && m.kind !== "cue" && m.kind !== "transition").length >= 2) return true;
    if (s.selection.kind === "cue") {
      const id = s.selection.id;
      return s.subtitles.cues.some((c) => c.id === id);
    }
    return s.selection.kind !== "transition";
  });
}

export function Inspector() {
  const selection = useEditor((s) => s.selection);
  const multi = useEditor((s) => s.multiSelection);
  // Two or more items open the group panel over what they share; one item
  // opens its own panel.
  const group = useMemo(() => {
    const items = multi.filter((m): m is NonNullable<Selection> => !!m && m.kind !== "cue" && m.kind !== "transition");
    return items.length >= 2 ? items : null;
  }, [multi]);
  const clip = useEditor((s) =>
    selection?.kind === "clip" ? s.clips.find((c) => c.id === selection.id) : undefined
  );
  const audio = useEditor((s) =>
    selection?.kind === "audio" ? s.audioClips.find((c) => c.id === selection.id) : undefined
  );
  const overlay = useEditor((s) =>
    selection?.kind === "overlay" ? s.overlays.find((o) => o.id === selection.id) : undefined
  );
  const cue = useEditor((s) =>
    selection?.kind === "cue" ? s.subtitles.cues.find((c) => c.id === selection.id) : undefined
  );

  // The layer floats over the editor: the preview runs the full width of the
  // row and passes under it. The button that brings a folded timeline back
  // shares the layer, standing at the foot of the rail's column in the rail's
  // own chrome. The bottom padding clears the host's own bar, so the panel and
  // the button both stay above the card's composer.
  const hasPanel = useHasInspector();
  return (
    <aside
      style={{ paddingBottom: "calc(0.75rem + var(--host-inset-bottom, 0px))" }}
      className="pointer-events-none absolute inset-y-0 right-0 z-30 flex items-start gap-2 p-3"
    >
      {/* Keyed on what is selected: picking something else builds a fresh
          column, so it opens on that thing's own fields. */}
      {hasPanel ? (
        <InspectorColumn
          key={group ? group.map((g) => `${g.kind}:${g.id}`).join() : selection?.id ?? "none"}
          clip={group ? undefined : clip}
          audio={group ? undefined : audio}
          overlay={group ? undefined : overlay}
          cue={group ? undefined : cue}
          group={group ?? undefined}
        />
      ) : (
        <ShowTimelineButton />
      )}
    </aside>
  );
}

/**
 * Brings the timeline back while it is folded away. It carries the rail's card
 * and button shape and hangs at the bottom of the rail's column, so its icon
 * sits under the rail's own buttons.
 */
/** Rotation in the inspector keeps tenths of a degree: a screen in the shot can
 *  lean 0.4°, and a picture fitted onto it has to lean the same. */
const tenthDeg = (v: number) => Math.round(v * 10) / 10;
const formatDeg = (v: number) => `${tenthDeg(v)}°`;

function ShowTimelineButton() {
  const t = useTranslations("inspector.rail");
  const open = useEditor((s) => s.timelineOpen);
  if (open) return null;
  return (
    <div className="pointer-events-auto mt-auto shrink-0 self-end rounded-xl border bg-background p-1 shadow-md">
      <TooltipProvider>
        <Tooltip>
          <TooltipTrigger
            aria-label={t("showTimeline")}
            onClick={() => useEditor.getState().setTimelineOpen(true)}
            className="grid size-8 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground"
          >
            <PanelTopClose className="size-4" />
          </TooltipTrigger>
          <TooltipContent side="top">{t("showTimeline")}</TooltipContent>
        </Tooltip>
      </TooltipProvider>
    </div>
  );
}

/** A view the rail opens beside Home; it names itself under
 * `inspector.rail.tabs`. */
type RailTab = { id: RailTabId; Icon: LucideIcon };
type RailTabId = "color" | "cutout" | "frame" | "animate" | "audio";

/** The video clip's deep views, in rail order under Home. */
const CLIP_TABS: readonly RailTab[] = [
  { id: "color", Icon: Palette },
  { id: "cutout", Icon: Scissors },
  { id: "frame", Icon: Frame },
  { id: "animate", Icon: Sparkles },
  { id: "audio", Icon: Volume2 },
];

/** An overlay's one deep view: its animation. */
const ANIM_TAB: RailTab = { id: "animate", Icon: Sparkles };

/** The deep views a selection of video clips shares. */
const GROUP_CLIP_TABS: readonly RailTab[] = [
  { id: "color", Icon: Palette },
  ANIM_TAB,
];

/**
 * The panel for one selection: the tab rail on its left, the open view's
 * body beside it. The view belongs to the selection — the column is keyed on
 * what is selected — so anything newly picked opens on Home. Hiding the panel
 * keeps the rail and drops the body; it comes back only from the rail, so
 * selecting more of the timeline never reopens it.
 */
function InspectorColumn({
  clip,
  audio,
  overlay,
  cue,
  group,
}: {
  clip?: VideoClip;
  audio?: AudioClip;
  overlay?: Overlay;
  cue?: SubtitleCue;
  group?: NonNullable<Selection>[];
}) {
  const open = useEditor((s) => s.inspectorOpen);
  const setOpen = useEditor((s) => s.setInspectorOpen);
  // The open tab and the Home scroller's place hold per item for the
  // session, so coming back to an item lands on its panel as it was left.
  const itemId = clip?.id ?? audio?.id ?? overlay?.id ?? cue?.id ?? (group ? `group:${group.map((g) => g.id).join()}` : PANEL_GLOBAL);
  const [view, setView] = usePanelState<string>(itemId, "tab", "main");
  const homeScroll = useRememberedScroll(itemId, "main");
  const pick = useCallback(
    (id: string) => {
      setView(id);
      setOpen(true);
    },
    [setView, setOpen]
  );
  // A group's deep views are the ones every member has: clips share Color and
  // Animation, elements share Animation, and an effect (which animates
  // nothing) or a mix of kinds leaves the rail with Home alone.
  const allClips = useEditor((s) => s.clips);
  const allOverlays = useEditor((s) => s.overlays);
  const groupClips = useMemo(
    () => (group ? allClips.filter((c) => group.some((g) => g.kind === "clip" && g.id === c.id)) : []),
    [group, allClips]
  );
  const groupOverlays = useMemo(
    () => (group ? allOverlays.filter((o) => group.some((g) => g.kind === "overlay" && g.id === o.id)) : []),
    [group, allOverlays]
  );
  const groupTabs =
    group && groupClips.length === group.length
      ? GROUP_CLIP_TABS
      : group && groupOverlays.length === group.length && !groupOverlays.some(isEffectOverlay)
        ? [ANIM_TAB]
        : [];
  const tabs = clip ? CLIP_TABS : overlay ? [ANIM_TAB] : groupTabs;
  const shown = tabs.some((t) => t.id === view) ? view : "main";
  return (
    <>
      <div className="flex min-h-0 shrink-0 flex-col gap-2 self-stretch">
        <InspectorRail
          clipId={clip?.id}
          tabs={tabs}
          view={open ? shown : null}
          open={open}
          onPick={pick}
          onToggle={() => setOpen(!open)}
        />
        <ShowTimelineButton />
      </div>
      {open && (
        <div
          data-field-panel=""
          className="pointer-events-auto flex max-h-full w-[272px] shrink-0 flex-col overflow-hidden rounded-xl border border-border bg-card shadow-xl"
        >
          {clip ? (
            <ClipColumn clip={clip} tab={shown} />
          ) : overlay && shown === ANIM_TAB.id ? (
            <AnimationPanel overlay={overlay} />
          ) : group && shown === "color" && groupClips.length ? (
            <ColorPanel clip={groupClips[0]} peers={groupClips} />
          ) : group && shown === ANIM_TAB.id && groupClips.length ? (
            <ClipAnimationPanel clip={groupClips[0]} peers={groupClips} />
          ) : group && shown === ANIM_TAB.id && groupOverlays.length ? (
            <AnimationPanel overlay={groupOverlays[0]} peers={groupOverlays} />
          ) : (
            <ScrollArea className="min-h-0 flex-1" {...homeScroll}>
              {group ? (
                <GroupPanel selection={group} />
              ) : audio ? (
                <AudioPanel clip={audio} />
              ) : overlay ? (
                isTextOverlay(overlay) ? (
                  <TextPanel overlay={overlay} />
                ) : isShapeOverlay(overlay) ? (
                  <ShapePanel overlay={overlay} />
                ) : isEffectOverlay(overlay) ? (
                  <EffectPanel overlay={overlay} />
                ) : (
                  <StickerPanel overlay={overlay} />
                )
              ) : cue ? (
                <CuePanel cue={cue} />
              ) : null}
            </ScrollArea>
          )}
        </div>
      )}
    </>
  );
}

/**
 * The panel's tab rail: a floating pill at its top-left, Home over the selection's
 * deep views, then the button that hides or shows the body. Every button is
 * an icon with its name in the tooltip; the open view reads dark, and a
 * hidden panel lights none of them. With the body hidden the pill floats over
 * the preview's corner and holds no column, so selecting and deselecting
 * leave the preview where it is.
 */
function InspectorRail({
  clipId,
  tabs,
  view,
  open,
  onPick,
  onToggle,
}: {
  clipId?: string;
  tabs: readonly RailTab[];
  view: string | null;
  open: boolean;
  onPick: (id: string) => void;
  onToggle: () => void;
}) {
  // A running matte bake shows on the Cutout tab itself, so the work stays
  // visible from any view.
  const baking = useMatteBakes((s) => !!clipId && s.jobs[clipId]?.status === "running");
  const t = useTranslations("inspector.rail");
  return (
    <div className="pointer-events-auto flex min-h-0 flex-col items-center rounded-xl border bg-background p-1 shadow-md">
      <ScrollArea className="min-h-0 w-full" viewportClassName="overscroll-contain" contentClassName="flex flex-col items-center gap-1">
        <RailButton id="home" label={t("home")} Icon={House} active={view === "main"} onClick={() => onPick("main")} />
        {tabs.map(({ id, Icon }) => (
          <RailButton key={id} id={id} label={t(`tabs.${id}`)} Icon={Icon} active={view === id} onClick={() => onPick(id)}>
            {id === "cutout" && baking && (
              <Loader2 className="absolute top-1 right-1 size-2.5 animate-spin" />
            )}
          </RailButton>
        ))}
      </ScrollArea>
      <div className="my-1 h-px w-5 shrink-0 bg-border" />
      <RailButton
        id="toggle"
        label={open ? t("hidePanel") : t("showPanel")}
        Icon={open ? PanelRightClose : PanelRightOpen}
        active={false}
        onClick={onToggle}
      />
    </div>
  );
}

function RailButton({
  id,
  label,
  Icon,
  active,
  onClick,
  children,
}: {
  id: string;
  label: string;
  Icon: LucideIcon;
  active: boolean;
  onClick: () => void;
  children?: React.ReactNode;
}) {
  return (
    <Tip label={label} side="left">
      <button
        type="button"
        aria-label={label}
        aria-pressed={active}
        className={cn(
          `panel-tab-${id} relative grid size-8 shrink-0 place-items-center rounded-lg transition-colors`,
          active
            ? "bg-neutral-900 text-white"
            : "text-muted-foreground hover:bg-foreground/5 hover:text-foreground"
        )}
        onClick={onClick}
      >
        <Icon className="size-4" strokeWidth={active ? 2.25 : 2} />
        {children}
      </button>
    </Tip>
  );
}

/** A name that renames in place: a plain label until it is clicked, then an
 * input, the way the project title in the top bar renames. What the item is —
 * the file, the text, the shape — stands in until a name is given and again
 * when the name is cleared. Enter or leaving the field commits; Escape puts
 * back what was there. */
function InlineName({
  name,
  fallback,
  label,
  onRename,
}: {
  name?: string;
  fallback: string;
  label: string;
  onRename: (name: string | undefined) => void;
}) {
  const [draft, setDraft] = useState<string | null>(null);
  const commit = () => {
    if (draft === null) return;
    const next = draft.trim().slice(0, 60);
    setDraft(null);
    if ((next || undefined) !== (name || undefined)) onRename(next || undefined);
  };
  if (draft === null) {
    return (
      <button
        type="button"
        aria-label={label}
        className="-mx-2 min-w-0 max-w-full cursor-text truncate rounded-md px-2 py-1 text-left text-sm font-semibold tracking-tight hover:bg-muted"
        onClick={() => setDraft(name ?? "")}
      >
        {name?.trim() || fallback}
      </button>
    );
  }
  return (
    <input
      autoFocus
      aria-label={label}
      className="-mx-2 h-7 w-full min-w-0 rounded-md border border-input bg-transparent px-2 text-sm font-semibold tracking-tight outline-none select-text focus:border-ring"
      value={draft}
      placeholder={fallback}
      spellCheck={false}
      onChange={(e) => setDraft(e.target.value)}
      onBlur={commit}
      onKeyDown={(e) => {
        if (e.key === "Enter") e.currentTarget.blur();
        if (e.key === "Escape") setDraft(null);
      }}
    />
  );
}

/** An element panel's title: the element's name, renamed in place. The
 * timeline chip and chat references show the same name. */
function ElementTitle({ overlay: o }: { overlay: Overlay }) {
  const t = useTranslations("inspector.titles");
  const shapeLabel = useLabels("shape");
  const effectLabel = useLabels("effect");
  const update = useEditor((s) => s.updateOverlay);
  // What the element is, standing in for a name: a title's text, a shape's
  // kind, an effect's name, or "Sticker", in the page's language.
  const kindName = isTextOverlay(o)
    ? overlayName({ ...o, name: undefined } as Overlay)
    : isShapeOverlay(o)
      ? shapeLabel(o.shape)
      : isEffectOverlay(o)
        ? effectLabel(o.effect)
        : t("sticker");
  return (
    <div className="flex h-10 shrink-0 items-center px-3.5">
      <InlineName
        key={o.id}
        label={t("elementName")}
        name={o.name}
        fallback={kindName || t("text")}
        onRename={(name) => update(o.id, { name })}
      />
    </div>
  );
}

/** One-line header for a media clip's panel: the clip's name, renamed in
 * place (the file's name stands in until one is given, and again when it is
 * cleared), and the clip's running length. The timeline bar shows the same
 * name. */
function ClipHead({
  clip,
  fileName,
  time,
  onRename,
}: {
  clip: { id: string; name?: string };
  fileName?: string;
  time: string;
  onRename: (name: string | undefined) => void;
}) {
  const t = useTranslations("inspector.titles");
  return (
    <div className="mb-1.5 flex h-10 shrink-0 items-center justify-between gap-2 border-b border-border">
      <InlineName
        key={clip.id}
        label={t("clipName")}
        name={clip.name}
        fallback={fileName?.trim() || t("clip")}
        onRename={onRename}
      />
      <Value className="shrink-0 text-muted-foreground">{time}</Value>
    </div>
  );
}

/** Matches the store's MIN_LEN: the shortest a trim can leave a clip. */
const MIN_TRIM = 0.1;

const formatSpeed = (v: number) => `${v.toFixed(2)}×`;
const formatPercent = (v: number) => `${Math.round(v * 100)}%`;

/** One-click frame layouts (Full / Top / Bottom / Left / Right / PiP) shared by
 * the video-clip and overlay-clip panels. Picking one regions the clip so two
 * videos can share the frame; "Full" clears the region. */
/** The clip's box narrowed to the source's own shape: the picture area a fit
 * clip already draws inside `rect`, which is the box that shows the whole shot
 * with no margins around it. */
function sourceAspectRect(
  rect: FrameRect,
  srcW: number,
  srcH: number,
  frame: { w: number; h: number }
): FrameRect {
  const px = contentRect(
    { x: rect.x * frame.w, y: rect.y * frame.h, w: rect.w * frame.w, h: rect.h * frame.h },
    srcW,
    srcH,
    false
  );
  return { x: px.x / frame.w, y: px.y / frame.h, w: px.w / frame.w, h: px.h / frame.h };
}

function LayoutButtons({
  rect,
  onPick,
  onSourceAspect,
}: {
  rect: FrameRect;
  onPick: (frame: FrameRect | undefined, fit: "fit" | "fill") => void;
  /** Narrow the box to the source's own shape, dropping the margins. */
  onSourceAspect?: () => void;
}) {
  const t = useTranslations("inspector.layout");
  const currentId =
    (Object.keys(LAYOUTS) as LayoutId[]).find((id) => LAYOUTS[id].label === regionLabel(rect)) ??
    "full";
  return (
    <>
    <div className="flex items-center justify-between gap-2 py-1">
      <span className="text-[11.5px] font-medium text-muted-foreground">{t("title")}</span>
      <Select
        value={currentId}
        items={Object.fromEntries((Object.keys(LAYOUTS) as LayoutId[]).map((id) => [id, t(`layouts.${id}`)]))}
        onValueChange={(id) => {
          const L = LAYOUTS[id as LayoutId];
          onPick(id === "full" ? undefined : { ...L.rect }, L.fit);
        }}
      >
        <SelectTrigger className="h-8 w-36 text-[12px]">
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          {(Object.keys(LAYOUTS) as LayoutId[]).map((id) => (
            <SelectItem key={id} value={id} className="text-[12px]">
              {t(`layouts.${id}`)}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
    {onSourceAspect && (
      <Row label={t("shape")}>
        <button
          className="clip-source-aspect rounded-md border border-input px-2 py-0.5 text-[11.5px] text-muted-foreground transition-colors hover:text-foreground"
          onClick={onSourceAspect}
        >
          {t("matchSource")}
        </button>
      </Row>
    )}
    </>
  );
}

/**
 * The video clip's body: Home, or the rail's open view. Color and Cutout lay
 * out their own bands around their own scroller; the others ride this one.
 */
function ClipColumn({ clip, tab }: { clip: VideoClip; tab: string }) {
  // Keyed on the tab: each view keeps its own scroller and its own place.
  const scroll = useRememberedScroll(clip.id, tab);
  if (tab === "color") return <ColorPanel clip={clip} />;
  if (tab === "cutout") return <RemovalPanel clip={clip} />;
  if (tab === "animate") return <ClipAnimationPanel clip={clip} />;
  return (
    <ScrollArea key={tab} className="min-h-0 flex-1" {...scroll}>
      {tab === "frame" ? (
        <ClipFramePanel clip={clip} />
      ) : tab === "audio" ? (
        <ClipAudioPanel clip={clip} />
      ) : (
        <ClipPanel clip={clip} />
      )}
    </ScrollArea>
  );
}

/** Header for a view: its name, with a back chevron when the view sits
 * inside another one. The band the Color view opens with. */
function SubviewHead({ title, onBack }: { title: string; onBack?: () => void }) {
  const t = useTranslations("inspector.titles");
  return (
    <div
      className={cn(
        "flex h-10 shrink-0 items-center gap-1 text-sm font-semibold tracking-tight",
        onBack ? "px-2.5" : "px-3.5"
      )}
    >
      {onBack && (
        <button
          type="button"
          aria-label={t("back")}
          className="grid size-6 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground"
          onClick={onBack}
        >
          <ChevronLeft className="size-4" />
        </button>
      )}
      {title}
    </div>
  );
}

/** The Frame view: what the clip's box does — its pose keyframes, border,
 * shadow, and mask. */
function ClipFramePanel({ clip }: { clip: VideoClip }) {
  const t = useTranslations("inspector.rail");
  return (
    <>
      <SubviewHead title={t("tabs.frame")} />
      <div className="flex flex-col gap-1 px-3.5 pb-4">
        <ClipTransformSection clip={clip} />
        <CameraCardSection clip={clip} />
        {/* A camera card draws its own corners and shadow. */}
        {!clip.card && <ClipBorderSection clip={clip} />}
        {!clip.card && <ClipShadowSection clip={clip} />}
        <ClipMaskSection clip={clip} />
        <ClipEffectsSection clip={clip} />
      </div>
    </>
  );
}

/** The Audio view: the clip's own sound and the generated voice laid over it. */
function ClipAudioPanel({ clip }: { clip: VideoClip }) {
  const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));
  const updateClip = useEditor((s) => s.updateClip);
  const [volumeDraft, setVolumeDraft] = useState<number | null>(null);
  const volume = volumeDraft ?? clip.volume ?? 1;
  const ck = useSliderCheckpoint();
  const writeSound = (sound: ClipSound | undefined, phase: "draft" | "commit") => {
    ck.begin();
    useEditor.getState().updateClipTransient(clip.id, { sound });
    if (phase === "commit") ck.end();
  };
  const [view, setView] = usePanelState<"main" | "sound">(clip.id, "audioView", "main");
  const t = useTranslations("inspector.clipAudio");
  if (view === "sound") {
    return (
      <SoundQualityPanel itemId={clip.id} sound={clip.sound} write={writeSound} onBack={() => setView("main")} />
    );
  }
  return (
    <>
      <SubviewHead title={t("title")} />
      <div className="flex flex-col gap-1 px-3.5 pb-4">
        <Row label={t("volume")}>
          <ValueSlider
            label={t("volume")}
            sliderClassName="clip-volume data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={volume}
            min={0}
            max={3}
            step={0.05}
            snap={[1]}
            format={formatPercent}
            parse={parsePercentInput}
            onDraft={setVolumeDraft}
            onCommit={(v) => {
              updateClip(clip.id, { volume: v === 1 ? undefined : v });
              setVolumeDraft(null);
            }}
          />
        </Row>
        <Row label={t("mute")}>
          <Switch
            checked={clip.muted}
            onCheckedChange={(v) => updateClip(clip.id, { muted: v })}
          />
        </Row>
        {asset?.type === "video" && <ClipSoundSource clip={clip} asset={asset} />}
        {asset?.type === "video" && (!assetIsSilent(asset) || !!asset.soundFrom) && <ClipSplitEdit clip={clip} />}
        {asset && !assetIsSilent(asset) && (
          <Row label={t("beats")} info={t("beatsInfo")}>
            <BeatsControl asset={asset} />
          </Row>
        )}
        {asset && (!assetIsSilent(asset) || !!asset.soundFrom) && (
          <SoundQualityRow sound={clip.sound} onOpen={() => setView("sound")} />
        )}
        <ClipGeneratedAudio clip={clip} />
      </div>
    </>
  );
}

/** The Select value that stands for the video's own sound. */
const CAMERA_SOUND = "camera";

/**
 * Where a video's sound comes from: the camera's own track, or a recording
 * made apart from it. Picking a recording lines it up against the camera's
 * sound and binds it to the video, so every clip of the video plays it; a
 * recording with no clear match is refused and the reason shown.
 */
function ClipSoundSource({ clip, asset }: { clip: VideoClip; asset: MediaAsset }) {
  const t = useTranslations("inspector.clipAudio");
  const describeError = useDescribeError();
  const assets = useEditor((s) => s.assets);
  const recordings = useMemo(
    () => assets.filter((a) => a.type === "audio" && !a.upload && a.duration > 0),
    [assets]
  );
  const audioAssetId = asset.soundFrom?.assetId;
  const bound = audioAssetId ? recordings.find((a) => a.id === audioAssetId) : undefined;
  const [syncing, setSyncing] = useState(false);
  const [refusal, setRefusal] = useState<string | null>(null);
  const pick = (id: string) => {
    setRefusal(null);
    if (id === CAMERA_SOUND) {
      unbindRecording(asset.id);
      return;
    }
    setSyncing(true);
    void bindRecording(asset.id, id, clip)
      .catch((e: unknown) => setRefusal(describeError(e, t("syncFailed"))))
      .finally(() => setSyncing(false));
  };
  return (
    <>
      <Row label={t("sound")} info={t("soundInfo")}>
        {syncing && <Loader2 className="size-3.5 animate-spin text-muted-foreground" />}
        <Select value={bound ? bound.id : CAMERA_SOUND} onValueChange={(v) => pick(String(v))} disabled={syncing}>
          <SelectTrigger className="clip-sound-source h-8 w-36 text-[12px]">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value={CAMERA_SOUND} className="text-[12px]">
              {t("camera")}
            </SelectItem>
            {recordings.map((r) => (
              <SelectItem key={r.id} value={r.id} className="text-[12px]">
                {r.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <ResetButton title={t("useCameraSound")} show={!!bound} onClick={() => pick(CAMERA_SOUND)} />
      </Row>
      {bound && asset.soundFrom && (
        <p className="pb-1 text-[11.5px] text-muted-foreground">
          {t("synced", {
            offset: `${asset.soundFrom.offset >= 0 ? "+" : "−"}${Math.abs(asset.soundFrom.offset).toFixed(3)}`,
          })}
        </p>
      )}
      {refusal && <p className="pb-1 text-[11.5px] text-destructive">{refusal}</p>}
    </>
  );
}

/** A split edit's readout: its seconds, or the word for none. Typing that
 * word (or "off") clears it. */
const formatSplit = (v: number, off: string) => (v > 0 ? `${v.toFixed(2)} s` : off);
const parseSplitInput = (raw: string, off: string) =>
  /^off$/i.test(raw.trim()) || raw.trim().toLowerCase() === off.toLowerCase()
    ? 0
    : parseNumberInput(raw.replace(/\s*s$/i, ""));

/**
 * The clip's split edit: its sound running ahead of the picture (a J-cut)
 * or past it (an L-cut), played from the source beyond the trim. The picture
 * and the clip's place on the timeline stay put.
 */
function ClipSplitEdit({ clip }: { clip: VideoClip }) {
  const t = useTranslations("inspector.clipAudio");
  const off = t("off");
  const updateClip = useEditor((s) => s.updateClip);
  const [leadDraft, setLeadDraft] = useState<number | null>(null);
  const [tailDraft, setTailDraft] = useState<number | null>(null);
  const lead = leadDraft ?? clip.audioLead ?? 0;
  const tail = tailDraft ?? clip.audioTail ?? 0;
  const slider = (
    label: string,
    value: number,
    onDraft: (v: number | null) => void,
    write: (v: number) => Partial<VideoClip>
  ) => (
    <ValueSlider
      label={label}
      sliderClassName="clip-split-edit data-horizontal:w-24"
      valueClassName="w-11 text-muted-foreground"
      value={value}
      min={0}
      max={SPLIT_EDIT_MAX_S}
      step={0.05}
      format={(v) => formatSplit(v, off)}
      parse={(raw) => parseSplitInput(raw, off)}
      onDraft={onDraft}
      onCommit={(v) => {
        updateClip(clip.id, write(v));
        onDraft(null);
      }}
    />
  );
  return (
    <>
      <Row label={t("soundLead")} info={t("soundLeadInfo")}>
        {slider(t("soundLead"), lead, setLeadDraft, (v) => ({ audioLead: v > 0 ? v : undefined }))}
      </Row>
      <Row label={t("soundTail")} info={t("soundTailInfo")}>
        {slider(t("soundTail"), tail, setTailDraft, (v) => ({ audioTail: v > 0 ? v : undefined }))}
      </Row>
    </>
  );
}

const formatDb = (v: number) => `${v > 0 ? "+" : ""}${v.toFixed(1)} dB`;
const parseDbInput = (raw: string) =>
  parseNumberInput(raw.replace(/\s*dB$/i, "").replace(/^\+/, ""));

/** The equalizer's bands read as one ladder: each row keeps its slider and
 * readout but sits at two thirds of a panel row's height. */
const EQ_ROWS = "[&>div]:min-h-6";
/** The regions in band order, each named once. */
const EQ_GROUPS = [...new Set(SOUND_EQ_BANDS.map((b) => b.group))];

/** Whether two treatments are the same sound, neutral stages dropped. */
const sameSound = (a: ClipSound | undefined, b: ClipSound | undefined) =>
  JSON.stringify(normalizeSound(a) ?? null) ===
  JSON.stringify(normalizeSound(b) ?? null);

/**
 * The Sound quality sections on one clip's own sound: the presets, a
 * seven-band equalizer, a compressor and a limiter. `write` lands a
 * treatment on the clip — drafts stream through it while a slider moves and
 * the commit closes the drag's one undo step — and every write goes through
 * the kit's normalizer, so a section switched off or returned to flat stores
 * as absence.
 */
function SoundQualitySections({
  itemId,
  sound,
  write,
}: {
  itemId: string;
  sound: ClipSound | undefined;
  write: (sound: ClipSound | undefined, phase: "draft" | "commit") => void;
}) {
  const t = useTranslations("inspector.sound");
  const set = (next: ClipSound | undefined, phase: "draft" | "commit") =>
    write(normalizeSound(next), phase);
  const eq = SOUND_EQ_BANDS.map((_, i) => sound?.eq?.[i] ?? 0);
  const setBand = (i: number, v: number, phase: "draft" | "commit") => {
    const next = [...eq];
    next[i] = v;
    set({ ...sound, eq: next }, phase);
  };
  const comp = sound?.compressor;
  const setComp = (
    patch: Partial<NonNullable<ClipSound["compressor"]>>,
    phase: "draft" | "commit",
  ) =>
    set(
      {
        ...sound,
        compressor: { ...(comp ?? SOUND_COMPRESSOR_DEFAULT), ...patch },
      },
      phase,
    );
  const cr = SOUND_COMPRESSOR_RANGE;
  const dbRow = (
    label: string,
    value: number,
    range: { min: number; max: number },
    onDraft: (v: number) => void,
    onCommit: (v: number) => void,
    format: (v: number) => string = formatDb,
    parse: (raw: string) => number | null = parseDbInput,
    step = 0.5,
    snap?: number[],
  ) => (
    <Row key={label} label={label}>
      <ValueSlider
        label={label}
        sliderClassName="data-horizontal:w-24"
        valueClassName="w-14 text-muted-foreground"
        value={value}
        min={range.min}
        max={range.max}
        step={step}
        snap={snap}
        format={format}
        parse={parse}
        onDraft={onDraft}
        onCommit={onCommit}
      />
    </Row>
  );
  return (
    <>
      <SoundPresetsRow itemId={itemId} sound={sound} onApply={(s) => set(s, "commit")} />
      <Section
        title={t("equalizer")}
        aside={
          <ResetButton
            title={t("flattenEqualizer")}
            show={!!sound?.eq}
            onClick={() => set({ ...sound, eq: undefined }, "commit")}
          />
        }
      >
        {/* The bands as four short ladders, one per region of the spectrum:
            the region's name over its rows, the rows close together, and a
            breath between one region and the next. */}
        <div className="flex flex-col gap-3 pt-0.5 pb-1">
          {EQ_GROUPS.map((group) => (
            <div key={group}>
              <div className="mb-0.5 text-[9.5px] leading-none tracking-wider text-muted-foreground/50 uppercase">
                {t(`eqGroups.${group}`)}
              </div>
              <div className={EQ_ROWS}>
                {SOUND_EQ_BANDS.map((b, i) =>
                  b.group === group
                    ? dbRow(
                        b.label,
                        eq[i],
                        { min: -SOUND_EQ_DB_RANGE, max: SOUND_EQ_DB_RANGE },
                        (v) => setBand(i, v, "draft"),
                        (v) => setBand(i, v, "commit"),
                        formatDb,
                        parseDbInput,
                        0.5,
                        [0],
                      )
                    : null,
                )}
              </div>
            </div>
          ))}
        </div>
      </Section>
      <Section
        title={t("compressor")}
        enabled={!!comp}
        onEnabledChange={(on) =>
          set(
            {
              ...sound,
              compressor: on ? SOUND_COMPRESSOR_DEFAULT : undefined,
            },
            "commit",
          )
        }
      >
        {comp && (
          <>
            {dbRow(
              t("threshold"),
              comp.threshold,
              cr.threshold,
              (v) => setComp({ threshold: v }, "draft"),
              (v) => setComp({ threshold: v }, "commit"),
            )}
            {dbRow(
              t("ratio"),
              comp.ratio,
              cr.ratio,
              (v) => setComp({ ratio: v }, "draft"),
              (v) => setComp({ ratio: v }, "commit"),
              (v) => `${v.toFixed(1)}:1`,
              (raw) => parseNumberInput(raw.replace(/\s*:\s*1$/, "")),
              0.1,
            )}
            {dbRow(
              t("attack"),
              comp.attack,
              cr.attack,
              (v) => setComp({ attack: v }, "draft"),
              (v) => setComp({ attack: v }, "commit"),
              (v) => `${v < 1 ? v.toFixed(1) : Math.round(v)} ms`,
              (raw) => parseNumberInput(raw.replace(/\s*ms$/i, "")),
              0.5,
            )}
            {dbRow(
              t("release"),
              comp.release,
              cr.release,
              (v) => setComp({ release: v }, "draft"),
              (v) => setComp({ release: v }, "commit"),
              (v) => `${Math.round(v)} ms`,
              (raw) => parseNumberInput(raw.replace(/\s*ms$/i, "")),
              5,
            )}
          </>
        )}
      </Section>
      <Section
        title={t("limiter")}
        enabled={!!sound?.limiter}
        onEnabledChange={(on) =>
          set(
            { ...sound, limiter: on ? SOUND_LIMITER_DEFAULT : undefined },
            "commit",
          )
        }
      >
        {sound?.limiter &&
          dbRow(
            t("ceiling"),
            sound.limiter.ceiling,
            SOUND_LIMITER_RANGE.ceiling,
            (v) => set({ ...sound, limiter: { ceiling: v } }, "draft"),
            (v) => set({ ...sound, limiter: { ceiling: v } }, "commit"),
          )}
      </Section>
    </>
  );
}

type SoundT = ReturnType<typeof useTranslations<"inspector.sound">>;
type SoundPresetId = keyof Messages["inspector"]["sound"]["presets"];

/** A shipped sound preset's name in the page's language. */
const soundPresetName = (t: SoundT, id: string) => t(`presets.${id as SoundPresetId}`);

/** What a clip's treatment reads as on the row that opens it. */
const soundSummary = (t: SoundT, sound: ClipSound | undefined) => {
  const s = normalizeSound(sound);
  if (!s) return t("off");
  const preset = SOUND_PRESETS.find((p) => p.sound && sameSound(p.sound, s));
  return preset ? soundPresetName(t, preset.id) : t("on");
};

/** The row on an audio panel that opens the Sound quality view, reading
 * what the clip carries. */
export function SoundQualityRow({ sound, onOpen }: { sound: ClipSound | undefined; onOpen: () => void }) {
  const t = useTranslations("inspector.sound");
  return (
    <Row label={t("title")}>
      <button
        type="button"
        className="sound-quality-open flex h-8 items-center gap-1 rounded-md border border-input px-2.5 text-[11.5px] font-medium text-muted-foreground transition-colors hover:text-foreground"
        onClick={onOpen}
      >
        {soundSummary(t, sound)}
        <ChevronRight className="size-3.5 shrink-0" />
      </button>
    </Row>
  );
}

/** The Sound quality view, pushed over an audio panel. */
export function SoundQualityPanel({
  itemId,
  sound,
  write,
  onBack,
}: {
  itemId: string;
  sound: ClipSound | undefined;
  write: (sound: ClipSound | undefined, phase: "draft" | "commit") => void;
  onBack: () => void;
}) {
  const t = useTranslations("inspector.sound");
  return (
    <>
      <SubviewHead title={t("title")} onBack={onBack} />
      <div className="flex flex-col gap-1 px-3.5 pb-4">
        <SoundQualitySections itemId={itemId} sound={sound} write={write} />
      </div>
    </>
  );
}

/** The presets as one dropdown — the shipped voice treatment and the user's
 * saved ones, with "Custom" standing in when the clip's treatment matches
 * none of them — plus saving the current treatment under a name and
 * deleting the saved one that is selected. */
function SoundPresetsRow({
  itemId,
  sound,
  onApply,
}: {
  itemId: string;
  sound: ClipSound | undefined;
  onApply: (sound: ClipSound | undefined) => void;
}) {
  const t = useTranslations("inspector.sound");
  const [naming, setNaming] = useState(false);
  const [name, setName] = useState("");
  const [busy, setBusy] = useState(false);
  // The shelf everything else reads: the library query is cached across the
  // session, so opening this view costs no listing and the dropdown is
  // filled the moment it draws.
  const client = useQueryClient();
  const library = useLibrary();
  const saved = useMemo(
    () =>
      (library.data?.templates ?? [])
        .map(soundPresetOf)
        .filter((p): p is SoundPreset => p !== null),
    [library.data]
  );

  const save = async () => {
    const projectId = useEditor.getState().projectId;
    const trimmed = name.trim();
    if (!projectId || !trimmed || busy || !sound) return;
    setBusy(true);
    try {
      const p = await saveSoundPreset(projectId, trimmed, sound);
      if (p) {
        setPicked(`${p.residency}:${p.id}`);
        await refetchLibrary(client);
      }
      setNaming(false);
      setName("");
    } catch {
      // Signed out or offline shelf — the list just doesn't gain one.
    } finally {
      setBusy(false);
    }
  };

  const options: {
    key: string;
    label: string;
    sound: ClipSound | undefined;
    saved?: SoundPreset;
  }[] = [
    // Flat is the shipped "nothing applied" treatment; it reads as Off.
    ...SOUND_PRESETS.map((p) => ({
      key: `shipped:${p.id}`,
      label: p.sound ? soundPresetName(t, p.id) : t("off"),
      sound: p.sound,
    })),
    ...saved.map((p) => ({
      key: `${p.residency}:${p.id}`,
      label: p.name,
      sound: p.sound,
      saved: p,
    })),
  ];
  // Two presets can hold the same settings — one saved while another was
  // applied — so the one the user picked stays selected for as long as the
  // clip still matches it; the first match stands in otherwise.
  const [picked, setPicked] = usePanelState<string | null>(itemId, "soundPreset", null);
  const current =
    options.find((o) => o.key === picked && sameSound(o.sound, sound)) ??
    options.find((o) => sameSound(o.sound, sound));
  const CUSTOM = "custom";
  const value = current?.key ?? CUSTOM;
  const items = Object.fromEntries([
    ...options.map((o) => [o.key, o.label]),
    [CUSTOM, t("custom")],
  ]);

  return (
    <>
      <Row label={t("preset")}>
        <Select
          value={value}
          items={items}
          onValueChange={(key) => {
            const o = options.find((x) => x.key === key);
            if (!o) return;
            setPicked(o.key);
            onApply(o.sound);
          }}
        >
          <SelectTrigger className="h-8 w-36 text-[12px]">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {options.map((o) => (
              <SelectItem key={o.key} value={o.key} className="text-[12px]">
                {o.label}
              </SelectItem>
            ))}
            <SelectItem
              value={CUSTOM}
              className="text-[12px]"
              disabled={value !== CUSTOM}
            >
              {t("custom")}
            </SelectItem>
          </SelectContent>
        </Select>
        {current?.saved ? (
          <button
            type="button"
            title={t("deleteNamed", { name: current.label })}
            aria-label={t("deletePresetNamed", { name: current.label })}
            className="grid size-5 shrink-0 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground"
            onClick={() => {
              const p = current.saved!;
              void deleteSoundPreset(p).catch(() => {});
              patchLibrary(client, (prev) => ({
                ...prev,
                templates: prev.templates.filter(
                  (item) => !(item.id === p.id && item.residency === p.residency)
                ),
              }));
            }}
          >
            <Trash2 className="size-3" />
          </button>
        ) : (
          <button
            type="button"
            title={t("savePreset")}
            className="shrink-0 text-[11.5px] text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40"
            disabled={!sound}
            onClick={() => setNaming(true)}
          >
            {t("save")}
          </button>
        )}
      </Row>
      <Dialog open={naming} onOpenChange={(o) => !o && setNaming(false)}>
        <DialogContent className="sm:max-w-sm">
          <DialogHeader>
            <DialogTitle>{t("saveDialogTitle")}</DialogTitle>
          </DialogHeader>
          <form
            onSubmit={(e) => {
              e.preventDefault();
              void save();
            }}
          >
            <Input
              autoFocus
              placeholder={t("presetName")}
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
            <DialogFooter className="mt-4">
              <Button type="submit" disabled={busy || !name.trim()} className="w-full">
                {busy && <Loader2 className="animate-spin" data-icon="inline-start" />}
                {t("savePreset")}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </>
  );
}
function ClipPanel({ clip }: { clip: VideoClip }) {
  const t = useTranslations("inspector.clip");
  const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));
  const aspect = useEditor((s) => s.aspect);
  const updateClip = useEditor((s) => s.updateClip);
  const zoomCk = useSliderCheckpoint();
  const panCk = useSliderCheckpoint();
  const turnCk = useSliderCheckpoint();
  const fadeCk = useSliderCheckpoint();
  const [speedDraft, setSpeedDraft] = useState<number | null>(null);
  const curved = hasSpeedCurve(clip);
  const speed = speedDraft ?? (curved ? retimeOf(clip).rate : (clip.speed ?? 1));
  const speedLen =
    curved && speedDraft === null ? retimeOf(clip).len : (clip.out - clip.in) / (speed > 0 ? speed : 1);
  const [curveOpen, setCurveOpen] = usePanelState(clip.id, "speedCurve", false);
  // Typing can trim out to the source's end but no further; an image has no
  // intrinsic duration, so its clip can be any length.
  const maxOut = asset && asset.type !== "image" ? asset.duration : Infinity;
  // The Shape row shows only while snugging the box to the footage's shape
  // would move it, so the button always visibly does something.
  const rect = rectOf(clip);
  const snug =
    asset?.width && asset?.height
      ? sourceAspectRect(rect, asset.width, asset.height, frameOf(aspect))
      : null;
  const snugMoves =
    !!snug && (["x", "y", "w", "h"] as const).some((k) => Math.abs(snug[k] - rect[k]) > 1e-3);
  // Which axes the crop window can travel on: the picture hangs past the box
  // there, so pan has somewhere to go. Measured in frame pixels, the same
  // geometry the preview's grey outline draws.
  const frPx = frameOf(aspect);
  const boxPx = { x: rect.x * frPx.w, y: rect.y * frPx.h, w: rect.w * frPx.w, h: rect.h * frPx.h };
  const picPx =
    asset?.width && asset?.height
      ? contentRect(
          boxPx,
          asset.width,
          asset.height,
          clipCovers(clip),
          clipZoom(clip),
          clip.panX ?? 0,
          clip.panY ?? 0
        )
      : boxPx;
  const panXFree = picPx.w - boxPx.w > 1;
  const panYFree = picPx.h - boxPx.h > 1;
  return (
    <>
      <div className="flex flex-col gap-1 px-3.5 pb-4">
        <ClipHead
          clip={clip}
          fileName={asset?.name}
          time={formatTime(speedLen)}
          onRename={(name) => updateClip(clip.id, { name })}
        />
        {asset?.block && (
          // A blocked-out shot's whole picture is its colour, so that is the
          // one thing there is to set on it by hand.
          <Row label={t("color")}>
            <ColorField
              value={asset.block.color || BLOCK_COLOR}
              label={t("blockColor")}
              onBegin={() => useEditor.getState().pushHistory()}
              onLive={(c) =>
                useEditor.getState().updateAsset(asset.id, { block: { ...asset.block!, color: c } })
              }
              onCommit={(c) =>
                useEditor.getState().updateAsset(asset.id, { block: { ...asset.block!, color: c } })
              }
            />
          </Row>
        )}
        <Row label={t("trim")}>
          <ScrubValue
            label={t("trimStart")}
            value={clip.in}
            min={0}
            max={clip.out - MIN_TRIM}
            step={0.1}
            keyStep={1}
            format={formatTime}
            parse={parseTimeInput}
            onCommit={(v) => useEditor.getState().setClipTrim(clip.id, v, clip.out)}
          />
          <Value className="text-muted-foreground">–</Value>
          <ScrubValue
            label={t("trimEnd")}
            value={clip.out}
            min={clip.in + MIN_TRIM}
            max={maxOut}
            step={0.1}
            keyStep={1}
            format={formatTime}
            parse={parseTimeInput}
            onCommit={(v) => useEditor.getState().setClipTrim(clip.id, clip.in, v)}
          />
          <ResetButton
            title={t("resetTrim")}
            show={Number.isFinite(maxOut) && (clip.in > 1e-3 || clip.out < maxOut - 1e-3)}
            onClick={() => useEditor.getState().setClipTrim(clip.id, 0, maxOut)}
          />
        </Row>
        <Row label={t("startsAt")}>
          <ScrubValue
            label={t("startsAt")}
            value={clip.start}
            min={0}
            max={Infinity}
            step={0.1}
            keyStep={1}
            format={formatTime}
            parse={parseTimeInput}
            onCommit={(v) => {
              updateClip(clip.id, { start: Math.max(0, v) });
              useEditor.getState().sortClips();
            }}
          />
        </Row>
        <Row label={t("speed")}>
          <ValueSlider
            label={t("speed")}
            sliderClassName="clip-speed data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={speed}
            min={SPEED_MIN}
            max={SPEED_MAX}
            step={0.05}
            snap={[1]}
            scrubMin={SPEED_FLOOR}
            scrubMax={Infinity}
            format={formatSpeed}
            parse={parseSpeedInput}
            onDraft={setSpeedDraft}
            onCommit={(v) => {
              useEditor.getState().setClipSpeed(clip.id, v);
              setSpeedDraft(null);
            }}
          />
          <ResetButton
            title={t("resetSpeed")}
            show={curved || Math.abs(speed - 1) > 1e-4}
            onClick={() => {
              useEditor.getState().setClipSpeed(clip.id, 1);
              setSpeedDraft(null);
            }}
          />
        </Row>
        <Row label={t("speedCurve")}>
          <Button
            variant={curveOpen ? "secondary" : "outline"}
            size="sm"
            className="h-6 px-2 text-[11px]"
            title={t("speedCurveHint")}
            onClick={() => {
              if (curveOpen) {
                setCurveOpen(false);
                return;
              }
              if (!curved) {
                useEditor.getState().setClipSpeedCurve(clip.id, flatSpeedCurve(clip));
              }
              setCurveOpen(true);
            }}
          >
            {curveOpen ? t("curveEditing") : curved ? t("curveEdit") : t("curveAdd")}
          </Button>
          {curved && (
            <span className="text-[11px] tabular-nums text-muted-foreground">
              {t("nodes", { count: clip.speedCurve!.length })}
            </span>
          )}
        </Row>
        <Row label={t("reverse")}>
          <Switch
            checked={!!clip.reverse}
            onCheckedChange={(v) => useEditor.getState().setClipReverse(clip.id, v)}
          />
        </Row>

        {/* Picture */}
        <div className="my-1.5 h-px bg-border" />
        <Row label={t("hidden")}>
          <Switch
            checked={!!clip.hidden}
            onCheckedChange={(v) => updateClip(clip.id, { hidden: v })}
          />
        </Row>
        {/* A camera card places the footage itself (Frame view). */}
        {!clip.card && (<>
        <Row label={t("framing")}>
          <div className="clip-framing flex rounded-lg border border-input p-0.5">
            {(["fit", "fill"] as const).map((mode) => (
              <button
                key={mode}
                className={cn(
                  "rounded-md px-2.5 py-1 text-[11.5px] font-medium transition-colors",
                  (clip.fit ?? "fit") === mode
                    ? "bg-neutral-900 text-white"
                    : "text-muted-foreground hover:text-foreground"
                )}
                aria-pressed={(clip.fit ?? "fit") === mode}
                onClick={() => updateClip(clip.id, { fit: mode, panX: 0, panY: 0 })}
              >
                {mode === "fit" ? t("fit") : t("fill")}
              </button>
            ))}
          </div>
        </Row>
        <Row label={t("zoom")}>
          <ValueSlider
            label={t("zoom")}
            sliderClassName="clip-zoom data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={clipZoom(clip)}
            min={1}
            max={CLIP_MAX_ZOOM}
            step={0.01}
            snap={[1]}
            keyStep={0.05}
            format={formatPercent}
            parse={parsePercentInput}
            onDraft={(v) => {
              zoomCk.begin();
              useEditor.getState().updateClipTransient(clip.id, {
                zoom: v > 1.001 ? v : undefined,
              });
            }}
            onCommit={(v) => {
              zoomCk.begin();
              updateClip(clip.id, { zoom: v > 1.001 ? v : undefined });
              zoomCk.end();
            }}
          />
          <ResetButton
            title={t("resetZoom")}
            show={clipZoom(clip) > 1}
            onClick={() => updateClip(clip.id, { zoom: undefined, panX: 0, panY: 0 })}
          />
        </Row>
        {(["panX", "panY"] as const).map((axis) => {
          const free = axis === "panX" ? panXFree : panYFree;
          const value = clip[axis] ?? 0;
          if (!free && value === 0) return null;
          return (
            <Row key={axis} label={axis === "panX" ? t("panX") : t("panY")}>
              <ValueSlider
                label={axis === "panX" ? t("panX") : t("panY")}
                sliderClassName="clip-pan data-horizontal:w-24"
                valueClassName="w-9 text-muted-foreground"
                value={value}
                min={-1}
                max={1}
                step={0.01}
                snap={[0]}
                keyStep={0.05}
                format={formatPercent}
                parse={parsePercentInput}
                onDraft={(v) => {
                  panCk.begin();
                  useEditor.getState().updateClipTransient(clip.id, { [axis]: v });
                }}
                onCommit={(v) => {
                  panCk.begin();
                  updateClip(clip.id, { [axis]: v });
                  panCk.end();
                }}
              />
              <ResetButton
                title={t("center")}
                show={value !== 0}
                onClick={() => updateClip(clip.id, { [axis]: 0 })}
              />
            </Row>
          );
        })}
        </>)}
        <Row label={t("rotation")}>
          <ValueSlider
            label={t("rotation")}
            sliderClassName="clip-rotation data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={clip.rotation ?? 0}
            min={-180}
            max={180}
            step={0.1}
            keyStep={1}
            snap={[-90, 0, 90]}
            format={formatDeg}
            parse={parseNumberInput}
            onDraft={(v) => {
              turnCk.begin();
              useEditor.getState().updateClipTransient(clip.id, {
                rotation: tenthDeg(v) || undefined,
              });
            }}
            onCommit={(v) => {
              turnCk.begin();
              updateClip(clip.id, { rotation: tenthDeg(v) || undefined });
              turnCk.end();
            }}
          />
          <ResetButton
            title={t("resetRotation")}
            show={!!clip.rotation}
            onClick={() => updateClip(clip.id, { rotation: undefined })}
          />
        </Row>
        <Row label={t("flip")}>
          <div className="clip-flip flex rounded-lg border border-input p-0.5">
            {(
              [
                ["flipH", t("flipHorizontal"), FlipHorizontal2],
                ["flipV", t("flipVertical"), FlipVertical2],
              ] as const
            ).map(([key, label, Icon]) => (
              <TooltipProvider key={key}>
                <Tooltip>
                  <TooltipTrigger
                    aria-label={label}
                    aria-pressed={!!clip[key]}
                    className={cn(
                      "grid size-6 place-items-center rounded-md transition-colors",
                      clip[key]
                        ? "bg-neutral-900 text-white"
                        : "text-muted-foreground hover:text-foreground"
                    )}
                    onClick={() => updateClip(clip.id, { [key]: clip[key] ? undefined : true })}
                  >
                    <Icon className="size-3.5" />
                  </TooltipTrigger>
                  <TooltipContent side="bottom">{label}</TooltipContent>
                </Tooltip>
              </TooltipProvider>
            ))}
          </div>
        </Row>
        <Row label={t("opacity")}>
          <ValueSlider
            label={t("opacity")}
            sliderClassName="clip-opacity data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={clip.opacity ?? 1}
            min={0}
            max={1}
            step={0.01}
            snap={[1]}
            format={formatPercent}
            parse={parsePercentInput}
            onDraft={(v) => {
              fadeCk.begin();
              useEditor.getState().updateClipTransient(clip.id, {
                opacity: v >= 0.999 ? undefined : v,
              });
            }}
            onCommit={(v) => {
              fadeCk.begin();
              updateClip(clip.id, { opacity: v >= 0.999 ? undefined : v });
              fadeCk.end();
            }}
          />
          <ResetButton
            title={t("resetOpacity")}
            show={(clip.opacity ?? 1) < 1}
            onClick={() => updateClip(clip.id, { opacity: undefined })}
          />
        </Row>
        <LayoutButtons
          rect={rect}
          onPick={(frame, fit) => updateClip(clip.id, { frame, fit })}
          onSourceAspect={
            snug && snugMoves
              ? () =>
                  updateClip(clip.id, {
                    frame: snug,
                    fit: "fit",
                    zoom: undefined,
                    panX: 0,
                    panY: 0,
                  })
              : undefined
          }
        />
      </div>
    </>
  );
}

/** Per-clip generated-audio block: the voice picker, "Generate audio for clip"
 * (which transcribes just this clip when it has no cues yet), and one volume
 * slider driving the voiceovers laid over the clip. Shared by every clip
 * panel on any track. */
function ClipGeneratedAudio({ clip }: { clip: VideoClip }) {
  // Subtitle cues overlapping this clip's timeline span, for the per-clip
  // readout. A selector rather than a snapshot so the generate button reads
  // fresh ids after it auto-transcribes the cut.
  const selectClipCueIds = useCallback(
    (s: EditorState) => {
      const sp = clipWindow(s.clips, s.assets, clip.id);
      if (!sp) return [];
      return s.subtitles.cues
        .filter((c) => c.text.trim() && c.end > sp.start && c.start < sp.start + sp.len)
        .map((c) => c.id);
    },
    [clip.id]
  );
  const ensureClipCues = useCallback(
    () => useEditor.getState().generateClipSubtitles(clip.id),
    [clip.id]
  );
  // Generated voiceover clips overlapping this clip's span — the "Generated
  // audio" slider drives them all, so clip sound and voiceover balance from one
  // panel. Same joined-string trick as the cue ids for reference stability.
  const [genVolDraft, setGenVolDraft] = useState<number | null>(null);
  const genCk = useSliderCheckpoint();
  const genAudioKey = useEditor((s) => {
    const sp = clipWindow(s.clips, s.assets, clip.id);
    if (!sp) return "";
    // AI-voice audio regardless of where it was made: the Audio panel tags
    // voiceovers, the chat tags its own — both are voice over this clip.
    const voiceAssets = new Set(
      s.assets
        .filter((a) => a.origin === "voiceover" || (a.origin === "chat" && a.type === "audio"))
        .map((a) => a.id)
    );
    return s.audioClips
      .filter((a) => {
        const len = retimeOf(a).len;
        return (
          voiceAssets.has(a.assetId) && a.start < sp.start + sp.len && a.start + len > sp.start
        );
      })
      .map((a) => a.id)
      .join("\n");
  });
  const genAudioIds = useMemo(() => (genAudioKey ? genAudioKey.split("\n") : []), [genAudioKey]);
  const genVolStore = useEditor((s) => {
    const first = s.audioClips.find((a) => a.id === genAudioIds[0]);
    return first ? first.volume : 1;
  });
  const genVol = genVolDraft ?? genVolStore;
  const t = useTranslations("inspector.clipAudio");
  return (
    <div className="mt-2 flex flex-col gap-1 border-t border-border pt-3">
      <GenerateSubtitlesAudio
        selectCueIds={selectClipCueIds}
        ensureCues={ensureClipCues}
        label={t("generateForClip")}
      />
      {genAudioIds.length > 0 && (
        <Row label={t("volume")}>
          <ValueSlider
            label={t("generatedVolume")}
            sliderClassName="clip-gen-volume data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={genVol}
            min={0}
            max={3}
            step={0.05}
            snap={[1]}
            format={formatPercent}
            parse={parsePercentInput}
            onDraft={(v) => {
              genCk.begin();
              setGenVolDraft(v);
              const s = useEditor.getState();
              genAudioIds.forEach((id) => s.updateAudioTransient(id, { volume: v }));
            }}
            onCommit={(v) => {
              genCk.begin();
              const s = useEditor.getState();
              genAudioIds.forEach((id) => s.updateAudioTransient(id, { volume: v }));
              genCk.end();
              setGenVolDraft(null);
            }}
          />
        </Row>
      )}
    </div>
  );
}

/** The Beats row's control: detect (or re-run) the asset's beat grid, and
 * clear it. The dots themselves live on the clip bars — dragged, added
 * (⌥-click), and removed (double-click) there. */
function BeatsControl({ asset }: { asset: MediaAsset }) {
  const t = useTranslations("inspector.beats");
  const busy = useSyncExternalStore(subscribeBeatsBusy, () => beatsBusyFor(asset.id), () => false);
  const grid = asset.beats;
  return (
    <>
      {grid && (
        <Value className="whitespace-nowrap text-muted-foreground">
          {grid.bpm > 0
            ? t("countBpm", { count: grid.beats.length, bpm: Math.round(grid.bpm) })
            : t("count", { count: grid.beats.length })}
        </Value>
      )}
      <Button
        size="sm"
        variant="outline"
        disabled={busy || !!asset.upload}
        onClick={() => {
          void detectAssetBeats(asset).catch((err) => {
            reportSwallowed("[cut] beat scan failed", err, asset.fileName);
          });
        }}
      >
        {busy && <Loader2 className="size-3.5 animate-spin" />}
        {t("detect")}
      </Button>
      {grid && (
        <ResetButton
          title={t("clear")}
          show
          onClick={() => {
            useEditor.getState().pushHistory();
            useEditor.getState().updateAsset(asset.id, { beats: undefined });
          }}
        />
      )}
    </>
  );
}

function AudioPanel({ clip }: { clip: AudioClip }) {
  const t = useTranslations("inspector.clip");
  const ta = useTranslations("inspector.clipAudio");
  const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));
  const updateAudioTransient = useEditor((s) => s.updateAudioTransient);
  const ck = useSliderCheckpoint();
  const setAudio = (patch: Partial<AudioClip>) => {
    ck.begin();
    updateAudioTransient(clip.id, patch);
  };
  // Detached audio carries the picture's rate, so its length goes through it;
  // the slider shows one number — the average under a curve — and setting it
  // makes the rate uniform.
  const len = retimeOf(clip).len;
  const speed = retimeOf(clip).rate;
  const maxFade = maxClipFade(clip);
  // Commit closes the checkpoint setAudio opened (or opens+closes one for a
  // typed entry), so any adjustment lands as a single undo step.
  const commitAudio = (patch: Partial<AudioClip>) => {
    setAudio(patch);
    ck.end();
  };
  const [view, setView] = usePanelState<"main" | "sound">(clip.id, "soundView", "main");
  if (view === "sound") {
    return (
      <SoundQualityPanel
        itemId={clip.id}
        sound={clip.sound}
        write={(sound, phase) => (phase === "commit" ? commitAudio({ sound }) : setAudio({ sound }))}
        onBack={() => setView("main")}
      />
    );
  }
  return (
    <>
      <div className="flex flex-col gap-1 px-3.5 pb-4">
        <ClipHead
          clip={clip}
          fileName={asset?.name}
          time={formatTime(len)}
          onRename={(name) => useEditor.getState().updateAudio(clip.id, { name })}
        />
        <Row label={t("trim")}>
          <ScrubValue
            label={t("trimStart")}
            value={clip.in}
            min={0}
            max={clip.out - MIN_TRIM}
            step={0.1}
            keyStep={1}
            format={formatTime}
            parse={parseTimeInput}
            onCommit={(v) => commitAudio({ in: v })}
          />
          <Value className="text-muted-foreground">–</Value>
          <ScrubValue
            label={t("trimEnd")}
            value={clip.out}
            min={clip.in + MIN_TRIM}
            max={asset?.duration ?? clip.out}
            step={0.1}
            keyStep={1}
            format={formatTime}
            parse={parseTimeInput}
            onCommit={(v) => commitAudio({ out: v })}
          />
          <ResetButton
            title={t("resetTrim")}
            show={!!asset && (clip.in > 1e-3 || clip.out < asset.duration - 1e-3)}
            onClick={() => asset && commitAudio({ in: 0, out: asset.duration })}
          />
        </Row>
        <Row label={t("startsAt")}>
          <ScrubValue
            label={t("startsAt")}
            value={clip.start}
            min={0}
            max={Infinity}
            step={0.1}
            keyStep={1}
            format={formatTime}
            parse={parseTimeInput}
            onCommit={(v) => commitAudio({ start: v })}
          />
        </Row>
        <Row label={t("speed")}>
          <ValueSlider
            label={t("speed")}
            sliderClassName="audio-speed data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={speed}
            min={SPEED_MIN}
            max={SPEED_MAX}
            step={0.05}
            snap={[1]}
            scrubMin={SPEED_FLOOR}
            scrubMax={Infinity}
            format={formatSpeed}
            parse={parseSpeedInput}
            onDraft={(v) => setAudio({ speed: Math.abs(v - 1) < 1e-4 ? undefined : v, speedCurve: undefined })}
            onCommit={(v) => commitAudio({ speed: Math.abs(v - 1) < 1e-4 ? undefined : v, speedCurve: undefined })}
          />
          <ResetButton
            title={t("resetSpeed")}
            show={Math.abs(speed - 1) > 1e-4 || !!clip.speedCurve}
            onClick={() => commitAudio({ speed: undefined, speedCurve: undefined })}
          />
        </Row>
        <Row label={t("reverse")}>
          <Switch
            checked={!!clip.reverse}
            onCheckedChange={(v) => commitAudio({ reverse: v || undefined })}
          />
        </Row>
        <Row label={ta("volume")}>
          <ValueSlider
            label={ta("volume")}
            sliderClassName="data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={clip.volume}
            min={0}
            max={3}
            step={0.05}
            snap={[1]}
            format={formatPercent}
            parse={parsePercentInput}
            onDraft={(v) => setAudio({ volume: v })}
            onCommit={(v) => commitAudio({ volume: v })}
          />
        </Row>
        <Row label={ta("fadeIn")}>
          <ValueSlider
            label={ta("fadeIn")}
            sliderClassName="fade-in-slider data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={clip.fadeIn ?? 0}
            min={0}
            max={maxFade}
            step={0.1}
            format={(v) => `${v.toFixed(1)}s`}
            parse={parseSecondsInput}
            onDraft={(v) => setAudio({ fadeIn: v })}
            onCommit={(v) => commitAudio({ fadeIn: v })}
          />
        </Row>
        <Row label={ta("fadeOut")}>
          <ValueSlider
            label={ta("fadeOut")}
            sliderClassName="fade-out-slider data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={clip.fadeOut ?? 0}
            min={0}
            max={maxFade}
            step={0.1}
            format={(v) => `${v.toFixed(1)}s`}
            parse={parseSecondsInput}
            onDraft={(v) => setAudio({ fadeOut: v })}
            onCommit={(v) => commitAudio({ fadeOut: v })}
          />
        </Row>
        <Row
          label={ta("duck")}
          info={
            clip.duck !== undefined
              ? ta("duckInfoSet", { percent: Math.round(clip.duck * 100) })
              : ta("duckInfo")
          }
        >
          <ValueSlider
            label={ta("duck")}
            sliderClassName="duck-slider data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={clip.duck ?? 1}
            min={0}
            max={1}
            step={0.05}
            format={(v) => (v >= 0.999 ? ta("off") : formatPercent(v))}
            parse={(raw) =>
              raw.trim().toLowerCase() === "off" || raw.trim().toLowerCase() === ta("off").toLowerCase()
                ? 1
                : parsePercentInput(raw)
            }
            onDraft={(v) => setAudio({ duck: v < 0.999 ? v : undefined })}
            onCommit={(v) => commitAudio({ duck: v < 0.999 ? v : undefined })}
          />
        </Row>
        {asset && !assetIsSilent(asset) && (
          <Row label={ta("beats")} info={ta("musicBeatsInfo")}>
            <BeatsControl asset={asset} />
          </Row>
        )}
        <Row label={t("hidden")}>
          <Switch
            checked={!!clip.hidden}
            onCheckedChange={(v) => useEditor.getState().updateAudio(clip.id, { hidden: v })}
          />
        </Row>
        <SoundQualityRow sound={clip.sound} onOpen={() => setView("sound")} />
      </div>
    </>
  );
}

/** The sizes and spacings a title usually wants, offered under each field's
 * chevron; any value in range can still be typed or dragged. */
export const LINE_HEIGHTS = [0.9, 1, 1.15, 1.25, 1.5, 1.75, 2];
export const LETTER_SPACINGS = [-2, 0, 2, 5, 10, 20];
/** Preset text box widths in percent of the frame width; 0 means no wrap. */
export const TEXT_WIDTHS = [0, 25, 50, 75, 100];

function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
  const t = useTranslations("inspector.text");
  const update = useEditor((s) => s.updateOverlay);
  const sizeCk = useSliderCheckpoint();
  const radiusCk = useSliderCheckpoint();
  const opacityCk = useSliderCheckpoint();
  const spacingCk = useSliderCheckpoint();
  const lineHeightCk = useSliderCheckpoint();
  const widthCk = useSliderCheckpoint();
  const strokeCk = useSliderCheckpoint();
  const taRef = useRef<HTMLTextAreaElement>(null);
  // The saved-style previews below are set in whatever font each style names,
  // so they re-render when a family finishes registering.
  const [, bumpFonts] = useState(0);
  useEffect(() => onFontsChanged(() => bumpFonts((n) => n + 1)), []);

  // Remember this title's look across clips and projects, so the next new title
  // starts from the same style.
  useEffect(() => {
    writeTextStyle({
      size: o.size,
      font: o.font,
      weight: o.weight,
      italic: o.italic,
      color: o.color,
      stroke: o.stroke,
      letterSpacing: o.letterSpacing,
      lineHeight: o.lineHeight,
      align: o.align,
      shadow: o.shadow,
      plate: o.plate,
      plateColor: o.plateColor,
      plateOpacity: o.plateOpacity,
      plateRadius: o.plateRadius,
    });
  }, [o.size, o.font, o.weight, o.italic, o.color, o.stroke, o.letterSpacing, o.lineHeight, o.align, o.shadow, o.plate, o.plateColor, o.plateOpacity, o.plateRadius]);

  const insertEmoji = (emoji: string) => {
    const ta = taRef.current;
    const s = useEditor.getState();
    s.pushHistory();
    const start = ta?.selectionStart ?? o.text.length;
    const end = ta?.selectionEnd ?? start;
    const next = o.text.slice(0, start) + emoji + o.text.slice(end);
    s.updateOverlayTransient(o.id, { text: next });
    // Advance the caret for the next insert without pulling focus off the
    // picker, so several emoji can be tapped in a row. The selection sticks to
    // the textarea even while it's unfocused.
    requestAnimationFrame(() => ta?.setSelectionRange(start + emoji.length, start + emoji.length));
  };

  return (
    <>
      <ElementTitle overlay={o} />
      <div className="flex flex-col gap-1 px-3.5 pb-4">
        <div className="relative mb-2">
          <Textarea
            ref={taRef}
            className="min-h-16 select-text pr-9"
            rows={3}
            value={o.text}
            onChange={(e) =>
              useEditor.getState().updateOverlayTransient(o.id, { text: e.target.value })
            }
            onFocus={() => useEditor.getState().pushHistory()}
          />
          <EmojiPicker
            onPick={insertEmoji}
            trigger={
              <Button
                variant="ghost"
                size="icon-sm"
                aria-label={t("insertEmoji")}
                title={t("insertEmoji")}
                className="absolute top-1.5 right-1.5 text-muted-foreground"
              >
                <Smile />
              </Button>
            }
          />
        </div>
        <StylePresetsRow overlay={o} />
        <div className="flex items-center gap-2">
          <FontPicker
            className="min-w-0 flex-1"
            value={o.font}
            onChange={(v) => update(o.id, { font: v as TextOverlay["font"] })}
          />
          <WeightSelect value={o.weight} onChange={(weight) => update(o.id, { weight })} />
        </div>
        <div className="mt-1 flex items-center gap-2">
          <SegGroup>
            <SegToggle
              label={t("italic")}
              active={!!o.italic}
              onClick={() => update(o.id, { italic: o.italic ? undefined : true })}
            >
              <Italic />
            </SegToggle>
          </SegGroup>
          <SegGroup>
            {(
              [
                ["left", AlignLeft],
                ["center", AlignCenter],
                ["right", AlignRight],
              ] as const
            ).map(([a, Icon]) => (
              <SegToggle
                key={a}
                label={t(`align.${a}`)}
                active={(o.align ?? "center") === a}
                onClick={() => update(o.id, { align: a === "center" ? undefined : a })}
              >
                <Icon />
              </SegToggle>
            ))}
          </SegGroup>
          <NumberField
            label={t("textSize")}
            className="ml-auto w-[74px]"
            icon={<Type />}
            value={o.size}
            min={TEXT_SIZE_MIN}
            max={TEXT_SIZE_MAX}
            step={1}
            presets={TEXT_SIZES}
            format={(v) => String(Math.round(v))}
            parse={parseNumberInput}
            onDraft={(v) => {
              sizeCk.begin();
              useEditor.getState().updateOverlayTransient(o.id, { size: v });
            }}
            onCommit={(v) => {
              sizeCk.begin();
              useEditor.getState().updateOverlayTransient(o.id, { size: v });
              sizeCk.end();
            }}
          />
        </div>
        <div className="mt-1 grid grid-cols-2 gap-2">
          <Field label={t("lineHeight")}>
            <NumberField
              label={t("lineHeight")}
              icon={<AlignVerticalSpaceAround />}
              value={o.lineHeight ?? 1.25}
              min={0.8}
              max={2}
              step={0.05}
              snap={[1.25]}
              presets={LINE_HEIGHTS}
              format={(v) => v.toFixed(2)}
              parse={parseNumberInput}
              onDraft={(v) => {
                lineHeightCk.begin();
                useEditor.getState().updateOverlayTransient(o.id, {
                  lineHeight: Math.abs(v - 1.25) < 0.025 ? undefined : v,
                });
              }}
              onCommit={(v) => {
                lineHeightCk.begin();
                useEditor.getState().updateOverlayTransient(o.id, {
                  lineHeight: Math.abs(v - 1.25) < 0.025 ? undefined : v,
                });
                lineHeightCk.end();
              }}
            />
          </Field>
          <Field label={t("letterSpacing")}>
            <NumberField
              label={t("letterSpacing")}
              icon={<AlignHorizontalSpaceAround />}
              value={(o.letterSpacing ?? 0) * 100}
              min={LETTER_SPACING_MIN * 100}
              max={LETTER_SPACING_MAX * 100}
              step={1}
              snap={[0]}
              presets={LETTER_SPACINGS}
              format={(v) => `${Math.round(v)}%`}
              parse={(raw) => parseNumberInput(raw.replace(/%$/, ""))}
              onDraft={(v) => {
                spacingCk.begin();
                useEditor.getState().updateOverlayTransient(o.id, {
                  letterSpacing: Math.abs(v) < 0.25 ? undefined : v / 100,
                });
              }}
              onCommit={(v) => {
                spacingCk.begin();
                useEditor.getState().updateOverlayTransient(o.id, {
                  letterSpacing: Math.abs(v) < 0.25 ? undefined : v / 100,
                });
                spacingCk.end();
              }}
            />
          </Field>
        </div>
        <Field label={t("textWidth")}>
          <NumberField label={t("textBoxWidth")} icon={<StretchHorizontal />}
            value={(o.wrapWidth ?? 0) * 100} min={0} max={200} step={1} presets={TEXT_WIDTHS}
            format={(v) => v === 0 ? t("auto") : `${Math.round(v)}%`}
            parse={(raw) => parseNumberInput(raw.replace(/%$/, ""))}
            onDraft={(v) => { widthCk.begin(); useEditor.getState().updateOverlayTransient(o.id, { wrapWidth: v > 0 ? v / 100 : undefined }); }}
            onCommit={(v) => { widthCk.begin(); useEditor.getState().updateOverlayTransient(o.id, { wrapWidth: v > 0 ? v / 100 : undefined }); widthCk.end(); }}
          />
        </Field>
        <TextTextureRow overlay={o} />
        <Row label={t("color")}>
          <ColorField
            value={o.color}
            label={t("textColor")}
            onBegin={() => useEditor.getState().pushHistory()}
            onLive={(c) => useEditor.getState().updateOverlayTransient(o.id, { color: c })}
            onCommit={(c) => update(o.id, { color: c })}
          />
        </Row>
        <TransformRows overlay={o} />
        <Section
          title={t("outline")}
          enabled={!!o.stroke}
          onEnabledChange={(v) =>
            update(o.id, { stroke: v ? { color: "#111114", width: 0.04 } : undefined })
          }
        >
          {o.stroke && (
            <>
              <Row label={t("color")}>
                <ColorField
                  value={o.stroke.color}
                  label={t("outlineColor")}
                  onBegin={() => useEditor.getState().pushHistory()}
                  onLive={(c) =>
                    useEditor.getState().updateOverlayTransient(o.id, {
                      stroke: { ...o.stroke!, color: c },
                    })
                  }
                  onCommit={(c) => update(o.id, { stroke: { ...o.stroke!, color: c } })}
                />
              </Row>
              <Row label={t("width")}>
                <ValueSlider
                  label={t("outlineWidth")}
                  sliderClassName="data-horizontal:w-24"
                  valueClassName="w-9 text-muted-foreground"
                  value={o.stroke.width * 100}
                  min={1}
                  max={15}
                  step={0.5}
                  snap={[4]}
                  format={(v) => String(Math.round(v))}
                  parse={parseNumberInput}
                  onDraft={(v) => {
                    strokeCk.begin();
                    useEditor.getState().updateOverlayTransient(o.id, {
                      stroke: { ...o.stroke!, width: v / 100 },
                    });
                  }}
                  onCommit={(v) => {
                    strokeCk.begin();
                    useEditor.getState().updateOverlayTransient(o.id, {
                      stroke: { ...o.stroke!, width: v / 100 },
                    });
                    strokeCk.end();
                  }}
                />
              </Row>
            </>
          )}
        </Section>
        <ShadowSection id={o.id} shadow={o.shadow} onToggle={(v) => update(o.id, { shadow: v })} />
        <Section
          title={t("backdrop")}
          enabled={o.plate}
          onEnabledChange={(v) => update(o.id, { plate: v })}
        >
          <>
            <Row label={t("color")}>
              <ColorField
                value={o.plateColor ?? PLATE_COLOR}
                label={t("backdropColor")}
                onBegin={() => useEditor.getState().pushHistory()}
                onLive={(c) => useEditor.getState().updateOverlayTransient(o.id, { plateColor: c })}
                onCommit={(c) => update(o.id, { plateColor: c })}
                opacity={{
                  label: t("backdropOpacity"),
                  value: o.plateOpacity ?? PLATE_OPACITY,
                  onDraft: (v) => {
                    opacityCk.begin();
                    useEditor.getState().updateOverlayTransient(o.id, { plateOpacity: v });
                  },
                  onCommit: (v) => {
                    opacityCk.begin();
                    useEditor.getState().updateOverlayTransient(o.id, { plateOpacity: v });
                    opacityCk.end();
                  },
                }}
              />
            </Row>
            <Row label={t("radius")}>
              <ValueSlider
                label={t("backdropRadius")}
                sliderClassName="data-horizontal:w-24"
                valueClassName="w-9 text-muted-foreground"
                value={o.plateRadius ?? PLATE_RADIUS}
                min={0}
                max={1}
                step={0.01}
                snap={[PLATE_RADIUS]}
                format={(v) => String(Math.round(v * 100))}
                parse={parsePercentInput}
                onDraft={(v) => {
                  radiusCk.begin();
                  useEditor.getState().updateOverlayTransient(o.id, { plateRadius: v });
                }}
                onCommit={(v) => {
                  radiusCk.begin();
                  useEditor.getState().updateOverlayTransient(o.id, { plateRadius: v });
                  radiusCk.end();
                }}
              />
            </Row>
          </>
        </Section>
        <OverlayMaskSection overlay={o} />
      </div>
    </>
  );
}

/** Named text-style presets from the shared Library: chips that apply a saved
 * look to the selected title, plus saving the current look under a name. */
export function StylePresetsRow({ overlay: o, peers }: { overlay: TextOverlay; peers?: readonly TextOverlay[] }) {
  const t = useTranslations("inspector.styles");
  const [presets, setPresets] = useState<StylePreset[] | null>(null);
  const [naming, setNaming] = useState(false);
  const [name, setName] = useState("");
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    let live = true;
    listStylePresets()
      .then((p) => live && setPresets(p))
      .catch(() => live && setPresets([]));
    return () => {
      live = false;
    };
  }, []);

  const save = async () => {
    const projectId = useEditor.getState().projectId;
    const trimmed = name.trim();
    if (!projectId || !trimmed || busy) return;
    setBusy(true);
    try {
      const p = await saveStylePreset(projectId, trimmed, o);
      if (p) setPresets((prev) => [p, ...(prev ?? [])]);
      setNaming(false);
      setName("");
    } catch {
      // Signed out or offline shelf — the chips just don't gain one.
    } finally {
      setBusy(false);
    }
  };

  // Overwrite a saved style with this title's look, in place in the chip row.
  const update = async (p: StylePreset) => {
    const projectId = useEditor.getState().projectId;
    if (!projectId || busy) return;
    setBusy(true);
    try {
      const next = await updateStylePreset(projectId, p, o);
      setPresets((prev) => (prev ?? []).flatMap((x) => (x !== p ? [x] : next ? [next] : [])));
    } catch {
      // Signed out or offline shelf — the saved style keeps its old look.
    } finally {
      setBusy(false);
    }
  };

  if (presets === null) return null;

  // A title that wears no saved style as-is has a look to push into one.
  const worn = presets.find((p) => styleMatches(p.style, o));
  const canUpdate = presets.length > 0 && !worn;
  return (
    <div className="mb-1.5">
      <div className="mb-1 flex items-center justify-between">
        <span className="text-[13px] text-muted-foreground">{t("title")}</span>
        {!naming && (
          <div className="flex items-center gap-3">
            {canUpdate && (
              <DropdownMenu>
                <DropdownMenuTrigger
                  disabled={busy}
                  className="text-[11.5px] text-muted-foreground transition-colors hover:text-foreground"
                >
                  {t("update")}
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  {presets.map((p) => (
                    <DropdownMenuItem key={`${p.residency}:${p.id}`} onClick={() => void update(p)}>
                      {p.name}
                    </DropdownMenuItem>
                  ))}
                </DropdownMenuContent>
              </DropdownMenu>
            )}
            <button
              type="button"
              className="text-[11.5px] text-muted-foreground transition-colors hover:text-foreground"
              onClick={() => setNaming(true)}
            >
              {t("save")}
            </button>
          </div>
        )}
      </div>
      {naming && (
        <div className="mb-1.5 flex items-center gap-1.5">
          <input
            autoFocus
            className="h-7 min-w-0 flex-1 rounded-md border border-input bg-transparent px-2 text-[12px] outline-none focus:border-ring"
            placeholder={t("name")}
            value={name}
            onChange={(e) => setName(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter") void save();
              if (e.key === "Escape") setNaming(false);
            }}
          />
          <Button size="sm" variant="outline" disabled={busy || !name.trim()} onClick={() => void save()}>
            {t("saveButton")}
          </Button>
        </div>
      )}
      {presets.length > 0 && (
        <div className="flex flex-wrap gap-1.5">
          {presets.map((p) => (
            <span key={`${p.residency}:${p.id}`} className="group relative">
              <button
                type="button"
                title={t("apply", { name: p.name })}
                className={cn(
                  "flex items-center gap-1.5 rounded-md border border-input px-2 py-1 text-[11.5px] transition-colors hover:border-ring",
                  p === worn && PICKED_RING
                )}
                onClick={() => {
                  const st = useEditor.getState();
                  st.pushHistory();
                  st.updateOverlaysTransient((peers ?? [o]).map((el) => ({ id: el.id, patch: { ...p.style } })));
                }}
              >
                <span
                  className="leading-none"
                  style={{
                    fontFamily: fontStack(p.style.font),
                    fontWeight: p.style.weight,
                    fontStyle: p.style.italic ? "italic" : undefined,
                    color: p.style.color,
                    textShadow: p.style.shadow ? "0 1px 2px rgba(0,0,0,0.5)" : undefined,
                    background: p.style.plate ? plateFill(p.style) : undefined,
                    borderRadius: p.style.plate ? 3 : undefined,
                    padding: p.style.plate ? "0 3px" : undefined,
                  }}
                >
                  Aa
                </span>
                {p.name}
              </button>
              <button
                type="button"
                title={t("delete", { name: p.name })}
                aria-label={t("deleteStyle", { name: p.name })}
                className="absolute -top-1.5 -right-1.5 hidden size-4 place-items-center rounded-full bg-black/60 text-[9px] text-white group-hover:grid"
                onClick={() => {
                  void deleteStylePreset(p).catch(() => {});
                  setPresets((prev) => (prev ?? []).filter((x) => x !== p));
                }}
              >
                ✕
              </button>
            </span>
          ))}
        </div>
      )}
    </div>
  );
}

/** Write an animation patch to the element — and its whole group, since a
 * grouped element's animation stamps the group. Neutral (all slots off)
 * stores as absence. */
function writeOverlayAnim(o: Overlay, anim: OverlayAnim, patch: Partial<OverlayAnim>, peers?: readonly Overlay[]) {
  const next = { ...anim, ...patch };
  if (!next.in) delete next.in;
  if (!next.out) delete next.out;
  if (!next.loop) delete next.loop;
  if (!next.move) delete next.move;
  if (!next.words) delete next.words;
  if (!next.hit) delete next.hit;
  if (!next.fonts) delete next.fonts;
  const value = hasOverlayAnim(next) ? next : undefined;
  const st = useEditor.getState();
  // A multi-selection names its targets; a lone grouped element stamps its group.
  const grouped = o.groupId ? st.overlays.filter((x) => x.groupId === o.groupId) : [];
  const targets = peers ?? (grouped.length > 1 ? grouped : [o]);
  st.updateOverlaysTransient(
    targets.map((el) => {
      if (!value?.words || !isTextOverlay(el)) return { id: el.id, patch: { anim: value } };
      // Word times are the element's own — each one's words are said at its
      // own moment — so a grouped write times every member against the cut
      // rather than copying one member's clock onto the rest. Times already
      // measured ride through: the alignment runs when a slot is first filled,
      // never on every frame of a slider drag.
      const carried = el.id === o.id ? value.words.times : el.anim?.words?.times;
      const times = carried ?? wordTimesFor(el, st.subtitles.cues);
      return {
        id: el.id,
        patch: { anim: { ...value, words: { ...value.words, ...(times ? { times } : {}) } } },
      };
    })
  );
}

/** The move's strength: how hard the hold pushes. The slider sits in two
 * places — the collapsed section, and the animation panel's Move tab — so it
 * is one component. */
function MoveStrengthSlider({ overlay: o, label, peers }: { overlay: Overlay; label: string; peers?: readonly Overlay[] }) {
  const ck = useSliderCheckpoint();
  const anim = o.anim ?? {};
  const move = anim.move;
  const write = (strength: number) => {
    if (!move) return;
    ck.begin();
    writeOverlayAnim(o, anim, { move: { ...move, strength } }, peers);
  };
  return (
    <Row label={label}>
      <ValueSlider
        label={label}
        sliderClassName="data-horizontal:w-24"
        valueClassName="w-9 text-muted-foreground"
        value={move?.strength ?? 1}
        min={MOVE_STRENGTH_MIN}
        max={MOVE_STRENGTH_MAX}
        step={MOVE_STRENGTH_STEP}
        snap={[1]}
        format={(v) => `${Math.round(v * 100)}%`}
        parse={parsePercentInput}
        disabled={!move}
        onDraft={write}
        onCommit={(v) => {
          write(v);
          ck.end();
        }}
      />
    </Row>
  );
}

/** The settings the picked word effect actually has: a swell has a size, a
 * fade has a level, anything that speaks in color has an accent. A knob the
 * effect does not use is left out — a slider with nothing to move explains
 * nothing. With no effect picked the rows sit greyed, so the panel floor
 * keeps its height while the reader scrolls the grid. */
function WordSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readonly Overlay[] }) {
  const t = useTranslations("inspector.anim");
  const ck = useSliderCheckpoint();
  const anim = o.anim ?? {};
  const words = anim.words;
  const knobs = wordKnobs(wordEffect(words?.style), words);
  // The sliders check-point on the first frame of a drag and release on
  // commit; the color field opens its own on pointer-down, so it writes
  // straight through — borrowing the slider's would leave it open and swallow
  // every checkpoint after it.
  const write = (patch: { scale?: number; dim?: number }) => {
    if (!words) return;
    ck.begin();
    writeOverlayAnim(o, anim, { words: { ...words, ...patch } }, peers);
  };
  const setColor = (color: string) => {
    if (!words) return;
    writeOverlayAnim(o, anim, { words: { ...words, color } }, peers);
  };
  return (
    <>
      {knobs.size && (
        <Row label={t("wordSize")}>
          <ValueSlider
            label={t("wordSize")}
            sliderClassName="data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={wordSwell(words)}
            min={WORD_SWELL_MIN}
            max={WORD_SWELL_MAX}
            step={0.02}
            snap={[1, WORD_POP_SCALE]}
            format={(v) => `${v.toFixed(2)}×`}
            parse={parseSpeedInput}
            disabled={!words}
            onDraft={(v) => write({ scale: v })}
            onCommit={(v) => {
              write({ scale: v });
              ck.end();
            }}
          />
        </Row>
      )}
      {knobs.dim && (
        <Row label={t("fadedTo")}>
          <ValueSlider
            label={t("fadedTo")}
            sliderClassName="data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={wordDim(words)}
            min={0}
            max={1}
            step={0.01}
            snap={[wordDim({ style: words?.style })]}
            format={(v) => `${Math.round(v * 100)}%`}
            parse={parsePercentInput}
            disabled={!words}
            onDraft={(v) => write({ dim: v })}
            onCommit={(v) => {
              write({ dim: v });
              ck.end();
            }}
          />
        </Row>
      )}
      {knobs.color && (
        <Row label={t("wordColor")}>
          <ColorField
            value={wordAccent(words, isTextOverlay(o) ? o.color : WORD_ACCENT_DEFAULT)}
            label={t("wordColor")}
            onBegin={() => useEditor.getState().pushHistory()}
            onLive={setColor}
            onCommit={setColor}
          />
        </Row>
      )}
    </>
  );
}

/** The typing bar of a typewriter entrance: on or off, whether it blinks once
 * typing stops, how many times, whether it goes after, and its color. */
function CaretSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readonly Overlay[] }) {
  const t = useTranslations("inspector.anim");
  const ck = useSliderCheckpoint();
  const anim = o.anim ?? {};
  const edge = anim.in;
  if (!edge) return null;
  const caret = edge.caret;
  const caretBlink = caret?.blink ?? true;
  const caretBlinks = caret?.blinks ?? 0;
  const caretHide = caret?.hide ?? false;
  const caretColor = caret?.color ?? (isTextOverlay(o) ? o.color : WORD_ACCENT_DEFAULT);
  const write = (next: OverlayCaret | undefined) => {
    const nextEdge = { ...edge };
    if (next) nextEdge.caret = next;
    else delete nextEdge.caret;
    writeOverlayAnim(o, anim, { in: nextEdge }, peers);
  };
  const toggle = (patch: Partial<OverlayCaret>) => {
    if (!caret) return;
    useEditor.getState().pushHistory();
    write({ ...caret, ...patch });
  };
  const setColor = (color: string) => {
    if (caret) write({ ...caret, color });
  };
  const setBlinks = (v: number) => {
    if (!caret) return;
    // No blinks count reads as blinking for good.
    const { blinks: _drop, ...rest } = caret;
    void _drop;
    write(v > 0 ? { ...caret, blinks: Math.round(v) } : rest);
  };
  return (
    <>
      <Row label={t("caret")}>
        <Switch
          checked={!!caret}
          onCheckedChange={(v) => {
            useEditor.getState().pushHistory();
            write(v ? { blink: true } : undefined);
          }}
        />
      </Row>
      {caret && (
        <Row label={t("blink")}>
          <Switch checked={caretBlink} onCheckedChange={(v) => toggle({ blink: v })} />
        </Row>
      )}
      {caret && caretBlink && (
        <Row label={t("blinks")}>
          <ValueSlider
            label={t("blinks")}
            sliderClassName="data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={caretBlinks}
            min={0}
            max={CARET_BLINKS_MAX}
            step={1}
            format={(v) => (v === 0 ? t("allBlinks") : `${Math.round(v)}`)}
            parse={parseNumberInput}
            onDraft={(v) => {
              ck.begin();
              setBlinks(v);
            }}
            onCommit={(v) => {
              setBlinks(v);
              ck.end();
            }}
          />
        </Row>
      )}
      {caret && (!caretBlink || caretBlinks > 0) && (
        <Row label={t("thenHide")}>
          <Switch checked={caretHide} onCheckedChange={(v) => toggle({ hide: v })} />
        </Row>
      )}
      {caret && (
        <Row label={t("caretColor")}>
          <ColorField
            value={caretColor}
            label={t("caretColor")}
            onBegin={() => useEditor.getState().pushHistory()}
            onLive={setColor}
            onCommit={setColor}
          />
        </Row>
      )}
    </>
  );
}

/** A newly picked hit lands at the playhead when the playhead is inside the
 * element with room for the hit, and in the element's middle otherwise.
 * Switching hits keeps the moment, the length and the darkening. */
function pickedHit(o: Overlay, anim: OverlayAnim, style: string): OverlayHit {
  if (anim.hit) return { ...anim.hit, style };
  const dur = Math.max(0.1, o.end - o.start);
  const seconds = Math.min(OVERLAY_HIT_DEFAULT_SECONDS, dur);
  const local = playheadAt() - o.start;
  const at = local >= 0 && local <= dur - seconds ? local : Math.max(0, (dur - seconds) / 2);
  return { style, at: Math.round(at * 100) / 100, seconds, darken: true };
}

/** The hit's moment inside the element, its length, and whether it darkens. */
function HitSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readonly Overlay[] }) {
  const t = useTranslations("inspector.anim");
  const ck = useSliderCheckpoint();
  const anim = o.anim ?? {};
  const hit = anim.hit;
  const dur = Math.max(0.2, Math.min(...(peers ?? [o]).map((el) => el.end - el.start)));
  const hitSeconds = hit?.seconds ?? OVERLAY_HIT_DEFAULT_SECONDS;
  const hitAt = hit?.at ?? 0;
  const hitDarken = hit?.darken ?? false;
  const write = (patch: Partial<OverlayHit>) => {
    if (!hit) return;
    ck.begin();
    writeOverlayAnim(o, anim, { hit: { ...hit, ...patch } }, peers);
  };
  return (
    <>
      <Row label={t("at")}>
        <ValueSlider
          label={t("at")}
          sliderClassName="data-horizontal:w-24"
          valueClassName="w-9 text-muted-foreground"
          value={hitAt}
          min={0}
          max={Math.max(0, dur - hitSeconds)}
          step={0.05}
          format={(v) => `${v.toFixed(2)}s`}
          parse={parseSecondsInput}
          disabled={!hit}
          onDraft={(v) => write({ at: v })}
          onCommit={(v) => {
            write({ at: v });
            ck.end();
          }}
        />
      </Row>
      <Row label={t("duration")}>
        <ValueSlider
          label={t("duration")}
          sliderClassName="data-horizontal:w-24"
          valueClassName="w-9 text-muted-foreground"
          value={hitSeconds}
          min={OVERLAY_HIT_MIN_SECONDS}
          max={Math.min(OVERLAY_HIT_MAX_SECONDS, dur)}
          step={0.05}
          snap={[OVERLAY_HIT_DEFAULT_SECONDS]}
          format={(v) => `${v.toFixed(2)}s`}
          parse={parseSecondsInput}
          disabled={!hit}
          onDraft={(v) => write({ seconds: v })}
          onCommit={(v) => {
            write({ seconds: v });
            ck.end();
          }}
        />
      </Row>
      <Row label={t("darken")}>
        <Switch
          checked={hitDarken}
          disabled={!hit}
          onCheckedChange={(v) => {
            if (!hit) return;
            useEditor.getState().pushHistory();
            writeOverlayAnim(o, anim, { hit: { ...hit, darken: v } }, peers);
          }}
        />
      </Row>
    </>
  );
}

/** A title's weight, from regular to black; each weight names itself under
 * `inspector.text.weights`. */
function WeightSelect({ value, onChange }: { value: TextWeight; onChange: (w: TextWeight) => void }) {
  const t = useTranslations("inspector.text");
  const weightLabel = (w: TextWeight) => t(`weights.${w}`);
  return (
    <Select
      value={String(value)}
      items={Object.fromEntries(TEXT_WEIGHTS.map((w) => [String(w), weightLabel(w)]))}
      onValueChange={(v) => onChange(Number(v) as TextWeight)}
    >
      <SelectTrigger aria-label={t("weight")} size="sm" className="w-24 text-[12px]">
        <SelectValue />
      </SelectTrigger>
      <SelectContent>
        {TEXT_WEIGHTS.map((w) => (
          <SelectItem key={w} value={String(w)} className="text-[12px]">
            {weightLabel(w)}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}

/** A face the cycle does not show yet, for the Add face button: the next
 * font in the menu after the last face, so each add brings a new look. */
function nextCycleFont(o: TextOverlay, faces: CycleFace[]): string {
  const ids = allFonts().map((f) => f.id);
  const used = new Set([o.font, ...faces.map((f) => f.font)]);
  const from = ids.indexOf(faces.at(-1)?.font ?? o.font);
  for (let i = 1; i <= ids.length; i++) {
    const id = ids[(from + i) % ids.length];
    if (!used.has(id)) return id;
  }
  return o.font;
}

/** The font cycle's faces, in the order the title walks them: each one's
 * font, weight, size and tracking, and a button to add another. The first
 * face added starts a cycle across the title's whole length. */
function FontCycleFaces({ overlay: o, peers }: { overlay: TextOverlay; peers?: readonly Overlay[] }) {
  const t = useTranslations("inspector.fontCycle");
  const ck = useSliderCheckpoint();
  const anim = o.anim ?? {};
  const fontCycle = anim.fonts;
  const faces = fontCycle?.faces ?? [];
  const dur = Math.max(0.2, Math.min(...(peers ?? [o]).map((el) => el.end - el.start)));

  // Every edit writes the whole face list; none left clears the cycle.
  const write = (next: CycleFace[]) => {
    const fonts: OverlayFontCycle | undefined = next.length
      ? (fontCycle ? { ...fontCycle, faces: next } : { faces: next, at: 0, seconds: dur, rate: FONT_CYCLE_RATE })
      : undefined;
    writeOverlayAnim(o, anim, { fonts }, peers);
  };
  const commit = (next: CycleFace[]) => {
    useEditor.getState().pushHistory();
    write(next);
  };
  const setFace = (i: number, patch: Partial<CycleFace>) => faces.map((f, j) => (j === i ? { ...f, ...patch } : f));

  return (
    <div className="flex flex-col gap-2">
      {faces.map((face, i) => (
        <div key={i} className={cn("flex flex-col gap-1.5", i > 0 && "border-t border-border pt-2")}>
          <div className="flex items-center gap-1.5">
            <FontPicker className="min-w-0 flex-1" value={face.font} onChange={(font) => commit(setFace(i, { font }))} />
            <Button
              variant="ghost"
              size="icon-sm"
              aria-label={t("removeFace")}
              onClick={() => commit(faces.filter((_, j) => j !== i))}
            >
              <X />
            </Button>
          </div>
          <Row label={t("weight")}>
            <div className="flex items-center gap-1.5">
              <WeightSelect value={face.weight ?? o.weight} onChange={(weight) => commit(setFace(i, { weight }))} />
              <SegGroup>
                <SegToggle
                  label={t("italic")}
                  active={face.italic ?? !!o.italic}
                  onClick={() => commit(setFace(i, { italic: !(face.italic ?? !!o.italic) }))}
                >
                  <Italic />
                </SegToggle>
              </SegGroup>
            </div>
          </Row>
          <Row label={t("size")}>
            <ValueSlider
              label={t("size")}
              sliderClassName="data-horizontal:w-24"
              valueClassName="w-9 text-muted-foreground"
              value={face.scale ?? 1}
              min={CYCLE_SCALE_MIN}
              max={CYCLE_SCALE_MAX}
              step={0.05}
              snap={[1]}
              format={(v) => `${v.toFixed(2)}×`}
              parse={parseNumberInput}
              onDraft={(scale) => {
                ck.begin();
                write(setFace(i, { scale }));
              }}
              onCommit={(scale) => {
                write(setFace(i, { scale }));
                ck.end();
              }}
            />
          </Row>
          <Row label={t("tracking")}>
            <ValueSlider
              label={t("tracking")}
              sliderClassName="data-horizontal:w-24"
              valueClassName="w-9 text-muted-foreground"
              value={(face.tracking ?? o.letterSpacing ?? 0) * 100}
              min={-5}
              max={50}
              step={1}
              format={(v) => `${Math.round(v)}%`}
              parse={(raw) => parseNumberInput(raw.replace(/%$/, ""))}
              onDraft={(v) => {
                ck.begin();
                write(setFace(i, { tracking: v / 100 }));
              }}
              onCommit={(v) => {
                write(setFace(i, { tracking: v / 100 }));
                ck.end();
              }}
            />
          </Row>
          {/* Hold: how long this face shows; 0 follows the cycle's rate. */}
          <Row label={t("hold")}>
            <ValueSlider
              label={t("hold")}
              sliderClassName="data-horizontal:w-24"
              valueClassName="w-9 text-muted-foreground"
              value={face.hold ?? 0}
              min={0}
              max={CYCLE_HOLD_MAX}
              step={1 / 60}
              snap={[0]}
              format={(v) => (v > 0 ? `${v.toFixed(2)}s` : t("rate"))}
              parse={parseNumberInput}
              onDraft={(v) => {
                ck.begin();
                write(setFace(i, { hold: v > 0 ? v : undefined }));
              }}
              onCommit={(v) => {
                write(setFace(i, { hold: v > 0 ? v : undefined }));
                ck.end();
              }}
            />
          </Row>
        </div>
      ))}
      <Button
        variant="secondary"
        size="sm"
        disabled={faces.length >= FONT_CYCLE_FACES_MAX}
        onClick={() => commit([...faces, { font: nextCycleFont(o, faces) }])}
      >
        <Plus />
        {t("addFace")}
      </Button>
    </div>
  );
}

/** Where the font cycle starts inside the title, how long it runs, how
 * many times a second the face changes, and the music beats that can time
 * every face instead. */
function FontCycleSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readonly Overlay[] }) {
  const t = useTranslations("inspector.fontCycle");
  const ck = useSliderCheckpoint();
  const anim = o.anim ?? {};
  const cycle = anim.fonts;
  const dur = Math.max(0.2, Math.min(...(peers ?? [o]).map((el) => el.end - el.start)));
  const fontCycleAt = cycle?.at ?? 0;
  const fontCycleSeconds = cycle?.seconds ?? dur;
  const fontCycleRate = cycle?.rate ?? FONT_CYCLE_RATE;
  const write = (patch: Partial<OverlayFontCycle>) => {
    if (!cycle) return;
    ck.begin();
    writeOverlayAnim(o, anim, { fonts: { ...cycle, ...patch } }, peers);
  };
  const slider = (
    label: string,
    value: number,
    min: number,
    max: number,
    step: number,
    format: (v: number) => string,
    key: keyof OverlayFontCycle
  ) => (
    <Row label={label}>
      <ValueSlider
        label={label}
        sliderClassName="data-horizontal:w-24"
        valueClassName="w-9 text-muted-foreground"
        value={value}
        min={min}
        max={max}
        step={step}
        format={format}
        parse={parseNumberInput}
        disabled={!cycle}
        onDraft={(v) => write({ [key]: v })}
        onCommit={(v) => {
          write({ [key]: v });
          ck.end();
        }}
      />
    </Row>
  );
  const secs = (v: number) => `${v.toFixed(2)}s`;

  // Clips whose music has a beat grid; one of them times every face.
  const clips = useEditor((s) => s.clips);
  const audioClips = useEditor((s) => s.audioClips);
  const assets = useEditor((s) => s.assets);
  const beatClips = useMemo(
    () =>
      [...audioClips, ...clips].flatMap((c) => {
        const asset = assets.find((a) => a.id === c.assetId);
        return (asset?.beats?.beats.length ?? 0) >= 2 ? [{ clip: c, asset: asset! }] : [];
      }),
    [clips, audioClips, assets]
  );
  const [fontCycleBeats, setFontCycleBeats] = useState<string>();
  const [fontCycleBeatStep, setFontCycleBeatStep] = useState<number>(1);
  const [beatNote, setBeatNote] = useState<string>();
  const beatSource = beatClips.find((b) => b.clip.id === fontCycleBeats) ?? beatClips[0];

  // A new face on each beat (or every other, or half beat) of the picked
  // clip inside the cycle's run, the faces repeating to fill it.
  const timeToBeats = () => {
    if (!cycle || !beatSource) return;
    const elDur = o.end - o.start;
    const beats = clipBeatTimes(beatSource.clip, beatSource.asset).map((at) => at - o.start);
    const edges = tidySwitches(
      beatSwitches(beats, fontCycleBeatStep, fontCycleAt, fontCycleAt + fontCycleSeconds),
      elDur
    );
    const problem = switchProblem(edges);
    if (problem) {
      setBeatNote(
        problem.kind === "few"
          ? t("beatsFew")
          : problem.kind === "many"
            ? t("beatsMany", { faces: problem.faces, max: FONT_CYCLE_FACES_MAX })
            : t("beatsLong", { seconds: problem.seconds.toFixed(2), max: CYCLE_HOLD_MAX })
      );
      return;
    }
    setBeatNote(undefined);
    useEditor.getState().pushHistory();
    writeOverlayAnim(o, anim, { fonts: timedFontCycle(cycle.faces, edges, fontCycleRate) }, peers);
  };

  return (
    <>
      {slider(t("at"), fontCycleAt, 0, Math.max(0, dur - 0.05), 0.05, secs, "at")}
      {slider(t("duration"), fontCycleSeconds, 0.05, Math.max(0.05, dur - fontCycleAt), 0.05, secs, "seconds")}
      {slider(t("rate"), fontCycleRate, FONT_CYCLE_RATE_MIN, FONT_CYCLE_RATE_MAX, 1, (v) => `${Math.round(v)}/s`, "rate")}
      <Row label={t("beats")} info={t("beatsInfo")}>
        {beatClips.length === 0 ? (
          <span className="text-[12px] text-muted-foreground">{t("detectFirst")}</span>
        ) : (
          <Select value={beatSource?.clip.id} onValueChange={(v) => setFontCycleBeats(String(v))} disabled={!cycle}>
            <SelectTrigger className="h-8 w-36 text-[12px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {beatClips.map(({ clip, asset }) => (
                <SelectItem key={clip.id} value={clip.id} className="text-[12px]">
                  {asset.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        )}
      </Row>
      {beatClips.length > 0 && (
        <Row label={t("eachFace")}>
          <div className="flex items-center gap-1.5">
            <Select
              value={String(fontCycleBeatStep)}
              onValueChange={(v) => setFontCycleBeatStep(Number(v))}
              disabled={!cycle}
            >
              <SelectTrigger className="h-8 w-20 text-[12px]" aria-label={t("beatsPerFace")}>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {CYCLE_BEAT_STEPS.map((step) => (
                  <SelectItem key={step} value={String(step)} className="text-[12px]">
                    {step === 0.5 ? t("halfBeat") : t("beatStep", { count: step })}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Button variant="secondary" size="sm" disabled={!cycle} onClick={timeToBeats}>
              {t("time")}
            </Button>
          </div>
        </Row>
      )}
      {beatNote && <p className="text-[11px] text-muted-foreground">{beatNote}</p>}
    </>
  );
}

/** The slots the picker fills, in tab order. */
type AnimSlot = "in" | "out" | "loop" | "move" | "words" | "fonts" | "hit";

/** The pill of slot tabs over an animation grid. A slot that is already set
 * reads darker, so switching tabs is not the only way to see what an item is
 * doing. */
function SlotTabs<T extends string>({
  tabs,
  slot,
  isSet,
  onPick,
}: {
  tabs: readonly T[];
  slot: T;
  isSet: (id: T) => boolean;
  onPick: (id: T) => void;
}) {
  const t = useTranslations("inspector.anim.slots");
  return (
    <div className="mx-3.5 flex shrink-0 rounded-lg bg-muted p-0.5 text-[11.5px] font-medium">
      {tabs.map((id) => (
        <button
          key={id}
          type="button"
          className={cn(
            "flex-1 rounded-md px-1 py-1 capitalize transition-colors",
            slot === id ? "bg-neutral-900 text-white" : "text-muted-foreground hover:text-foreground",
            isSet(id) && slot !== id && "text-foreground"
          )}
          onClick={() => onPick(id)}
        >
          {t(id as AnimSlot)}
        </button>
      ))}
    </div>
  );
}

const CLIP_ANIM_SLOTS = ["in", "out"] as const;

/** The Animation view a video clip's rail opens: In and Out over the tile
 * grid, the ramp's length on the floor. A pick lands as the bar on that edge —
 * the timeline draws it, the Transitions tab marks it, and the assistant's
 * set_animation writes the same one — and plays itself on the footage. */
export function ClipAnimationPanel({ clip, peers }: { clip: VideoClip; peers?: readonly VideoClip[] }) {
  const t = useTranslations("inspector.anim");
  const [picked, setSlot] = usePanelState<"in" | "out">(clip.id, "animSlot", "in");
  const slot = picked === "out" ? "out" : "in";
  const tilesScroll = useRememberedScroll(clip.id, `anim:${slot}`);
  const anim = slot === "in" ? clip.animIn : clip.animOut;
  // The ramp's length lands once, on release: every write to the edge is a
  // bar edit with its own undo step.
  const [secondsDraft, setSecondsDraft] = useState<number | null>(null);
  const targets = peers ?? [clip];
  // The ramp fits the shortest clip it lands on.
  const len = Math.min(...targets.map(clipLen));
  const rehearse = (seconds: number) =>
    previewBar({ start: slot === "in" ? clip.start : clip.start + clipLen(clip) - seconds, seconds });
  // One undo step across every target.
  const setAll = (value: ClipAnim | null) => {
    const st = useEditor.getState();
    st.beginHistoryBatch();
    for (const c of targets) st.setClipAnim(c.id, slot, value);
    st.endHistoryBatch();
  };
  const pick = (style: AnimStyle | null) => {
    if (!style) {
      if (anim) setAll(null);
      return;
    }
    const seconds = anim?.seconds ?? ANIM_DEFAULT_SECONDS;
    setAll({ style, seconds });
    rehearse(seconds);
  };
  return (
    <div className="flex min-h-0 flex-1 flex-col">
      <div className="shrink-0 bg-card pb-2">
        <div className="flex h-10 shrink-0 items-center px-3.5 text-sm font-semibold tracking-tight">
          {t("title")}
        </div>
        <SlotTabs
          tabs={CLIP_ANIM_SLOTS}
          slot={slot}
          isSet={(id) => !!(id === "in" ? clip.animIn : clip.animOut)}
          onPick={setSlot}
        />
      </div>
      {/* pt-1 clears the selected tile's ring, which draws outside its box. */}
      <ScrollArea
        key={slot}
        className="min-h-0 flex-1"
        {...tilesScroll}
        viewportClassName="overscroll-contain"
        contentClassName="flex flex-col gap-1 px-3.5 pt-1 pb-2"
      >
        <ClipAnimationTiles clip={clip} which={slot} value={anim?.style} onPick={pick} />
      </ScrollArea>
      <div className="shrink-0 border-t border-border bg-card px-3.5 py-0.5">
        <Row label={t("duration")}>
          <ValueSlider
            label={t("duration")}
            sliderClassName="data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={secondsDraft ?? anim?.seconds ?? ANIM_DEFAULT_SECONDS}
            min={0.1}
            max={Math.min(TRANSITION_MAX, len)}
            step={0.05}
            snap={[ANIM_DEFAULT_SECONDS]}
            format={(v) => `${v.toFixed(2)}s`}
            parse={parseSecondsInput}
            disabled={!anim}
            onDraft={setSecondsDraft}
            onCommit={(v) => {
              setSecondsDraft(null);
              if (!anim) return;
              setAll({ ...anim, seconds: v });
              rehearse(v);
            }}
          />
        </Row>
      </div>
    </div>
  );
}

/** The animation subview an overlay panel pushes into: a tab per slot over
 * the tile grid, the active slot's own control under it. The slots pick from
 * the same grid, one at a time — the tiles are big enough to read the motion,
 * which a stack of grids would not be. */
export function AnimationPanel({ overlay: o, peers }: { overlay: Overlay; peers?: readonly Overlay[] }) {
  const t = useTranslations("inspector.anim");
  const anim = o.anim ?? {};
  // The active slot holds for the session, like every settings view's tab.
  const [picked, setSlot] = usePanelState<AnimSlot>(o.id, "animSlot", "in");
  // Word emphasis is a title's slot; a shape or a sticker has no words, so
  // selecting one hands the picker back to the entrance.
  // Word emphasis needs words on every target.
  const tabs: AnimSlot[] = (peers ?? [o]).every(isTextOverlay)
    ? ["in", "out", "loop", "move", "words", "fonts", "hit"]
    : ["in", "out", "loop", "move", "hit"];
  const slot = tabs.includes(picked) ? picked : "in";
  const tilesScroll = useRememberedScroll(o.id, `anim:${slot}`);
  const active =
    slot === "move" || slot === "words" || slot === "fonts" || slot === "hit" ? undefined : anim[slot];
  const seconds =
    slot === "in" || slot === "out"
      ? anim[slot]?.seconds
      : slot === "hit"
        ? (anim.hit?.seconds ?? OVERLAY_HIT_DEFAULT_SECONDS)
        : undefined;
  const activeMove = anim.move;
  const hitStyle = anim.hit?.style;
  const pick = (style: string | null) => {
    // The fonts tab edits its faces in place; it has no tiles to pick.
    if (slot === "fonts") return;
    if (slot === "hit") {
      if (!style && !anim.hit) return;
      useEditor.getState().pushHistory();
      const patch: Partial<OverlayAnim> = { hit: style ? pickedHit(o, anim, style) : undefined };
      writeOverlayAnim(o, anim, patch, peers);
      // The pick plays itself on the stage, over its own window.
      if (style) playAnimPreview({ ...o, anim: { ...anim, ...patch } }, "hit");
      else stopAnimPreview();
      return;
    }
    if (slot === "words") {
      if (!style && !anim.words) return;
      useEditor.getState().pushHistory();
      // The transcript is the clock: the times land at apply, measured
      // against whatever the cut has been transcribed to say. Nothing to
      // measure against leaves them out, and the words share the element's
      // span instead.
      const patch: Partial<OverlayAnim> = {
        words: style
          ? {
              style: style as WordEffectId,
              ...(anim.words?.color ? { color: anim.words.color } : {}),
              ...(anim.words?.scale !== undefined ? { scale: anim.words.scale } : {}),
              ...(anim.words?.dim !== undefined ? { dim: anim.words.dim } : {}),
            }
          : undefined,
      };
      writeOverlayAnim(o, anim, patch, peers);
      // The pick sweeps itself along the line, the same as any other slot.
      if (style) {
        const el = useEditor.getState().overlays.find((x) => x.id === o.id) ?? o;
        playAnimPreview(el, "words");
      } else stopAnimPreview();
      return;
    }
    if (slot === "move") {
      if (!style && !activeMove) return;
      useEditor.getState().pushHistory();
      // A newly picked move starts at full strength; switching moves keeps
      // whatever strength the last one was set to.
      const patch: Partial<OverlayAnim> = {
        move: style ? { style, strength: activeMove?.strength ?? 1 } : undefined,
      };
      writeOverlayAnim(o, anim, patch, peers);
      // The pick plays itself on the stage, the same as any other slot.
      if (style) playAnimPreview({ ...o, anim: { ...anim, ...patch } }, "move");
      else stopAnimPreview();
      return;
    }
    if (!style) {
      stopAnimPreview();
      useEditor.getState().pushHistory();
      writeOverlayAnim(o, anim, { [slot]: undefined }, peers);
      return;
    }
    const caret = slot === "in" ? keepCaret(anim.in, style) : undefined;
    const patch: Partial<OverlayAnim> =
      slot === "loop"
        ? { loop: { style: style as OverlayLoopStyle, speed: anim.loop?.speed ?? 1 } }
        : {
            [slot]: {
              style: style as OverlayAnimStyle,
              // A long count's length shrinks to the new style's cap.
              seconds: Math.min(edgeMaxSeconds(style), seconds ?? OVERLAY_ANIM_DEFAULT_SECONDS),
              ...(caret ? { caret } : {}),
            },
          };
    useEditor.getState().pushHistory();
    writeOverlayAnim(o, anim, patch, peers);
    // The pick plays itself on the stage, for exactly its own length.
    playAnimPreview({ ...o, anim: { ...anim, ...patch } }, slot);
  };
  // A rehearsal belongs to the panel that started it: leaving takes it away.
  useEffect(() => stopAnimPreview, []);

  return (
    // Three bands: the tabs, the grid, the bar. Only the middle one scrolls —
    // it owns the scroller, so the two edges are outside it and stay still
    // even while the grid rubber-bands at its ends.
    <div className="flex min-h-0 flex-1 flex-col">
      <div className="shrink-0 bg-card pb-2">
        <div className="flex h-10 shrink-0 items-center px-3.5 text-sm font-semibold tracking-tight">
          {t("title")}
        </div>
        <SlotTabs
          tabs={tabs}
          slot={slot}
          isSet={(id) => (id === "move" ? !!activeMove : !!anim[id])}
          onPick={setSlot}
        />
      </div>
      {/* pt-1 clears the selected tile's ring, which draws outside its box.
          The bounce stops here rather than travelling to the panel behind. */}
      <ScrollArea
        // Keyed on the tab: each list of tiles keeps its own place.
        key={slot}
        className="min-h-0 flex-1"
        {...tilesScroll}
        viewportClassName="overscroll-contain"
        contentClassName="flex flex-col gap-1 px-3.5 pt-1 pb-2"
      >
        {slot === "fonts" && isTextOverlay(o) ? (
          <FontCycleFaces overlay={o} peers={peers} />
        ) : slot === "fonts" ? null : (
        <AnimationTiles
          slot={slot}
          // A slot carrying its own preset is playing something no tile here
          // names, so the grid shows nothing selected rather than the catalog
          // entry the id happens to hold.
          value={
            active?.preset
              ? undefined
              : slot === "move"
                ? activeMove?.style
                : slot === "words"
                  ? anim.words?.style
                  : slot === "hit"
                    ? hitStyle
                    : active?.style
          }
          custom={!!active?.preset}
          isText={isTextOverlay(o)}
          seconds={seconds ?? OVERLAY_ANIM_DEFAULT_SECONDS}
          speed={anim.loop?.speed ?? 1}
          textColor={isTextOverlay(o) ? o.color : WORD_ACCENT_DEFAULT}
          accentColor={anim.words?.color}
          accentScale={anim.words?.scale}
          accentDim={anim.words?.dim}
          onPick={pick}
        />
        )}
      </ScrollArea>
      <AnimationToolbar overlay={o} slot={slot} peers={peers} />
    </div>
  );
}

/** The bar on the panel floor: the one number the active tab has, kept in
 * reach while the reader is still scrolling the grid. Each slot measures
 * something different — a ramp in seconds, a loop's rate, how hard a move
 * pushes — so the bar shows the tab's own control and nothing else. It stays
 * put with the slot unset, greyed rather than gone, because a bar that comes
 * and goes moves the grid under the pointer. */
function AnimationToolbar({ overlay: o, slot, peers }: { overlay: Overlay; slot: AnimSlot; peers?: readonly Overlay[] }) {
  const t = useTranslations("inspector.anim");
  const easeLabel = useLabels("ease");
  const ck = useSliderCheckpoint();
  const anim = o.anim ?? {};
  // The ramp fits the shortest element it lands on.
  const dur = Math.max(0.2, Math.min(...(peers ?? [o]).map((el) => el.end - el.start)));
  const edge = slot === "in" || slot === "out" ? anim[slot] : undefined;

  const bar = (children: React.ReactNode) => (
    <div className="shrink-0 border-t border-border bg-card px-3.5 py-0.5">{children}</div>
  );

  if (slot === "move") return bar(<MoveStrengthSlider overlay={o} label={t("strength")} peers={peers} />);

  if (slot === "words") return bar(<WordSettings overlay={o} peers={peers} />);

  if (slot === "hit") return bar(<HitSettings overlay={o} peers={peers} />);

  if (slot === "fonts") return bar(<FontCycleSettings overlay={o} peers={peers} />);

  if (slot === "loop") {
    const write = (speed: number) => {
      if (!anim.loop) return;
      ck.begin();
      writeOverlayAnim(o, anim, { loop: { ...anim.loop, speed } }, peers);
    };
    return bar(
      <Row label={t("speed")}>
        <ValueSlider
          label={t("speed")}
          sliderClassName="data-horizontal:w-24"
          valueClassName="w-9 text-muted-foreground"
          value={anim.loop?.speed ?? 1}
          min={LOOP_SPEED_MIN}
          max={LOOP_SPEED_MAX}
          step={0.25}
          snap={[1]}
          format={(v) => `${v.toFixed(2)}×`}
          parse={parseSpeedInput}
          disabled={!anim.loop}
          onDraft={write}
          onCommit={(v) => {
            write(v);
            ck.end();
          }}
        />
      </Row>
    );
  }

  const write = (secs: number) => {
    if (!edge) return;
    ck.begin();
    writeOverlayAnim(o, anim, { [slot]: { ...edge, seconds: secs } }, peers);
  };
  // A typing entrance on a title carries its typing bar's settings too.
  const types = slot === "in" && isTextOverlay(o) && !!edgeMotion(edge)?.animate.typed;
  // A per-letter style on a title carries its letter hand-off.
  const stagger = isTextOverlay(o) ? edgeStagger(edge) : undefined;
  const writeStagger = (v: number) => {
    if (!edge) {
      return;
    }
    ck.begin();
    writeOverlayAnim(o, anim, { [slot]: { ...edge, stagger: v } }, peers);
  };
  // The order the letters take their turns, and how far the motion reaches.
  const edgeSequence = Array.isArray(edge?.order) ? edge.order : null;
  const edgeOrder = edgeSequence ? "sequence" : (edge?.order ?? (edgeMotion(edge)?.selector?.randomize ? "shuffle" : "reading"));
  const ownReach = edgeOwnReach(edge);
  const edgeDistance = edge?.distance ?? ownReach;
  const edgeEase = edge?.ease ?? "style";
  // A style that fades as it moves can be told to stay solid.
  const edgeFades = !!(edge && (edge.preset ?? edgePreset(edge.style))?.animate.opacity);
  const edgeFade = edge?.fade !== false;
  // How much of the move the fade takes: a share, or all of it.
  const edgeFadeShare = typeof edge?.fade === "number" ? edge.fade : 1;
  // How soft it starts: the slot's own, else the style's far-end defocus.
  const edgeBlur = edge?.blur ?? (edge ? ((edge.preset ?? edgePreset(edge.style))?.animate.blur?.[0]?.v ?? 0) : 0);
  // An edge's curve: the style's own, or any ease by name.
  const edgeEaseItems: Record<string, string> = {
    style: t("styleOwnEase"),
    ...Object.fromEntries(EASE_IDS.map((id) => [id, easeLabel(id)])),
  };
  const writeEdge = (patch: Partial<OverlayEdge>) => {
    if (!edge) return;
    ck.begin();
    writeOverlayAnim(o, anim, { [slot]: { ...edge, ...patch } }, peers);
  };
  // A slot on a title: its reel's turn, spacing, window and landing, shown in
  // design px of the title's size (the edge keeps them in em).
  const rolls = isTextOverlay(o) && !!edgeMotion(edge)?.animate.roll;
  const typeSize = isTextOverlay(o) ? o.size : 0;
  const lineEm = (isTextOverlay(o) ? o.lineHeight : undefined) ?? LINE_HEIGHT;
  const edgeReel: ReelDirection = edge?.reel ?? "up";
  const edgeReelPitch = (edge?.pitch ?? SLOT_PITCH * lineEm) * typeSize;
  const edgeReelBand = (edge?.band ?? lineEm / 2) * typeSize;
  const edgeOvershoot = (edge?.overshoot ?? 0) * typeSize;
  const edgeSettle = edge?.settle ?? 0.3;
  const reelItems: Record<ReelDirection, string> = { up: t("reelUp"), down: t("reelDown") };
  // A dive: the point it zooms about, held where it stands, design px from
  // the element's center; off flies the deepest ink to the frame's center.
  const dives = !!edgeMotion(edge)?.animate.dive;
  const edgeAnchor = edge?.anchor;
  return bar(
    <>
      <Row label={t("duration")}>
        <ValueSlider
          label={t("duration")}
          sliderClassName="data-horizontal:w-24"
          valueClassName="w-9 text-muted-foreground"
          value={edge?.seconds ?? OVERLAY_ANIM_DEFAULT_SECONDS}
          min={OVERLAY_ANIM_MIN_SECONDS}
          max={Math.min(edgeMaxSeconds(edge?.style), dur)}
          step={0.05}
          snap={[OVERLAY_ANIM_DEFAULT_SECONDS]}
          format={(v) => `${v.toFixed(2)}s`}
          parse={parseSecondsInput}
          disabled={!edge}
          onDraft={write}
          onCommit={(v) => {
            write(v);
            ck.end();
          }}
        />
      </Row>
      {stagger !== undefined && (
        <Row label={t("stagger")}>
          <ValueSlider
            label={t("stagger")}
            sliderClassName="data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={stagger}
            min={0}
            max={EDGE_STAGGER_MAX}
            step={0.01}
            snap={[edgeMotion(edge)?.selector?.spread ?? 0]}
            format={(v) => String(Math.round(v * 100))}
            parse={parsePercentInput}
            onDraft={writeStagger}
            onCommit={(v) => {
              writeStagger(v);
              ck.end();
            }}
          />
        </Row>
      )}
      {stagger !== undefined && (
        <Row label={t("shuffle")}>
          <Switch
            checked={edgeOrder !== "reading"}
            onCheckedChange={(v) => {
              writeEdge({ order: v ? "shuffle" : "reading" });
              ck.end();
            }}
          />
        </Row>
      )}
      {ownReach > 0 && (
        // The curve the move travels on, over the style's own.
        <Row label={t("ease")}>
          <Select
            value={edgeEase}
            items={edgeEaseItems}
            onValueChange={(id) => {
              const rest = { ...edge! };
              delete rest.ease;
              ck.begin();
              writeOverlayAnim(o, anim, { [slot]: id === "style" ? rest : { ...rest, ease: id as EaseId } }, peers);
              ck.end();
            }}
          >
            <SelectTrigger className="h-8 w-36 text-[12px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {Object.entries(edgeEaseItems).map(([id, label]) => (
                <SelectItem key={id} value={id} className="text-[12px]">
                  {label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </Row>
      )}
      {edgeFades && (
        <Row label={t("fade")}>
          <Switch
            checked={edgeFade}
            onCheckedChange={(v) => {
              const rest = { ...edge! };
              delete rest.fade;
              ck.begin();
              writeOverlayAnim(o, anim, { [slot]: v ? rest : { ...rest, fade: false } }, peers);
              ck.end();
            }}
          />
        </Row>
      )}
      {edgeFades && edgeFade && (
        <Row label={t("fadeLength")}>
          <ValueSlider
            label={t("fadeLength")}
            sliderClassName="data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={edgeFadeShare}
            min={0.05}
            max={1}
            step={0.05}
            format={(v) => `${Math.round(v * 100)}%`}
            parse={(t) => Number(t.replace("%", "")) / 100}
            onDraft={(v) => writeEdge({ fade: v >= 1 ? undefined : v })}
            onCommit={(v) => {
              writeEdge({ fade: v >= 1 ? undefined : v });
              ck.end();
            }}
          />
        </Row>
      )}
      {edgeSequence && isTextOverlay(o) && (
        // An order read off a reference: the letters as they arrive.
        <Row label={t("order")}>
          <span className="truncate text-xs text-muted-foreground" title={t("orderHint")}>
            {edgeSequence.map((i) => [...o.text][i] ?? "").join(" ")}
          </span>
        </Row>
      )}
      {ownReach > 0 && (
        <Row label={t("distance")}>
          <ValueSlider
            label={t("distance")}
            sliderClassName="data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={edgeDistance}
            min={1}
            max={EDGE_DISTANCE_MAX}
            step={1}
            snap={[ownReach]}
            format={(v) => String(Math.round(v))}
            parse={(t) => Number(t)}
            onDraft={(v) => writeEdge({ distance: v })}
            onCommit={(v) => {
              writeEdge({ distance: v });
              ck.end();
            }}
          />
        </Row>
      )}
      {rolls && (
        <Row label={t("reel")}>
          <Select
            value={edgeReel}
            items={reelItems}
            onValueChange={(id) => {
              writeEdge({ reel: id as ReelDirection });
              ck.end();
            }}
          >
            <SelectTrigger className="h-8 w-36 text-[12px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {REEL_DIRECTIONS.map((id) => (
                <SelectItem key={id} value={id} className="text-[12px]">
                  {reelItems[id]}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </Row>
      )}
      {rolls &&
        (
          [
            ["reelPitch", edgeReelPitch, "pitch", 0.2],
            ["reelBand", edgeReelBand, "band", 0.2],
            ["overshoot", edgeOvershoot, "overshoot", 0],
          ] as const
        ).map(([label, value, field, minEm]) => (
          <Row key={field} label={t(label)}>
            <ValueSlider
              label={t(label)}
              sliderClassName="data-horizontal:w-24"
              valueClassName="w-9 text-muted-foreground"
              value={value}
              min={minEm * typeSize}
              max={EDGE_REEL_EM_MAX * typeSize}
              step={1}
              format={(v) => String(Math.round(v))}
              parse={(t) => Number(t)}
              onDraft={(v) => writeEdge({ [field]: v > 0 ? v / typeSize : undefined })}
              onCommit={(v) => {
                writeEdge({ [field]: v > 0 ? v / typeSize : undefined });
                ck.end();
              }}
            />
          </Row>
        ))}
      {rolls && edgeOvershoot > 0 && (
        <Row label={t("settle")}>
          <ValueSlider
            label={t("settle")}
            sliderClassName="data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={edgeSettle}
            min={0.05}
            max={EDGE_SETTLE_MAX}
            step={0.01}
            format={(v) => `${Math.round(v * 100)}%`}
            parse={(t) => Number(t.replace("%", "")) / 100}
            onDraft={(v) => writeEdge({ settle: v })}
            onCommit={(v) => {
              writeEdge({ settle: v });
              ck.end();
            }}
          />
        </Row>
      )}
      {dives && (
        <Row label={t("anchor")}>
          <Switch
            checked={!!edgeAnchor}
            onCheckedChange={(v) => {
              writeEdge({ anchor: v ? { x: 0, y: 0 } : undefined });
              ck.end();
            }}
          />
        </Row>
      )}
      {dives &&
        edgeAnchor &&
        (
          [
            ["anchorX", "x"],
            ["anchorY", "y"],
          ] as const
        ).map(([label, axis]) => (
          <Row key={axis} label={t(label)}>
            <ValueSlider
              label={t(label)}
              sliderClassName="data-horizontal:w-24"
              valueClassName="w-9 text-muted-foreground"
              value={edgeAnchor[axis]}
              min={-EDGE_DISTANCE_MAX}
              max={EDGE_DISTANCE_MAX}
              step={1}
              format={(v) => String(Math.round(v))}
              parse={(t) => Number(t)}
              onDraft={(v) => writeEdge({ anchor: { ...edgeAnchor, [axis]: v } })}
              onCommit={(v) => {
                writeEdge({ anchor: { ...edgeAnchor, [axis]: v } });
                ck.end();
              }}
            />
          </Row>
        ))}
      {edge && (
        <Row label={t("blur")}>
          <ValueSlider
            label={t("blur")}
            sliderClassName="data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={edgeBlur}
            min={0}
            max={EDGE_BLUR_MAX}
            step={1}
            format={(v) => String(Math.round(v))}
            parse={(t) => Number(t)}
            onDraft={(v) => writeEdge({ blur: v })}
            onCommit={(v) => {
              writeEdge({ blur: v });
              ck.end();
            }}
          />
        </Row>
      )}
      {types && <CaretSettings overlay={o} peers={peers} />}
    </>
  );
}

/** Rotation and opacity, shared by every overlay kind. Neutral values store
 * as absence so untouched elements carry nothing. */
/** The element twin of the clip panels' Hidden row: parked on the timeline,
 * out of the played and exported picture. It closes the Transform section
 * (the effect panel, which has no Transform, mounts it alone), so the
 * timeline chip always has an inspector fallback. */
function HiddenRow({ overlay: o }: { overlay: Overlay }) {
  const t = useTranslations("inspector.clip");
  const update = useEditor((s) => s.updateOverlay);
  return (
    <Row label={t("hidden")}>
      <Switch
        checked={!!o.hidden}
        onCheckedChange={(v) => update(o.id, { hidden: v || undefined })}
      />
    </Row>
  );
}

/** X and Y as percentages of the frame, the pair of scrubs both the element
 * and the clip transform sections show. The range differs — an element stays
 * inside the frame, a keyed clip pans past it. */
function PositionRow({
  pose,
  min,
  max,
  ck,
  onSet,
}: {
  pose: { x: number; y: number };
  min: number;
  max: number;
  ck: { begin: () => void; end: () => void };
  onSet: (axis: "x" | "y", pct: number) => void;
}) {
  const t = useTranslations("inspector.transform");
  return (
    <Row label={t("position")}>
      {(["x", "y"] as const).map((axis) => (
        <span key={axis} className="flex items-center gap-1">
          <span className="text-[11px] text-muted-foreground/70 uppercase">{axis}</span>
          <ScrubValue
            label={t("axisPosition", { axis: axis.toUpperCase() })}
            className="w-9 text-muted-foreground"
            value={pose[axis] * 100}
            min={min}
            max={max}
            step={0.5}
            keyStep={1}
            snap={[50]}
            format={(v) => String(Math.round(v))}
            parse={parseNumberInput}
            onScrub={(v) => {
              ck.begin();
              onSet(axis, v);
            }}
            onCommit={(v) => {
              ck.begin();
              onSet(axis, v);
              ck.end();
            }}
          />
        </span>
      ))}
    </Row>
  );
}

/** Two numbers a key holds per axis — the stretch of each side, the tilt
 * about each axis — scrubbed side by side like Position. */
function KeyAxisRow({
  label,
  axes,
  min,
  max,
  snap,
  format,
  parse,
  ck,
}: {
  label: string;
  axes: { name: string; value: number; set: (v: number) => void }[];
  min: number;
  max: number;
  snap: number[];
  format: (v: number) => string;
  parse: (s: string) => number | null;
  ck: { begin: () => void; end: () => void };
}) {
  const t = useTranslations("inspector.transform");
  return (
    <Row label={label}>
      {axes.map((axis) => (
        <span key={axis.name} className="flex items-center gap-1">
          <span className="text-[11px] text-muted-foreground/70 uppercase">{axis.name}</span>
          <ScrubValue
            label={t("axisLabel", { label, axis: axis.name })}
            className="w-10 text-muted-foreground"
            value={axis.value}
            min={min}
            max={max}
            step={(max - min) / 400}
            keyStep={(max - min) / 80}
            snap={snap}
            format={format}
            parse={parse}
            onScrub={(v) => {
              ck.begin();
              axis.set(v);
            }}
            onCommit={(v) => {
              ck.begin();
              axis.set(v);
              ck.end();
            }}
          />
        </span>
      ))}
    </Row>
  );
}

/** One caption's own settings: where it sits, and which of its words are set
 * apart in the track's emphasis style (the Subtitles panel styles it). */
function CuePanel({ cue }: { cue: SubtitleCue }) {
  const t = useTranslations("inspector.cue");
  const subtitles = useEditor((s) => s.subtitles);
  const posCk = useSliderCheckpoint();
  const own = cue.x !== undefined && cue.y !== undefined;
  const pose = cueSpot(subtitles, cue);
  const setPos = (axis: "x" | "y", pct: number) => {
    const v = Math.min(0.98, Math.max(0.02, pct / 100));
    useEditor.getState().setCuePosition(cue.id, { ...pose, [axis]: v });
  };
  const words = displayWords(cue.text);
  const marked = new Set(cueEmphasis(cue));
  return (
    <div className="flex flex-col gap-1 px-3.5 pt-2 pb-4">
      <Section
        title={t("ownPosition")}
        info={t("ownPositionInfo")}
        enabled={own}
        onEnabledChange={(on) => {
          useEditor.getState().pushHistory();
          useEditor.getState().setCuePosition(cue.id, on ? cueSpot(subtitles, { lane: cue.lane }) : null);
        }}
      >
        <PositionRow pose={pose} min={2} max={98} ck={posCk} onSet={setPos} />
      </Section>
      <Section
        title={t("emphasis")}
        info={t("emphasisInfo")}
      >
        <div className="cue-emphasis flex flex-wrap gap-1 pb-1.5">
          {words.map((w, i) => (
            <button
              key={i}
              type="button"
              aria-pressed={marked.has(i)}
              className={cn(
                "rounded-md px-1.5 py-0.5 text-[12px] transition-colors",
                marked.has(i)
                  ? "bg-[#FFE94A]/80 font-semibold text-[#111114] italic"
                  : "bg-secondary/60 text-foreground hover:bg-secondary"
              )}
              onClick={() => useEditor.getState().setCueEmphasis([{ id: cue.id, indices: [i] }])}
            >
              {w}
            </button>
          ))}
        </div>
      </Section>
    </div>
  );
}

function TransformRows({ overlay: o }: { overlay: Overlay }) {
  const t = useTranslations("inspector.transform");
  const rotationCk = useSliderCheckpoint();
  const opacityCk = useSliderCheckpoint();
  const scaleCk = useSliderCheckpoint();
  const posCk = useSliderCheckpoint();
  const now = usePreviewTime();
  // With keys in play these rows edit the pose at the playhead rather than the
  // element's resting fields — which is what makes them a track.
  const keyed = hasOverlayKeys(o);
  const tLocal = localTimeOf(o, now);
  const pose = poseAt(o, tLocal);
  const keyPose = keyPoseAt(o, tLocal);
  const stretchCk = useSliderCheckpoint();
  const tiltCk = useSliderCheckpoint();
  const setKey = (patch: Partial<Omit<OverlayKey, "t">>) =>
    useEditor.getState().setOverlayKey(o.id, tLocal, patch, { transient: true });
  const setRotation = (v: number) => {
    const deg = tenthDeg(v);
    if (keyed) return setKey({ rotation: deg });
    useEditor.getState().updateOverlayTransient(o.id, { rotation: deg === 0 ? undefined : deg });
  };
  const setOpacity = (v: number) => {
    const a = Math.max(0, Math.min(1, v));
    if (keyed) return setKey({ opacity: a });
    useEditor.getState().updateOverlayTransient(o.id, { opacity: a >= 0.995 ? undefined : a });
  };
  // Position reads as a percentage of the frame, which is what the document
  // stores — an element sits in the same spot at any aspect, and the number
  // means the same thing on a square as on a widescreen.
  const clampPos = keyed ? clampKeyPos : clampOverlayPos;
  const setPos = (axis: "x" | "y", pct: number) => {
    const v = clampPos(pct / 100, o);
    if (keyed) return setKey({ [axis]: v });
    useEditor.getState().updateOverlayTransient(o.id, { [axis]: v });
  };
  return (
    <Section title={t("title")}>
      <KeyframeControls overlay={o} />
      <PositionRow pose={pose} min={clampPos(-Infinity, o) * 100} max={clampPos(Infinity, o) * 100} ck={posCk} onSet={setPos} />
      {keyed && (
        <Row label={t("scale")}>
          <ValueSlider
            label={t("scale")}
            sliderClassName="data-horizontal:w-20"
            valueClassName="w-12 text-muted-foreground"
            value={keyPose.scale}
            min={0.1}
            max={4}
            // The slider stays fine-grained where most work happens; the
            // readout scrubs and types past it, because a title that zooms
            // until one glyph fills the frame is tens of times its own size.
            scrubMin={0.01}
            scrubMax={Infinity}
            step={0.01}
            snap={[1]}
            keyStep={0.05}
            format={(v) => `${Math.round(v * 100)}%`}
            parse={parsePercentInput}
            onDraft={(v) => {
              scaleCk.begin();
              setKey({ scale: v });
            }}
            onCommit={(v) => {
              scaleCk.begin();
              setKey({ scale: v });
              scaleCk.end();
            }}
          />
        </Row>
      )}
      {keyed && (
        <KeyAxisRow
          label={t("stretch")}
          axes={[
            { name: "W", value: keyPose.scaleX ?? 1, set: (v) => setKey({ scaleX: v }) },
            { name: "H", value: keyPose.scaleY ?? 1, set: (v) => setKey({ scaleY: v }) },
          ]}
          min={0}
          max={4}
          snap={[1]}
          format={(v) => `${Math.round(v * 100)}%`}
          parse={parsePercentInput}
          ck={stretchCk}
        />
      )}
      {keyed && (
        <KeyAxisRow
          label={t("tilt")}
          axes={[
            { name: "X", value: keyPose.tiltX ?? 0, set: (v) => setKey({ tiltX: Math.round(v) }) },
            { name: "Y", value: keyPose.tiltY ?? 0, set: (v) => setKey({ tiltY: Math.round(v) }) },
          ]}
          min={-TILT_MAX}
          max={TILT_MAX}
          snap={[0]}
          format={(v) => `${Math.round(v)}°`}
          parse={parseNumberInput}
          ck={tiltCk}
        />
      )}
      <Row label={t("rotation")}>
        <ValueSlider
          label={t("rotation")}
          sliderClassName="data-horizontal:w-24"
          valueClassName="w-9 text-muted-foreground"
          value={keyed ? pose.rotation : (o.rotation ?? 0)}
          min={-180}
          max={180}
          step={0.1}
          keyStep={1}
          snap={[-90, 0, 90]}
          format={formatDeg}
          parse={parseNumberInput}
          onDraft={(v) => {
            rotationCk.begin();
            setRotation(v);
          }}
          onCommit={(v) => {
            rotationCk.begin();
            setRotation(v);
            rotationCk.end();
          }}
        />
      </Row>
      <Row label={t("opacity")}>
        <ValueSlider
          label={t("opacity")}
          sliderClassName="data-horizontal:w-24"
          valueClassName="w-9 text-muted-foreground"
          value={keyed ? pose.opacity : (o.opacity ?? 1)}
          min={0}
          max={1}
          step={0.01}
          format={(v) => String(Math.round(v * 100))}
          parse={parsePercentInput}
          onDraft={(v) => {
            opacityCk.begin();
            setOpacity(v);
          }}
          onCommit={(v) => {
            opacityCk.begin();
            setOpacity(v);
            opacityCk.end();
          }}
        />
      </Row>
      <ElementMotionRows overlay={o} />
      <HiddenRow overlay={o} />
    </Section>
  );
}

/** Seconds into the element at the playhead, clamped to its own window. */
function localTimeOf(o: { start: number; end: number }, now: number): number {
  return Math.max(0, Math.min(now - o.start, Math.max(0.1, o.end - o.start)));
}

/**
 * The keyframe track: the first row of Transform, because a key holds exactly
 * what the rows under it show. The diamond stores that pose where the playhead
 * stands, the arrows walk the keys already set, and the bin drops the one under
 * the playhead. A key has no form of its own — it is edited by moving the
 * element or pulling those same rows.
 */
function KeyframeControls({ overlay: o }: { overlay: Overlay }) {
  const now = usePreviewTime();
  const seek = useEditor((s) => s.seek);
  const st = () => useEditor.getState();
  return (
    <>
      <KeyRow
        element={o}
        now={now}
        keys={o.kf ?? []}
        onAdd={(tLocal) => st().setOverlayKey(o.id, tLocal)}
        onRemove={(tLocal) => st().removeOverlayKey(o.id, tLocal)}
        onSeek={seek}
      />
      <TrackRow id={o.id} use="follow" />
    </>
  );
}

/** The key track row itself — diamond, walkers, count, bin — over whichever
 * key list it is handed. The pose track and the mask track both mount it;
 * the mask track's diamond wears the timeline's amber so the two tracks
 * read apart everywhere. */
export function KeyRow({
  element,
  now,
  keys,
  track = "pose",
  onAdd,
  onRemove,
  onSeek,
}: {
  element: { start: number; end: number };
  now: number;
  keys: { t: number }[];
  track?: "pose" | "mask";
  onAdd: (tLocal: number) => void;
  onRemove: (tLocal: number) => void;
  onSeek: (t: number) => void;
}) {
  const tr = useTranslations("inspector.keys");
  const inWindow = now >= element.start - 1e-6 && now <= element.end + 1e-6;
  const tLocal = Math.max(
    0,
    Math.min(now - element.start, Math.max(0.1, element.end - element.start))
  );
  const here = keyIndexAt(keys, tLocal);
  const prev = [...keys].sort((a, b) => a.t - b.t).reverse().find((k) => k.t < tLocal - KEY_EPSILON);
  const next = [...keys].sort((a, b) => a.t - b.t).find((k) => k.t > tLocal + KEY_EPSILON);
  return (
    <Row label={tr("title")}>
      <Button
        size="sm"
        variant="ghost"
        className="size-7 p-0"
        disabled={!inWindow}
        title={here >= 0 ? tr("update") : tr("add")}
        aria-label={here >= 0 ? tr("update") : tr("add")}
        onClick={() => onAdd(tLocal)}
      >
        <Diamond
          className={cn(
            "size-3.5",
            track === "mask" && "text-[#ff9f0a]",
            here >= 0 && "fill-current"
          )}
        />
      </Button>
      <Button
        size="sm"
        variant="ghost"
        className="size-7 p-0"
        disabled={!prev}
        title={tr("previous")}
        aria-label={tr("previous")}
        onClick={() => prev && onSeek(element.start + prev.t)}
      >
        <ChevronLeft className="size-3.5" />
      </Button>
      <Button
        size="sm"
        variant="ghost"
        className="size-7 p-0"
        disabled={!next}
        title={tr("next")}
        aria-label={tr("next")}
        onClick={() => next && onSeek(element.start + next.t)}
      >
        <ChevronRight className="size-3.5" />
      </Button>
      {keys.length > 0 && <Value className="text-muted-foreground">{keys.length}</Value>}
      <Button
        size="sm"
        variant="ghost"
        // Icons centre in a 28px box; the value columns below run to the panel
        // edge. The pull-right lands this glyph on the same edge as their text.
        className="-mr-1.5 size-7 p-0 text-muted-foreground"
        disabled={here < 0}
        title={tr("remove")}
        aria-label={tr("remove")}
        onClick={() => onRemove(tLocal)}
      >
        <Trash2 className="size-3.5" />
      </Button>
    </Row>
  );
}

/** A mask kind's picker icon, drawn from the same outline the stage gizmo
 * traces, so the tile shows the shape the mask cuts. A linear edge keeps its
 * top half, a mirror its band; the person matte wears a figure. */
function MaskShapeIcon({ kind }: { kind: MaskKind }) {
  if (kind === "subject") return <User className="size-[18px]" strokeWidth={1.75} />;
  if (kind === "pen") return <PenTool className="size-[18px]" strokeWidth={1.75} />;
  const d = maskOutlinePathD({ kind }, 15, kind === "square" ? 15 : 12, 12, 2.5);
  return (
    <svg viewBox="-10 -10 20 20" className="size-[18px]" fill="none" stroke="currentColor" strokeWidth={1.5}>
      {kind === "linear" && <path d="M-9 -8 L9 -3 V-9 H-9 Z" fill="currentColor" opacity={0.3} stroke="none" />}
      {kind === "mirror" && <path d="M-9 -7 L9 -4 V4 L-9 7 Z" fill="currentColor" opacity={0.3} stroke="none" />}
      {kind === "linear" ? (
        <path d="M-9 -8 L9 -3" strokeDasharray="2.5 1.5" />
      ) : kind === "mirror" ? (
        <path d="M-9 -7 L9 -4 M-9 7 L9 4" strokeDasharray="2.5 1.5" />
      ) : (
        <path d={d} strokeLinejoin="round" />
      )}
    </svg>
  );
}

/** How a panel's mask section reads and writes its owner's mask — the same
 * section serves overlay elements and video clips through this. */
interface MaskTarget {
  /** The masked clip or overlay, for the panel's memory of the section. */
  id: string;
  /** Timeline window for the keyframe row and playhead-local time. */
  element: { start: number; end: number };
  mask?: Mask;
  /** Picking Subject starts inverted — behind the person. Elements set this:
   * a shape or title masked by the person is almost always meant to sit
   * behind them, and the Invert toggle flips it to on-person. Clips keep the
   * plain direction, where Subject means keep the person. */
  subjectStartsBehind?: boolean;
  /** Replace the mask outright (or remove it), as one undo step. */
  set: (mask: Mask | undefined) => void;
  /** Live-drag mask update, no undo entry. */
  setTransient: (mask: Mask) => void;
  setKey: (
    tLocal: number,
    patch?: Partial<Omit<MaskKey, "t">>,
    opts?: { transient?: boolean }
  ) => void;
  removeKey: (tLocal: number) => void;
}

/**
 * A video clip's pose track: the keyframe row plus, once keys exist, the
 * position/scale/rotation/opacity rows editing the key at the playhead — the
 * element Transform contract over the clip's anchor. A clip with no keys
 * rests in its region, so the rows appear with the first key.
 */
function ClipTransformSection({ clip }: { clip: VideoClip }) {
  const tr = useTranslations("inspector.transform");
  const clips = useEditor((s) => s.clips);
  const assets = useEditor((s) => s.assets);
  const now = usePreviewTime();
  const seek = useEditor((s) => s.seek);
  const posCk = useSliderCheckpoint();
  const scaleCk = useSliderCheckpoint();
  const rotationCk = useSliderCheckpoint();
  const opacityCk = useSliderCheckpoint();
  const st = () => useEditor.getState();
  const win = clipWindow(clips, assets, clip.id);
  if (!win) return null;
  const el = { start: win.start, end: win.start + win.len };
  const tLocal = localTimeOf(el, now);
  const keyed = clipKeyed(clip);
  const pose = clipPoseAt(clip, tLocal);
  const setKey = (patch: Partial<Omit<OverlayKey, "t">>) =>
    st().setClipKey(clip.id, tLocal, patch, { transient: true });
  return (
    <Section title={tr("title")}>
      <KeyRow
        element={el}
        now={now}
        keys={clip.kf ?? []}
        onAdd={(t) => st().setClipKey(clip.id, t)}
        onRemove={(t) => st().removeClipKey(clip.id, t)}
        onSeek={seek}
      />
      <TrackRow id={clip.id} use="follow" />
      {keyed && (
        <>
          <PositionRow
            pose={pose}
            min={-50}
            max={150}
            ck={posCk}
            onSet={(axis, pct) => setKey({ [axis]: pct / 100 })}
          />
          <Row label={tr("scale")}>
            <ValueSlider
              label={tr("scale")}
              sliderClassName="data-horizontal:w-24"
              valueClassName="w-9 text-muted-foreground"
              value={pose.scale}
              min={0.1}
              max={4}
              step={0.01}
              snap={[1]}
              keyStep={0.05}
              format={(v) => `${Math.round(v * 100)}%`}
              parse={parsePercentInput}
              onDraft={(v) => {
                scaleCk.begin();
                setKey({ scale: v });
              }}
              onCommit={(v) => {
                scaleCk.begin();
                setKey({ scale: v });
                scaleCk.end();
              }}
            />
          </Row>
          <Row label={tr("rotation")}>
            <ValueSlider
              label={tr("rotation")}
              sliderClassName="data-horizontal:w-24"
              valueClassName="w-9 text-muted-foreground"
              value={pose.rotation}
              min={-180}
              max={180}
              step={0.1}
              keyStep={1}
              snap={[-90, 0, 90]}
              format={formatDeg}
              parse={parseNumberInput}
              onDraft={(v) => {
                rotationCk.begin();
                setKey({ rotation: tenthDeg(v) });
              }}
              onCommit={(v) => {
                rotationCk.begin();
                setKey({ rotation: tenthDeg(v) });
                rotationCk.end();
              }}
            />
          </Row>
          <Row label={tr("opacity")}>
            <ValueSlider
              label={tr("opacity")}
              sliderClassName="data-horizontal:w-24"
              valueClassName="w-9 text-muted-foreground"
              value={pose.opacity}
              min={0}
              max={1}
              step={0.01}
              format={(v) => String(Math.round(v * 100))}
              parse={parsePercentInput}
              onDraft={(v) => {
                opacityCk.begin();
                setKey({ opacity: v });
              }}
              onCommit={(v) => {
                opacityCk.begin();
                setKey({ opacity: v });
                opacityCk.end();
              }}
            />
          </Row>
        </>
      )}
      <ClipMotionRows clip={clip} tLocal={tLocal} />
    </Section>
  );
}

/** The overlay inspector's mask target, over the overlay store actions. */
function OverlayMaskSection({ overlay: o }: { overlay: Overlay }) {
  const st = () => useEditor.getState();
  return (
    <MaskSection
      target={{
        id: o.id,
        element: o,
        mask: o.mask,
        subjectStartsBehind: true,
        set: (mask) => st().updateOverlay(o.id, { mask }),
        setTransient: (mask) => st().updateOverlayTransient(o.id, { mask }),
        setKey: (t, patch, opts) => st().setOverlayMaskKey(o.id, t, patch, opts),
        removeKey: (t) => st().removeOverlayMaskKey(o.id, t),
      }}
    />
  );
}

/** The clip inspector's mask target, over the clip store actions. The clip's
 * timeline window comes through `clipWindow` (track-0 starts derive from the
 * span layout). */
/** Rounded corners and a border stroke on the clip's box. The section's
 * switch turns the style on with visible defaults; off returns the clip to a
 * plain box. */
function ClipBorderSection({ clip }: { clip: VideoClip }) {
  const t = useTranslations("inspector.box");
  const widthCk = useSliderCheckpoint();
  const radiusCk = useSliderCheckpoint();
  const bs = clip.boxStyle;
  const st = () => useEditor.getState();
  const write = (patch: Partial<BoxStyle>) =>
    st().updateClipTransient(clip.id, { boxStyle: { ...st().clips.find((c) => c.id === clip.id)?.boxStyle, ...patch } });
  return (
    <Section
      title={t("border")}
      info={t("borderInfo")}
      enabled={!!bs}
      onEnabledChange={(v) =>
        st().updateClip(clip.id, {
          boxStyle: v ? { radius: 16, borderWidth: 6, borderColor: "#FFFFFF" } : undefined,
        })
      }
    >
      {bs && (
        <>
          <Row label={t("width")}>
            <ScrubValue
              label={t("borderWidth")}
              className="w-9 text-muted-foreground"
              value={bs.borderWidth ?? 0}
              min={0}
              max={60}
              step={1}
              format={(v) => String(Math.round(v))}
              parse={parseNumberInput}
              onScrub={(v) => {
                widthCk.begin();
                write({ borderWidth: v });
              }}
              onCommit={(v) => {
                widthCk.begin();
                write({ borderWidth: v });
                widthCk.end();
              }}
            />
          </Row>
          <Row label={t("radius")}>
            <ScrubValue
              label={t("cornerRadius")}
              className="w-9 text-muted-foreground"
              value={bs.radius ?? 0}
              min={0}
              max={200}
              step={1}
              format={(v) => String(Math.round(v))}
              parse={parseNumberInput}
              onScrub={(v) => {
                radiusCk.begin();
                write({ radius: v });
              }}
              onCommit={(v) => {
                radiusCk.begin();
                write({ radius: v });
                radiusCk.end();
              }}
            />
          </Row>
          <Row label={t("color")}>
            <ColorField
              value={bs.borderColor ?? "#FFFFFF"}
              label={t("borderColor")}
              onBegin={() => st().pushHistory()}
              onLive={(c) => write({ borderColor: c })}
              onCommit={(c) => st().updateClip(clip.id, { boxStyle: { ...bs, borderColor: c } })}
            />
          </Row>
        </>
      )}
    </Section>
  );
}

/** The clip's drop shadow: cast by whatever shape the clip really shows — the
 * box, its rounded corners, and its mask together. */
function ClipShadowSection({ clip }: { clip: VideoClip }) {
  const t = useTranslations("inspector.box");
  const blurCk = useSliderCheckpoint();
  const offsetCk = useSliderCheckpoint();
  const opacityCk = useSliderCheckpoint();
  const st = () => useEditor.getState();
  const sh = clip.boxStyle?.shadow;
  const write = (patch: Partial<ClipShadow>) => {
    const cur = st().clips.find((c) => c.id === clip.id)?.boxStyle;
    st().updateClipTransient(clip.id, {
      boxStyle: { ...cur, shadow: { blur: cur?.shadow?.blur ?? 24, ...cur?.shadow, ...patch } },
    });
  };
  return (
    <Section
      title={t("shadow")}
      info={t("shadowInfo")}
      enabled={!!sh}
      onEnabledChange={(v) =>
        st().updateClip(clip.id, {
          boxStyle: v
            ? { ...clip.boxStyle, shadow: { blur: 24, y: 12 } }
            : clip.boxStyle?.radius || clip.boxStyle?.borderWidth
              ? { ...clip.boxStyle, shadow: undefined }
              : undefined,
        })
      }
    >
      {sh && (
        <>
          <Row label={t("blur")}>
            <ScrubValue
              label={t("shadowBlur")}
              className="w-9 text-muted-foreground"
              value={sh.blur}
              min={0}
              max={120}
              step={1}
              format={(v) => String(Math.round(v))}
              parse={parseNumberInput}
              onScrub={(v) => {
                blurCk.begin();
                write({ blur: v });
              }}
              onCommit={(v) => {
                blurCk.begin();
                write({ blur: v });
                blurCk.end();
              }}
            />
          </Row>
          <Row label={t("offset")}>
            {(["x", "y"] as const).map((axis) => (
              <span key={axis} className="flex items-center gap-1">
                <span className="text-[11px] text-muted-foreground/70 uppercase">{axis}</span>
                <ScrubValue
                  label={t("shadowOffset", { axis: axis.toUpperCase() })}
                  className="w-9 text-muted-foreground"
                  value={sh[axis] ?? 0}
                  min={-120}
                  max={120}
                  step={1}
                  format={(v) => String(Math.round(v))}
                  parse={parseNumberInput}
                  onScrub={(v) => {
                    offsetCk.begin();
                    write({ [axis]: Math.round(v) || undefined });
                  }}
                  onCommit={(v) => {
                    offsetCk.begin();
                    write({ [axis]: Math.round(v) || undefined });
                    offsetCk.end();
                  }}
                />
              </span>
            ))}
          </Row>
          <Row label={t("opacity")}>
            <ValueSlider
              label={t("shadowOpacity")}
              sliderClassName="data-horizontal:w-24"
              valueClassName="w-9 text-muted-foreground"
              value={sh.opacity ?? 0.35}
              min={0}
              max={1}
              step={0.01}
              format={formatPercent}
              parse={parsePercentInput}
              onDraft={(v) => {
                opacityCk.begin();
                write({ opacity: v });
              }}
              onCommit={(v) => {
                opacityCk.begin();
                write({ opacity: v });
                opacityCk.end();
              }}
            />
          </Row>
          <Row label={t("color")}>
            <ColorField
              value={sh.color ?? "#000000"}
              label={t("shadowColor")}
              onBegin={() => st().pushHistory()}
              onLive={(c) => write({ color: c })}
              onCommit={(c) => write({ color: c })}
            />
          </Row>
        </>
      )}
    </Section>
  );
}

function ClipMaskSection({ clip }: { clip: VideoClip }) {
  const clips = useEditor((s) => s.clips);
  const assets = useEditor((s) => s.assets);
  const st = () => useEditor.getState();
  const win = clipWindow(clips, assets, clip.id);
  if (!win) return null;
  return (
    <MaskSection
      target={{
        id: clip.id,
        element: { start: win.start, end: win.start + win.len },
        mask: clip.mask,
        set: (mask) => st().updateClip(clip.id, { mask }),
        setTransient: (mask) => st().updateClipTransient(clip.id, { mask }),
        setKey: (t, patch, opts) => st().setClipMaskKey(clip.id, t, patch, opts),
        removeKey: (t) => st().removeClipMaskKey(clip.id, t),
      }}
    />
  );
}

/**
 * The mask itself: shape picker, its own keyframe track, and the geometry
 * rows. With mask keys in play the rows edit the key at the playhead, the
 * same contract as Transform; otherwise they edit the mask's resting fields.
 */
function MaskSection({ target }: { target: MaskTarget }) {
  const tr = useTranslations("inspector.mask");
  const now = usePreviewTime();
  const seek = useEditor((s) => s.seek);
  const posCk = useSliderCheckpoint();
  const sizeCk = useSliderCheckpoint();
  const rotationCk = useSliderCheckpoint();
  const featherCk = useSliderCheckpoint();
  const radiusCk = useSliderCheckpoint();
  // Size link: scrubbing one axis carries the other so the shape keeps its
  // pixel proportions. On for a circle, which starts round.
  const [linked, setLinked] = usePanelState<boolean | null>(target.id, "maskLinked", null);
  const m = target.mask;
  const tLocal = localTimeOf(target.element, now);
  const geom = m ? maskFrameAt(m, tLocal) : null;
  const sizeLinked = linked ?? m?.kind === "circle";
  const writeGeom = (patch: Partial<Omit<MaskKey, "t">>) => {
    if (!m) return;
    if (hasMaskKeys(m)) return target.setKey(tLocal, patch, { transient: true });
    // A zero radius is no radius on the resting mask.
    const next = { ...m, ...patch };
    if (patch.radius === 0) delete next.radius;
    target.setTransient(next);
  };
  // One axis moves, the other follows at the current pixel ratio.
  const writeSize = (axis: "w" | "h", v: number) => {
    if (!geom || !sizeLinked || sizeAxes.length < 2) return writeGeom({ [axis]: v });
    const fr = frameOf(useEditor.getState().aspect);
    const ratio = (geom.h * fr.h) / Math.max(1e-6, geom.w * fr.w);
    if (axis === "w") return writeGeom({ w: v, h: Math.min(2, Math.max(0.01, (v * fr.w * ratio) / fr.h)) });
    writeGeom({ h: v, w: Math.min(2, Math.max(0.01, (v * fr.h) / ratio / fr.w)) });
  };
  const sizeAxes = m ? maskSizeAxes(m.kind) : [];
  const subject = m?.kind === "subject";
  // A pen outline still being drawn has no geometry to edit yet.
  const drawing = !!m && m.kind === "pen" && !penClosed(m);
  // A pen mask starts over: the outline goes, and the box returns to the
  // frame so the next drawing lands where the clicks fall.
  const redraw = () => {
    if (!m) return;
    target.set({ kind: "pen", invert: m.invert, feather: m.feather });
  };
  // A circle at rest is round: w and h are fractions of different frame
  // edges, so equal pixels means unequal fractions.
  const roundCircle = (w: number) => {
    const fr = frameOf(useEditor.getState().aspect);
    return { w, h: (w * fr.w) / fr.h };
  };
  // Reset puts the geometry back where a fresh mask starts — centered, half
  // frame, upright, hard-edged, square-cornered — keeping the kind, the
  // invert and any keys: with keys the default lands on the key at the
  // playhead.
  const reset = () => {
    if (!m) return;
    const rest = restingMaskFrame({ kind: m.kind });
    const geom = m.kind === "circle" ? { ...rest, ...roundCircle(rest.w) } : rest;
    if (hasMaskKeys(m)) {
      target.set({ ...m, radius: undefined });
      target.setKey(tLocal, geom, { transient: true });
      return;
    }
    setLinked(null);
    target.set({ kind: m.kind, invert: m.invert, kf: m.kf, points: m.points, ...(subject ? {} : geom) });
  };
  return (
    <Section
      title={tr("title")}
      info={tr("info")}
      enabled={!!m}
      onEnabledChange={(v) => target.set(v ? { kind: "rect" } : undefined)}
      aside={
        m && !subject ? (
          <Button
            variant="ghost"
            size="sm"
            className="h-7 px-2 text-[12px] text-muted-foreground"
            onClick={m.kind === "pen" ? redraw : reset}
            disabled={drawing}
          >
            {m.kind === "pen" ? tr("redraw") : tr("reset")}
          </Button>
        ) : undefined
      }
    >
      {m && geom && (
        <>
          <div className="grid grid-cols-4 gap-1.5 py-1" role="radiogroup" aria-label={tr("shape")}>
            {MASK_SHAPES.map((s) => (
              <button
                key={s.id}
                type="button"
                role="radio"
                aria-checked={m.kind === s.id}
                title={tr(`shapes.${s.id}`)}
                className={cn(
                  "flex flex-col items-center gap-1 rounded-md border px-1 pb-1 pt-2 text-[10px] leading-none transition-colors",
                  m.kind === s.id
                    ? "border-primary bg-primary/10 text-foreground"
                    : "border-transparent bg-muted/60 text-muted-foreground hover:bg-muted hover:text-foreground"
                )}
                onClick={() => {
                  const kind = s.id;
                  if (kind === m.kind) return;
                  // A fresh circle starts perfectly round: w and h are frame
                  // fractions, so equal pixels means unequal fractions. The
                  // size link and ⇧-drag on the stage keep it round after.
                  // Pen is drawn fresh over the frame, so its box starts as
                  // the frame; leaving it drops the outline.
                  if (kind === "pen") return redraw();
                  const patch =
                    kind === "circle" && !hasMaskKeys(m)
                      ? roundCircle(m.w ?? 0.5)
                      : kind === "subject" && m.kind !== "subject" && target.subjectStartsBehind
                        ? { invert: true }
                        : {};
                  const rest = { ...m };
                  delete rest.points;
                  target.set({ ...rest, ...patch, kind });
                }}
              >
                <MaskShapeIcon kind={s.id} />
                <span className="w-full truncate text-center">{tr(`shapes.${s.id}`)}</span>
              </button>
            ))}
          </div>
          {!subject && !drawing && <TrackRow id={target.id} use="mask" />}
          {drawing && (
            <p className="px-1 py-1.5 text-[11.5px] leading-snug text-muted-foreground">
              {tr("penHint")}
            </p>
          )}
          {!subject && !drawing && (
            <KeyRow
              element={target.element}
              now={now}
              keys={m.kf ?? []}
              track="mask"
              onAdd={(t) => target.setKey(t)}
              onRemove={(t) => target.removeKey(t)}
              onSeek={seek}
            />
          )}
          {!subject && !drawing && (
            <Row label={tr("position")}>
              {(["x", "y"] as const).map((axis) => (
                <span key={axis} className="flex items-center gap-1">
                  <span className="text-[11px] text-muted-foreground/70 uppercase">{axis}</span>
                  <ScrubValue
                    label={tr("axisOffset", { axis: axis.toUpperCase() })}
                    className="w-9 text-muted-foreground"
                    value={geom[axis] * 100}
                    min={-100}
                    max={100}
                    step={0.5}
                    keyStep={1}
                    snap={[0]}
                    format={(v) => String(Math.round(v))}
                    parse={parseNumberInput}
                    onScrub={(v) => {
                      posCk.begin();
                      writeGeom({ [axis]: v / 100 });
                    }}
                    onCommit={(v) => {
                      posCk.begin();
                      writeGeom({ [axis]: v / 100 });
                      posCk.end();
                    }}
                  />
                </span>
              ))}
            </Row>
          )}
          {sizeAxes.length > 0 && !drawing && (
            <Row label={tr("size")}>
              {sizeAxes.map((axis, i) => (
                <span key={axis} className="flex items-center gap-1">
                  {i === 1 && (
                    <Button
                      variant="ghost"
                      size="icon"
                      className={cn("size-6", sizeLinked ? "text-foreground" : "text-muted-foreground/60")}
                      aria-label={sizeLinked ? tr("unlinkSize") : tr("linkSize")}
                      aria-pressed={sizeLinked}
                      title={sizeLinked ? tr("sizesLinked") : tr("sizesFree")}
                      onClick={() => setLinked(!sizeLinked)}
                    >
                      {sizeLinked ? <Link2 className="size-3.5" /> : <Link2Off className="size-3.5" />}
                    </Button>
                  )}
                  <span className="text-[11px] text-muted-foreground/70 uppercase">{axis}</span>
                  <ScrubValue
                    label={axis === "w" ? tr("width") : tr("height")}
                    className="w-9 text-muted-foreground"
                    value={geom[axis] * 100}
                    min={1}
                    max={200}
                    step={1}
                    snap={[100]}
                    format={(v) => String(Math.round(v))}
                    parse={parseNumberInput}
                    onScrub={(v) => {
                      sizeCk.begin();
                      writeSize(axis, v / 100);
                    }}
                    onCommit={(v) => {
                      sizeCk.begin();
                      writeSize(axis, v / 100);
                      sizeCk.end();
                    }}
                  />
                </span>
              ))}
            </Row>
          )}
          {!subject && !drawing && (
            <Row label={tr("rotation")}>
              <ValueSlider
                label={tr("maskRotation")}
                sliderClassName="data-horizontal:w-24"
                valueClassName="w-9 text-muted-foreground"
                value={geom.rotation}
                min={-180}
                max={180}
                step={0.1}
                keyStep={1}
                snap={[-90, 0, 90]}
                format={formatDeg}
                parse={parseNumberInput}
                onDraft={(v) => {
                  rotationCk.begin();
                  writeGeom({ rotation: tenthDeg(v) });
                }}
                onCommit={(v) => {
                  rotationCk.begin();
                  writeGeom({ rotation: tenthDeg(v) });
                  rotationCk.end();
                }}
              />
            </Row>
          )}
          {!drawing && (
          <Row label={tr("feather")}>
            <ValueSlider
              label={tr("feather")}
              sliderClassName="data-horizontal:w-24"
              valueClassName="w-9 text-muted-foreground"
              value={geom.feather}
              min={0}
              max={MASK_FEATHER_MAX}
              step={1}
              format={(v) => String(Math.round(v))}
              parse={parseNumberInput}
              onDraft={(v) => {
                featherCk.begin();
                writeGeom({ feather: Math.round(v) });
              }}
              onCommit={(v) => {
                featherCk.begin();
                writeGeom({ feather: Math.round(v) });
                featherCk.end();
              }}
            />
          </Row>
          )}
          {maskHasRadius(m.kind) && (
            <Row label={tr("radius")}>
              <ValueSlider
                label={tr("cornerRadius")}
                sliderClassName="data-horizontal:w-24"
                valueClassName="w-9 text-muted-foreground"
                value={geom.radius}
                min={0}
                max={MASK_RADIUS_MAX}
                step={1}
                format={(v) => String(Math.round(v))}
                parse={parseNumberInput}
                onDraft={(v) => {
                  radiusCk.begin();
                  writeGeom({ radius: Math.round(v) });
                }}
                onCommit={(v) => {
                  radiusCk.begin();
                  writeGeom({ radius: Math.round(v) });
                  radiusCk.end();
                }}
              />
            </Row>
          )}
          {!drawing && (
            <Row label={tr("invert")}>
              <Switch
                checked={!!m.invert}
                onCheckedChange={(v) => target.set({ ...m, invert: v || undefined })}
                aria-label={tr("invertMask")}
              />
            </Row>
          )}
        </>
      )}
    </Section>
  );
}

function ShapePanel({ overlay: o }: { overlay: ShapeOverlay }) {
  const t = useTranslations("inspector.shape");
  const update = useEditor((s) => s.updateOverlay);
  const fillCk = useSliderCheckpoint();
  const radiusCk = useSliderCheckpoint();
  const strokeCk = useSliderCheckpoint();
  const marks = dealsMarks(o.shape);
  const boxShape = !lineLikeShape(o.shape) && !marks;
  return (
    <>
      <ElementTitle overlay={o} />
      <div className="flex flex-col gap-1 px-3.5 pb-4">
        <Row label={boxShape ? t("fill") : t("color")}>
          <ColorField
            value={o.fill}
            label={boxShape ? t("fillColor") : t("shapeColor")}
            onBegin={() => useEditor.getState().pushHistory()}
            onLive={(c) => useEditor.getState().updateOverlayTransient(o.id, { fill: c })}
            onCommit={(c) => update(o.id, { fill: c })}
            opacity={
              boxShape
                ? {
                    label: t("fillOpacity"),
                    value: o.fillOpacity ?? 1,
                    onDraft: (v) => {
                      fillCk.begin();
                      useEditor.getState().updateOverlayTransient(o.id, {
                        fillOpacity: v >= 0.995 ? undefined : v,
                      });
                    },
                    onCommit: (v) => {
                      fillCk.begin();
                      useEditor.getState().updateOverlayTransient(o.id, {
                        fillOpacity: v >= 0.995 ? undefined : v,
                      });
                      fillCk.end();
                    },
                  }
                : undefined
            }
          />
        </Row>
        {o.shape === "rect" && (
          <Row label={t("cornerRadius")}>
            <ValueSlider
              label={t("cornerRadius")}
              sliderClassName="data-horizontal:w-24"
              valueClassName="w-9 text-muted-foreground"
              value={o.radius ?? 0}
              min={0}
              max={120}
              step={1}
              format={(v) => String(Math.round(v))}
              parse={parseNumberInput}
              onDraft={(v) => {
                radiusCk.begin();
                const radius = Math.round(v);
                useEditor.getState().updateOverlayTransient(o.id, {
                  radius: radius === 0 ? undefined : radius,
                });
              }}
              onCommit={(v) => {
                radiusCk.begin();
                const radius = Math.round(v);
                useEditor.getState().updateOverlayTransient(o.id, {
                  radius: radius === 0 ? undefined : radius,
                });
                radiusCk.end();
              }}
            />
          </Row>
        )}
        {boxShape && (
          <Section
            title={t("outline")}
            enabled={!!o.stroke}
            onEnabledChange={(v) =>
              update(o.id, { stroke: v ? { color: "#111114", width: 6 } : undefined })
            }
          >
            {o.stroke && (
              <>
                <Row label={t("color")}>
                  <ColorField
                    value={o.stroke.color}
                    label={t("outlineColor")}
                    onBegin={() => useEditor.getState().pushHistory()}
                    onLive={(c) =>
                      useEditor.getState().updateOverlayTransient(o.id, {
                        stroke: { ...o.stroke!, color: c },
                      })
                    }
                    onCommit={(c) => update(o.id, { stroke: { ...o.stroke!, color: c } })}
                  />
                </Row>
                <Row label={t("width")}>
                  <ValueSlider
                    label={t("outlineWidth")}
                    sliderClassName="data-horizontal:w-24"
                    valueClassName="w-9 text-muted-foreground"
                    value={o.stroke.width}
                    min={1}
                    max={40}
                    step={1}
                    snap={[6]}
                    format={(v) => String(Math.round(v))}
                    parse={parseNumberInput}
                    onDraft={(v) => {
                      strokeCk.begin();
                      useEditor.getState().updateOverlayTransient(o.id, {
                        stroke: { ...o.stroke!, width: Math.round(v) },
                      });
                    }}
                    onCommit={(v) => {
                      strokeCk.begin();
                      useEditor.getState().updateOverlayTransient(o.id, {
                        stroke: { ...o.stroke!, width: Math.round(v) },
                      });
                      strokeCk.end();
                    }}
                  />
                </Row>
              </>
            )}
          </Section>
        )}
        {boxShape && <PatternSection overlay={o} />}
        {marks && <InksRow overlay={o} />}
        <ShadowSection id={o.id} shadow={o.shadow} onToggle={(v) => update(o.id, { shadow: v || undefined })} />
        <OverlayMaskSection overlay={o} />
        <TransformRows overlay={o} />
      </div>
    </>
  );
}

/** A doodle's other paints: one swatch per ink, each with a remove button,
 * and an add button while there is room. Each mark takes the fill or one of
 * these. */
function InksRow({ overlay: o }: { overlay: ShapeOverlay }) {
  const t = useTranslations("inspector.shape");
  const update = useEditor((s) => s.updateOverlay);
  const inks = o.inks ?? [];

  // Every change writes the whole list back with one entry changed.
  const swap = (i: number, c: string) => inks.map((x, j) => (j === i ? c : x));
  const write = (next: string[]) => update(o.id, { inks: next.length > 0 ? next : undefined });
  return (
    <Row label={t("inks")}>
      <div className="flex flex-col items-end gap-1">
        {inks.map((ink, i) => (
          <div key={i} className="flex items-center gap-1">
            <ColorField
              value={ink}
              label={t("ink", { n: i + 1 })}
              onBegin={() => useEditor.getState().pushHistory()}
              onLive={(c) => useEditor.getState().updateOverlayTransient(o.id, { inks: swap(i, c) })}
              onCommit={(c) => update(o.id, { inks: swap(i, c) })}
            />
            <Button variant="ghost" size="icon-xs" aria-label={t("removeInk", { n: i + 1 })} onClick={() => write(inks.filter((_, j) => j !== i))}>
              <X />
            </Button>
          </div>
        ))}
        {inks.length < DOODLE_INKS_MAX && (
          <Button variant="ghost" size="icon-xs" aria-label={t("addInk")} onClick={() => write([...inks, DOODLE_INKS[inks.length % DOODLE_INKS.length]])}>
            <Plus />
          </Button>
        )}
      </div>
    </Row>
  );
}

/** The drop shadow controls text and shapes share. A colored shadow at
 * offset 0 reads as a glow. */
function ShadowSection({
  id,
  shadow,
  onToggle,
}: {
  id: string;
  shadow: boolean | ShadowSpec | undefined;
  onToggle: (on: boolean) => void;
}) {
  const t = useTranslations("inspector.box");
  const update = useEditor((s) => s.updateOverlay);
  const shadowCk = useSliderCheckpoint();
  const spec: ShadowSpec = typeof shadow === "object" ? shadow : {};

  // A slider drag lands live and checkpoints once, the way every row does.
  const draft = (patch: ShadowSpec) => {
    shadowCk.begin();
    useEditor.getState().updateOverlayTransient(id, { shadow: { ...spec, ...patch } });
  };
  const commit = (patch: ShadowSpec) => {
    draft(patch);
    shadowCk.end();
  };
  return (
    <Section title={t("shadow")} enabled={!!shadow} onEnabledChange={onToggle}>
      <>
        <Row label={t("color")}>
          <ColorField
            value={spec.color ?? "#000000"}
            label={t("shadowColor")}
            onBegin={() => useEditor.getState().pushHistory()}
            onLive={(c) => useEditor.getState().updateOverlayTransient(id, { shadow: { ...spec, color: c } })}
            onCommit={(c) => update(id, { shadow: { ...spec, color: c } })}
            opacity={{
              label: t("shadowOpacity"),
              value: spec.opacity ?? 0.65,
              onDraft: (v) => draft({ opacity: v }),
              onCommit: (v) => commit({ opacity: v }),
            }}
          />
        </Row>
        <Row label={t("blur")}>
          <ValueSlider
            label={t("shadowBlur")}
            sliderClassName="data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={spec.blur ?? SHADOW.blur}
            min={0}
            max={SHADOW_BLUR_MAX}
            step={1}
            snap={[SHADOW.blur]}
            format={(v) => String(Math.round(v))}
            parse={parseNumberInput}
            onDraft={(v) => draft({ blur: v })}
            onCommit={(v) => commit({ blur: v })}
          />
        </Row>
        <Row label={t("offset")}>
          <ValueSlider
            label={t("shadowOffsetY")}
            sliderClassName="data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={spec.offsetY ?? SHADOW.offsetY}
            min={-SHADOW_OFFSET_MAX}
            max={SHADOW_OFFSET_MAX}
            step={1}
            snap={[0, SHADOW.offsetY]}
            format={(v) => String(Math.round(v))}
            parse={parseNumberInput}
            onDraft={(v) => draft({ offsetY: Math.round(v) })}
            onCommit={(v) => commit({ offsetY: Math.round(v) })}
          />
        </Row>
      </>
    </Section>
  );
}

/** A shape's pattern fill: stripes in the fill color, with line, gap and
 * angle sliders. Off is a solid fill. */
function PatternSection({ overlay: o }: { overlay: ShapeOverlay }) {
  const t = useTranslations("inspector.shape");
  const update = useEditor((s) => s.updateOverlay);
  const patternCk = useSliderCheckpoint();
  const pattern = o.pattern ?? STRIPES_DEFAULT;

  // Each slider writes the whole pattern back with its one field changed.
  const draft = (patch: Partial<StripesPattern>) => {
    patternCk.begin();
    useEditor.getState().updateOverlayTransient(o.id, { pattern: { ...pattern, ...patch } });
  };
  const commit = (patch: Partial<StripesPattern>) => {
    draft(patch);
    patternCk.end();
  };
  const slider = (label: string, value: number, min: number, max: number, step: number, write: (v: number) => Partial<StripesPattern>) => (
    <ValueSlider
      label={label}
      sliderClassName="data-horizontal:w-24"
      valueClassName="w-9 text-muted-foreground"
      value={value}
      min={min}
      max={max}
      step={step}
      format={(v) => String(Math.round(v * 10) / 10)}
      parse={parseNumberInput}
      onDraft={(v) => draft(write(v))}
      onCommit={(v) => commit(write(v))}
    />
  );
  return (
    <Section
      title={t("pattern")}
      enabled={!!o.pattern}
      onEnabledChange={(v) => update(o.id, { pattern: v ? STRIPES_DEFAULT : undefined })}
    >
      {o.pattern && (
        <>
          <Row label={t("line")}>{slider(t("stripeWidth"), pattern.width, STRIPE_LINE_MIN, STRIPE_LINE_MAX, 0.5, (v) => ({ width: v }))}</Row>
          <Row label={t("gap")}>{slider(t("stripeGap"), pattern.gap, 0, STRIPE_GAP_MAX, 0.5, (v) => ({ gap: v }))}</Row>
          <Row label={t("angle")}>{slider(t("stripeAngle"), pattern.angle ?? 0, -90, 90, 1, (v) => ({ angle: Math.round(v) || undefined }))}</Row>
        </>
      )}
    </Section>
  );
}

/** A flash element's setting, drafted while a slider drags. */
function writeFlash(id: string, patch: FlashPulse, how: PulseWrite) {
  if (how === "draft") {
    useEditor.getState().updateOverlayTransient(id, patch);
    return;
  }
  useEditor.getState().updateOverlay(id, patch);
}

function EffectPanel({ overlay: o }: { overlay: EffectOverlay }) {
  const t = useTranslations("inspector.effect");
  const amountCk = useSliderCheckpoint();
  return (
    <>
      <ElementTitle overlay={o} />
      {/* Which effect this is belongs to the Effects tab: it marks this one and
          swaps it on a click, so the panel is only its knobs. */}
      <div className="flex flex-col gap-1 px-3.5 pb-4">
        {o.effect === "zoom" ? (
          <ZoomTarget overlay={o} />
        ) : AMOUNTLESS_EFFECTS.includes(o.effect) ? null : (
          <>
          {o.effect === "lightleak" && <LeakCourseRow overlay={o} />}
          {o.effect === "glitch" && <GlitchKindRow overlay={o} />}
          {o.effect === "flash" && (
            <>
              <FlashPulseRows pulse={o} write={(patch, how) => writeFlash(o.id, patch, how)} />
              <FlashFadeRow pulse={o} write={(patch, how) => writeFlash(o.id, patch, how)} />
            </>
          )}
          <Row label={t("amount")}>
            <ValueSlider
              label={t("effectAmount")}
              sliderClassName="data-horizontal:w-24"
              valueClassName="w-9 text-muted-foreground"
              value={o.amount ?? 0.5}
              min={0.05}
              max={1}
              step={0.01}
              snap={[0.5]}
              format={(v) => String(Math.round(v * 100))}
              parse={parsePercentInput}
              onDraft={(v) => {
                amountCk.begin();
                useEditor.getState().updateOverlayTransient(o.id, { amount: v });
              }}
              onCommit={(v) => {
                amountCk.begin();
                useEditor.getState().updateOverlayTransient(o.id, { amount: v });
                amountCk.end();
              }}
            />
          </Row>
          </>
        )}
        <HiddenRow overlay={o} />
      </div>
    </>
  );
}

/** A glitch's kind: the random mix, or one kind pinned to every frame. The
 * kinds name themselves under `inspector.effect.glitchKinds`; "mix" is the
 * random schedule, stored as absence. */
function GlitchKindRow({ overlay: o }: { overlay: EffectOverlay }) {
  const t = useTranslations("inspector.effect");
  const kinds = ["mix", ...GLITCH_KINDS] as const;
  return (
    <Row label={t("kind")}>
      <Select
        value={o.glitch ?? "mix"}
        items={Object.fromEntries(kinds.map((k) => [k, t(`glitchKinds.${k}`)]))}
        onValueChange={(v) => useEditor.getState().updateOverlay(o.id, { glitch: v === "mix" ? undefined : (v as GlitchKind) })}
      >
        <SelectTrigger className="h-8 w-36 text-[12px]">
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          {kinds.map((k) => (
            <SelectItem key={k} value={k} className="text-[12px]">
              {t(`glitchKinds.${k}`)}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </Row>
  );
}

/** A light leak's course: a drifting glow for the whole element, the film
 * burn played once across it, the scorch flashing hot tones through it, the
 * film-strip flash over a cut, or the burn's dark climb. Each course names
 * itself under `inspector.effect.leakCourses`. */
function LeakCourseRow({ overlay: o }: { overlay: EffectOverlay }) {
  const t = useTranslations("inspector.effect");
  const leak = o.leak ?? "drift";
  return (
    <Row label={t("course")}>
      <div className="flex w-44 rounded-lg border border-input p-0.5 text-[11.5px] font-medium">
        {LEAK_COURSES.map((c) => (
          <button
            key={c}
            type="button"
            aria-pressed={leak === c}
            className={cn(
              "flex-1 rounded-md px-1 py-1 whitespace-nowrap transition-colors",
              leak === c ? "bg-neutral-900 text-white" : "text-muted-foreground hover:text-foreground"
            )}
            onClick={() => useEditor.getState().updateOverlay(o.id, { leak: c === "drift" ? undefined : c })}
          >
            {t(`leakCourses.${c as LeakCourse}`)}
          </button>
        ))}
      </div>
    </Row>
  );
}

/** The grain a title wears inside its letters, or none; each names itself
 * under `inspector.text.textures`. */
function TextTextureRow({ overlay: o }: { overlay: TextOverlay }) {
  const t = useTranslations("inspector.text");
  const texture = o.texture ?? "none";
  return (
    <Row label={t("texture")}>
      <div className="flex w-36 rounded-lg border border-input p-0.5 text-[11.5px] font-medium">
        {(["none", ...TEXT_TEXTURES] as const).map((c) => (
          <button
            key={c}
            type="button"
            aria-pressed={texture === c}
            className={cn(
              "flex-1 rounded-md px-1 py-1 whitespace-nowrap transition-colors",
              texture === c ? "bg-neutral-900 text-white" : "text-muted-foreground hover:text-foreground"
            )}
            onClick={() => useEditor.getState().updateOverlay(o.id, { texture: c === "none" ? undefined : c })}
          >
            {t(`textures.${c as TextTexture | "none"}`)}
          </button>
        ))}
      </div>
    </Row>
  );
}

/** What each flash tone is called in the panel. */
/** The focus puck's diameter, in px — `size-5` on the element below. */
const PUCK = 20;

/**
 * Where a zoom lands and how close it gets.
 *
 * The stage mirrors the live preview, so the point is chosen against the
 * picture the zoom will sit on: drag the puck onto what matters. Depth is
 * three steps — a zoom is a choice of how close, and a slider of it is a
 * decision nobody wants to make twice.
 */
type ZoomLevelId = keyof Messages["inspector"]["effect"]["zoomLevels"];

function ZoomTarget({ overlay: o }: { overlay: EffectOverlay }) {
  const t = useTranslations("inspector.effect");
  const aspect = useEditor((s) => s.aspect);
  const frame = frameOf(aspect);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const portrait = frame.h > frame.w;
  const focus = { x: o.focus?.x ?? 0.5, y: o.focus?.y ?? 0.5 };
  const amount = o.amount ?? 0.5;
  // How long the push in takes: the far left is a cut straight to the close
  // shot, everything right of it moves the camera in over that many seconds.
  const ramp = zoomRampOf(o.ramp);
  const rampCk = useSliderCheckpoint();

  useEffect(() => {
    let raf = 0;
    const tick = () => {
      raf = requestAnimationFrame(tick);
      const dst = canvasRef.current;
      const src = getPreviewCanvas();
      const ctx = dst?.getContext("2d");
      if (!dst || !src || !ctx) return;
      ctx.clearRect(0, 0, dst.width, dst.height);
      ctx.drawImage(src, 0, 0, dst.width, dst.height);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  const aim = (e: React.PointerEvent<HTMLDivElement>) => {
    const r = e.currentTarget.getBoundingClientRect();
    useEditor.getState().updateOverlayTransient(o.id, {
      focus: {
        x: Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)),
        y: Math.max(0, Math.min(1, (e.clientY - r.top) / r.height)),
      },
    });
  };

  return (
    <div className="flex flex-col items-center gap-2 pt-1">
      <div
        className="relative cursor-grab overflow-hidden rounded-lg bg-black select-none active:cursor-grabbing"
        style={{
          aspectRatio: `${frame.w} / ${frame.h}`,
          height: portrait ? 168 : undefined,
          width: portrait ? undefined : "100%",
        }}
        onPointerDown={(e) => {
          if (e.button !== 0) return;
          e.currentTarget.setPointerCapture(e.pointerId);
          useEditor.getState().pushHistory();
          aim(e);
        }}
        onPointerMove={(e) => {
          if (e.buttons & 1) aim(e);
        }}
      >
        <canvas
          ref={canvasRef}
          width={Math.round(frame.w / 5)}
          height={Math.round(frame.h / 5)}
          className="pointer-events-none block size-full"
        />
        {/* The puck rides its point, pulled back by its own radius at the
            edges so the whole of it stays on the picture. */}
        <div
          className="pointer-events-none absolute size-5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-[#0a84ff] ring-2 ring-white/90 shadow-[0_1px_4px_rgba(0,0,0,0.45)]"
          style={{
            left: `calc(${focus.x * 100}% + ${((0.5 - focus.x) * PUCK).toFixed(2)}px)`,
            top: `calc(${focus.y * 100}% + ${((0.5 - focus.y) * PUCK).toFixed(2)}px)`,
          }}
        />
      </div>
      <div className="flex w-full flex-col">
        <Row label={t("depth")} grow>
          {/* The segmented control the rest of the inspector uses — bordered
              box, dark pill on the chosen one — stretched over the row's
              free width. */}
          <div className="flex min-w-0 grow rounded-lg border border-input p-0.5 text-[11.5px] font-medium">
            {ZOOM_LEVELS.map((l) => (
              <button
                key={l.id}
                type="button"
                aria-pressed={Math.abs(amount - l.amount) < 0.01}
                className={cn(
                  `zoom-${l.id} flex-1 rounded-md px-1 py-1 whitespace-nowrap transition-colors`,
                  Math.abs(amount - l.amount) < 0.01
                    ? "bg-neutral-900 text-white"
                    : "text-muted-foreground hover:text-foreground"
                )}
                onClick={() => useEditor.getState().updateOverlay(o.id, { amount: l.amount })}
              >
                {t(`zoomLevels.${l.id as ZoomLevelId}`)}
              </button>
            ))}
          </div>
        </Row>
        <Row label={t("speed")}>
          <ValueSlider
            label={t("zoomSpeed")}
            sliderClassName="data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={ramp}
            min={0}
            max={ZOOM_RAMP_MAX}
            step={0.1}
            format={(v) => `${v.toFixed(1)}s`}
            parse={parseSecondsInput}
            onDraft={(v) => {
              rampCk.begin();
              useEditor.getState().updateOverlayTransient(o.id, { ramp: v });
            }}
            onCommit={(v) => {
              rampCk.begin();
              useEditor.getState().updateOverlayTransient(o.id, { ramp: v });
              rampCk.end();
            }}
          />
        </Row>
      </div>
    </div>
  );
}

function StickerPanel({ overlay: o }: { overlay: StickerOverlay }) {
  const t = useTranslations("inspector.sticker");
  const widthCk = useSliderCheckpoint();
  const asset = useEditor((s) =>
    o.assetId ? s.assets.find((a) => a.id === o.assetId) : undefined
  );
  return (
    <>
      <ElementTitle overlay={o} />
      <div className="flex flex-col gap-1 px-3.5 pb-4">
        {asset ? (
          <div className="mb-1 truncate text-[12px] text-muted-foreground" title={asset.name}>
            {asset.name}
          </div>
        ) : null}
        <Row label={t("size")}>
          <ValueSlider
            label={t("stickerSize")}
            sliderClassName="data-horizontal:w-24"
            valueClassName="w-9 text-muted-foreground"
            value={o.w}
            min={STICKER_W_MIN}
            max={1}
            step={0.005}
            format={(v) => (v < 0.1 ? (v * 100).toFixed(1) : String(Math.round(v * 100)))}
            parse={parsePercentInput}
            onDraft={(v) => {
              widthCk.begin();
              useEditor.getState().updateOverlayTransient(o.id, { w: v });
            }}
            onCommit={(v) => {
              widthCk.begin();
              useEditor.getState().updateOverlayTransient(o.id, { w: v });
              widthCk.end();
            }}
          />
        </Row>
        <OverlayMaskSection overlay={o} />
        <TransformRows overlay={o} />
      </div>
    </>
  );
}