Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript
59.2 KB
Raw Blame
import { trackIdAtOffset } from "./track-hit-test";
import { useChannelWaveform } from "./use-channel-waveform";
import { setDragResolvesOverlap } from "../../../stores/project/drag-placement";
import { useEditorWorkspaceStore } from "../../../stores/editor-workspace-store";
import { useTimelineTouchGesture, listenTimelineGesture } from "./touch-gestures";
import { TimelineTouchMoveHandle } from "./TimelineTouchMoveHandle";
import { pinTimelineClip } from "./visible-clips";
import { moveLinkedCaptions } from "../../../utils/linked-caption-edit";
import React, { useRef, useState, useEffect, useCallback } from "react";
import { flushSync } from "react-dom";
import { ContextMenu, ContextMenuTrigger } from "@openreel/ui";
import { Box, Image, Layers } from "@/icons/lucide-compat";
import { getCompoundClipId, type Clip, type Track, type TransitionType } from "@openreel/core";
import { computeLaneInfos, type ClipLaneInfo } from "./clip-lane-info";
import { useProjectStore } from "../../../stores/project-store";
import { ClipMarkerFlags } from "./ClipMarkerFlags";
import { useUIStore } from "../../../stores/ui-store";
import { useEditPointStore } from "../../../stores/edit-point-store";
import { selectEditPoint } from "../../../services/edit-point-commands";
import { useTimelineStore } from "../../../stores/timeline-store";
import {
  calculateSnap,
  getClipStyle,
  getClipWaveformBarAmplitudes,
} from "./utils";
import { ClipContextMenu } from "./ClipContextMenu";
import { toast } from "../../../stores/notification-store";
import { getTransitionBridge } from "../../../bridges/transition-bridge";
import {
  EFFECT_DRAG_MIME,
  TRANSITION_DRAG_MIME,
} from "../panels/EffectsTransitionsPanel";
import { parseEditorEffectDropPayload } from "./effect-drop";
import { applyEditorEffectToClip } from "../../../services/editor-effect-application";
import { editableTimelineIds, editTimelineSelection, timelineDragRepresentatives } from "../../../services/linked-timeline-edit";
import { getVisibleRepeatRange } from "./visible-repeat-range";
import { AudioClipFade } from "./AudioClipFade";
import { ClipGainLine } from "./ClipGainLine";
import { GAIN_LINE_MIN_TRACK_HEIGHT } from "./clip-gain-geometry";
import { openNestClip } from "../../../services/sequence-commands";
import { SplitEditBadge } from "./SplitEditBadge";
import { beginClipDragActivity, endClipDragActivity } from "./clip-drag-activity";
import { RemoteClipSelection } from "./RemotePresence";
import {
  AUDIO_TYPE_LABELS,
  clipDropOptionsFromModifiers,
  getMediaLabel,
  planClipDropResolution,
  resolveClipLabel,
  snapshotClipOrigins,
  type ClipOrigin,
} from "@openreel/core";
import { v4 as uuidv4 } from "uuid";

/** Whether a mouse button or touch is currently down, tracked once for every clip. */
let pointerIsDown = false;
if (typeof window !== "undefined") {
  const down = () => { pointerIsDown = true; };
  const up = () => { pointerIsDown = false; };
  window.addEventListener("mousedown", down, true);
  window.addEventListener("pointerdown", down, true);
  window.addEventListener("mouseup", up, true);
  window.addEventListener("pointerup", up, true);
  window.addEventListener("pointercancel", up, true);
  window.addEventListener("blur", up);
}

/** Where the store has a clip right now (a drop compares it with the live position to skip a redundant move). */
function findPlacedClip(project: { timeline: { tracks: ReadonlyArray<{ id: string; clips: ReadonlyArray<{ id: string; startTime: number }> }> } }, clipId: string): { trackId: string; startTime: number } | null {
  for (const track of project.timeline.tracks) {
    const found = track.clips.find((candidate) => candidate.id === clipId);
    if (found) return { trackId: track.id, startTime: found.startTime };
  }
  return null;
}

interface ClipComponentProps {
  clip: Clip;
  track: Track;
  /**
   * Every track, in display order. Optional once the lane supplies `laneInfo` and
   * `getAllTracks`: a clip then no longer re-renders when some OTHER track array
   * identity changes (a one-clip move replaces `tracks` for everybody).
   */
  allTracks?: Track[];
  /** Reads the latest tracks at gesture time (drag snapping / target lane), never during render. */
  getAllTracks?: () => Track[];
  /** Cross-clip derived render state, computed once per lane per commit (see clip-lane-info.ts). */
  laneInfo?: ClipLaneInfo;
  pixelsPerSecond: number;
  scrollX: number;
  viewportWidth: number;
  isSelected: boolean;
  trackHeights: Map<string, number>;
  /** Full row heights (clip lane plus expanded automation lanes) for vertical drag hit-testing; defaults to trackHeights. */
  rowHeights?: Map<string, number>;
  timelineRef: React.RefObject<HTMLDivElement | null>;
  trackTopInset?: number;
  onSelect: (clipId: string, addToSelection: boolean) => void;
  onMoveClip: (
    clipId: string,
    newStartTime: number,
    targetTrackId?: string,
  ) => void | Promise<void>;
  onSnapIndicator: (time: number | null) => void;
  onTrimClip?: (
    clipId: string,
    edge: "left" | "right",
    newTime: number,
  ) => void | Promise<void>;
}

const AUTO_SCROLL_THRESHOLD = 80;
const AUTO_SCROLL_SPEED = 10;
const DRAG_THRESHOLD = 5;

const ClipComponentImpl: React.FC<ClipComponentProps> = ({
  clip,
  track,
  allTracks,
  getAllTracks,
  laneInfo,
  pixelsPerSecond,
  scrollX,
  viewportWidth,
  isSelected,
  trackHeights,
  rowHeights,
  timelineRef,
  trackTopInset = 0,
  onSelect,
  onMoveClip,
  onSnapIndicator,
  onTrimClip,
}) => {
  const mediaItem = useProjectStore((state) => state.getMediaItem(clip.mediaId));
  // Label colour: the clip's own, else its media's (Project panel).
  const clipLabel = getMediaLabel(resolveClipLabel(clip, mediaItem));
  const tool = useEditorWorkspaceStore(s => s.timelineTool);
  const snapSettings = useUIStore((state) => state.snapSettings);
  const showVideoWaveforms = useUIStore((state) => state.showWaveforms);
  const effectApplicationClipId = useUIStore(
    (state) => state.effectApplicationClipId,
  );
  const effectApplicationLabel = useUIStore(
    (state) => state.effectApplicationLabel,
  );
  const motionCompositionId =
    typeof clip.metadata?.motionCompositionId === "string"
      ? clip.metadata.motionCompositionId
      : undefined;
  const motionComposition = useProjectStore((state) =>
    motionCompositionId
      ? (state.project.motionCompositions ?? []).find(
          (composition) => composition.id === motionCompositionId,
        )
      : undefined,
  );
  // A nest is identified by its metadata OR by its `compound:<id>` media id (legacy and imported nests
  // carry only the latter); checking metadata alone left those without the double-click-to-open gesture.
  const compoundClipId = getCompoundClipId(clip) ?? undefined;
  const isCompoundClip = Boolean(compoundClipId);
  const [isDragging, setIsDragging] = useState(false);
  const [isPendingDrag, setIsPendingDrag] = useState(false);
  const [dragOffset, setDragOffset] = useState(0);
  const [dragYOffset, setDragYOffset] = useState(0);
  const [isInvalidDrop, setIsInvalidDrop] = useState(false);
  const [isTrimming, setIsTrimming] = useState(false);
  const [trimEdge, setTrimEdge] = useState<"left" | "right" | null>(null);
  // "left:roll" / "right:ripple" when this clip owns a selected edit point (or is
  // the neighbour across the selected cut); "" otherwise. A string keeps the
  // selector from re-rendering every clip on unrelated selection changes.
  const editPointKey = useEditPointStore((s) => {
    const sel = s.selection;
    if (sel?.type !== "edit") return "";
    if (sel.clipId === clip.id) return `${sel.edge}:${sel.kind}`;
    if (sel.neighborId === clip.id) return `${sel.edge === "left" ? "right" : "left"}:${sel.kind}`;
    return "";
  });
  const [editPointEdge, editPointKind] = editPointKey.split(":") as ["left" | "right" | undefined, "ripple" | "roll" | undefined];
  const handleEditPointClick = (edge: "left" | "right") => (e: React.MouseEvent) => {
    e.stopPropagation();
    // A trim drag also ends in a click; only a click without movement selects.
    if (Math.abs(e.clientX - trimStartRef.current.mouseX) > 3) return;
    selectEditPoint(clip.id, edge, { toggleKind: e.metaKey || e.ctrlKey });
  };
  // Snapshot of every additional selected clip at drag start. Multi-clip
  // drag applies the same time delta to each entry so they stay locked
  // together as the dragged clip moves.
  const batchDragSnapshotRef = useRef<Array<{ clipId: string; startTime: number }> | null>(null);
  const multiDragSnapshotRef = useRef<
    Array<{ clipId: string; startTime: number; trackId: string }>
  >([]);
  const dragStartTimeRef = useRef(clip.startTime);
  // Every clip's track/start when the drag began: the drop resolves overlaps
  // (overwrite / insert / copy) against it. See planClipDropResolution.
  const dragOriginsRef = useRef<Map<string, ClipOrigin> | null>(null);
  const dropModifiersRef = useRef({ altKey: false, metaKey: false, ctrlKey: false });
  const trimStartRef = useRef<{
    mouseX: number;
    startTime: number;
    duration: number;
  }>({
    mouseX: 0,
    startTime: clip.startTime,
    duration: clip.duration,
  });
  const dragStartRef = useRef<{ mouseY: number; clipY: number; scrollTop: number }>({
    mouseY: 0,
    clipY: 0,
    scrollTop: 0,
  });
  const mousePositionRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
  const dragActivationEventRef = useRef<MouseEvent | null>(null);
  const suppressDragReleaseClickRef = useRef(false);
  const pendingDropRef = useRef<{ time: number; targetTrackId?: string }>({
    time: clip.startTime,
  });
  const dragPendingRef = useRef<{ active: boolean; startX: number; startY: number }>({
    active: false,
    startX: 0,
    startY: 0,
  });
  const clipRef = useRef<HTMLDivElement>(null);
  const dragMinimumTimeRef = useRef(0);
  const trimCommitRef = useRef<Promise<void>>(Promise.resolve());
  const trimGroupOpenRef = useRef(false);
  const dragGroupOpenRef = useRef(false);
  const dragCommitRef = useRef<Promise<unknown>>(Promise.resolve());
  const closeDragGroup = useCallback(async () => {
    if (!dragGroupOpenRef.current) return;
    dragGroupOpenRef.current = false;
    await dragCommitRef.current;
    setDragResolvesOverlap(false);
    useProjectStore.getState().endHistoryGroup();
  }, []);
  // React can tear this component's effects down and rebuild them while a
  // drag is still in progress (the project changes on every frame). Closing the
  // history group then would split one drag into dozens of undo steps, so the
  // group only closes on teardown once the pointer is up; if it is still down,
  // it closes when the pointer is released.
  useEffect(() => () => {
    if (!pointerIsDown) {
      void closeDragGroup();
      return;
    }
    if (!dragGroupOpenRef.current) return;
    const release = () => {
      window.removeEventListener("mouseup", release);
      window.removeEventListener("pointerup", release);
      window.removeEventListener("pointercancel", release);
      // The drag's own handler normally closes it first; this is the backstop.
      setTimeout(() => void closeDragGroup(), 400);
    };
    window.addEventListener("mouseup", release);
    window.addEventListener("pointerup", release);
    window.addEventListener("pointercancel", release);
  }, [closeDragGroup]);
  const touchGesture = useTimelineTouchGesture();
  const [contextMenuOpen, setContextMenuOpen] = useState(false);
  const moveCommitRafRef = useRef<number | null>(null);
  const pendingCommitRef = useRef<(() => void) | null>(null);

  // Drag-drop highlight state: "effect" when an effect is hovered over
  // the clip body, "transition-left" / "transition-right" when a
  // transition is hovered over one of the clip's edges.
  const [dragHover, setDragHover] = useState<
    "effect" | "transition-left" | "transition-right" | null
  >(null);

  const left = clip.startTime * pixelsPerSecond;
  const width = clip.duration * pixelsPerSecond;

  const clipMediaType = track.type === "audio" ? "audio" : mediaItem?.type ?? track.type;
  const isVideo = clipMediaType === "video";
  const isAudio = clipMediaType === "audio";
  const isImage = clipMediaType === "image";
  const frameRate = useProjectStore((state) => state.project.settings.frameRate);
  // Latest tracks for gesture handlers; render never reads them (see `laneInfo`).
  const allTracksRef = useRef<Track[]>(allTracks ?? []);
  allTracksRef.current = allTracks ?? allTracksRef.current;
  const readTracks = useCallback(
    () => getAllTracks?.() ?? allTracksRef.current,
    [getAllTracks],
  );
  const fallbackLaneInfo = React.useMemo(
    () =>
      laneInfo
        ? null
        : computeLaneInfos([clip], {
            track,
            allTracks: allTracks ?? [],
            frameRate,
            mediaTypeOf: () => clipMediaType,
          }).get(clip.id) ?? null,
    [laneInfo, clip, track, allTracks, frameRate, clipMediaType],
  );
  const info = laneInfo ?? fallbackLaneInfo!;
  const { hasDetachedAudio, splitOffset } = info;
  const drawWaveform = isAudio || (isVideo && showVideoWaveforms &&
    !hasDetachedAudio && (clip.audioTrackIndex ?? 0) === 0);
  const isMotionClip = Boolean(clip.metadata?.motionClip);
  const clipStyle = getClipStyle(clipMediaType);

  const handleClick = (e: React.MouseEvent) => {
    if (e.button !== 0) return;
    e.stopPropagation();
    if (suppressDragReleaseClickRef.current) {
      suppressDragReleaseClickRef.current = false;
      return;
    }
    if (isDragging || isPendingDrag) return;
    if (tool === "blade" && !track.locked) {
      const rect=clipRef.current?.getBoundingClientRect(); if(!rect) return;
      const rate=useProjectStore.getState().project.settings.frameRate;
      const time=Math.round((clip.startTime+(e.clientX-rect.left)/pixelsPerSecond)*rate)/rate;
      if(time>clip.startTime && time<clip.startTime+clip.duration) void editTimelineSelection([clip.id], "split", time);
      return;
    }
    onSelect(clip.id, e.shiftKey || e.metaKey);
  };

  const handleMouseDown = (e: React.MouseEvent) => {
    if (touchGesture.shouldIgnoreMouse(e)) return false;
    if (e.button !== 0) return;
    if (track.locked || isTrimming || tool === "blade") return false;
    e.stopPropagation();
    // A cross-track drag may not emit a click. Never suppress a later gesture.
    suppressDragReleaseClickRef.current = false;
    const state = useProjectStore.getState();
    const rawSelection = useUIStore.getState().getSelectedClipIds();
    const dragSelection = rawSelection.includes(clip.id) ? rawSelection : [clip.id];
    const editable = editableTimelineIds(dragSelection);
    if (!editable.includes(clip.id)) return false;
    const earliest = Math.min(...editable.map((id) => state.getClip(id)?.startTime ?? clip.startTime));
    dragMinimumTimeRef.current = clip.startTime - earliest;

    const rect = clipRef.current?.parentElement?.getBoundingClientRect();
    const clipRect = clipRef.current?.getBoundingClientRect();
    if (!rect || !clipRect) return false;

    const clickX = e.clientX - rect.left;
    const clipStartX = clip.startTime * pixelsPerSecond;
    setDragOffset(clickX - clipStartX);
    dragStartTimeRef.current = clip.startTime;

    dragStartRef.current = {
      mouseY: e.clientY,
      clipY: clipRect.top - rect.top,
      scrollTop: timelineRef.current?.scrollTop || 0,
    };
    mousePositionRef.current = { x: e.clientX, y: e.clientY };
    dragActivationEventRef.current = null;
    pendingDropRef.current = { time: clip.startTime };
    dragPendingRef.current = { active: true, startX: e.clientX, startY: e.clientY };
    setDragYOffset(0);
    setIsInvalidDrop(false);

    // If this clip is part of a multi-selection, snapshot the other
    // selected clips' start positions so we can drag them as a group.
    const selectedIds = timelineDragRepresentatives(state.project, editable, clip.id);
    multiDragSnapshotRef.current = selectedIds.flatMap((id) => {
      const companion = state.getClip(id);
      return companion ? [{ clipId: id, startTime: companion.startTime, trackId: companion.trackId }] : [];
    });
    batchDragSnapshotRef.current = editable.length - 1 >= BATCH_DRAG_COMPANIONS
      ? editable.flatMap((id) => {
          const member = state.getClip(id);
          return member ? [{ clipId: id, startTime: member.startTime }] : [];
        })
      : null;
    // Install gesture listeners before native input can deliver move/up in a burst.
    // Only gesture entry and activation flush; ordinary moves remain RAF-coalesced.
    flushSync(() => setIsPendingDrag(true));
  };

  // ── Drag-drop: effects & transitions from the assets panel ────
  // The asset cards set custom MIME types so we know which mode to use.
  // For effects the drop hits anywhere on the clip body. For transitions
  // we treat the outer ~25% of the clip's width as an "edge zone" — the
  // closer edge wins, and we map left edge → incoming, right edge →
  // outgoing transition.
  const readDragKind = (e: React.DragEvent): "effect" | "transition" | null => {
    const types = e.dataTransfer.types;
    if (types.includes(EFFECT_DRAG_MIME)) return "effect";
    if (types.includes(TRANSITION_DRAG_MIME)) return "transition";
    // text/plain fallback (some browsers don't preserve custom types)
    if (types.includes("text/plain")) {
      // Can't read data during dragover; trust the parsed kind by
      // payload sniffing on drop. We optimistically allow both here.
      return null;
    }
    return null;
  };

  const computeTransitionEdge = useCallback(
    (e: React.DragEvent): "transition-left" | "transition-right" => {
      const rect = clipRef.current?.getBoundingClientRect();
      if (!rect) return "transition-right";
      const ratio = (e.clientX - rect.left) / rect.width;
      return ratio < 0.5 ? "transition-left" : "transition-right";
    },
    [],
  );

  const handleDragOver = useCallback(
    (e: React.DragEvent<HTMLDivElement>) => {
      const kind = readDragKind(e);
      if (kind === null) {
        // Don't preventDefault — let other handlers (e.g. timeline file
        // drop) take over.
        return;
      }
      e.preventDefault();
      e.stopPropagation();
      e.dataTransfer.dropEffect = "copy";
      if (kind === "effect") {
        setDragHover("effect");
      } else {
        setDragHover(computeTransitionEdge(e));
      }
    },
    [computeTransitionEdge],
  );

  const handleDragLeave = useCallback((e: React.DragEvent<HTMLDivElement>) => {
    // Only clear when the pointer actually exits the clip — dragleave
    // fires on every child too.
    const related = e.relatedTarget as Node | null;
    if (!related || !clipRef.current?.contains(related)) {
      setDragHover(null);
    }
  }, []);

  const applyTransitionAt = useCallback(
    (
      transitionType: TransitionType,
      edge: "left" | "right",
      transitionParams?: Record<string, unknown>,
      transitionDuration?: number,
    ) => {
      const projectState = useProjectStore.getState();
      const tracks = projectState.project.timeline.tracks;
      const owningTrack = tracks.find((t) =>
        t.clips.some((c) => c.id === clip.id),
      );
      if (!owningTrack) return;
      const sortedClips = [...owningTrack.clips].sort((a, b) => {
        if (a.startTime !== b.startTime) return a.startTime - b.startTime;
        return a.id.localeCompare(b.id);
      });
      const idx = sortedClips.findIndex((c) => c.id === clip.id);
      const previousClip = idx > 0 ? sortedClips[idx - 1] : undefined;
      const nextClip =
        idx < sortedClips.length - 1 ? sortedClips[idx + 1] : undefined;
      const clipA = edge === "left" ? previousClip : sortedClips[idx];
      const clipB = edge === "left" ? sortedClips[idx] : nextClip;

      const bridge = getTransitionBridge();
      if (!bridge.isInitialized()) {
        toast.error("Transition engine not ready", "Try again in a moment.");
        return;
      }
      const defaultParams = {
        ...bridge.getDefaultParams(transitionType),
        ...transitionParams,
      };
      const result =
        clipA && clipB
          ? bridge.createTransition(
              clipA,
              clipB,
              transitionType,
              transitionDuration ?? useEditorWorkspaceStore.getState().transitionDuration,
              defaultParams,
            )
          : bridge.createClipEdgeTransition(
              sortedClips[idx],
              edge === "left" ? "in" : "out",
              transitionType,
              transitionDuration ?? useEditorWorkspaceStore.getState().transitionDuration,
              defaultParams,
            );
      if (result.success && result.transitionId) {
        const transition = bridge.getTransition(result.transitionId);
        if (transition) {
          projectState.addClipTransition(transition);
          toast.success(
            transition.edge === "in"
              ? "Intro transition applied"
              : transition.edge === "out"
                ? "Outro transition applied"
                : "Transition applied",
            `${transitionType} • ${transition.duration.toFixed(1)}s`,
          );
          return;
        }
      }
      toast.error(
        "Transition failed",
        result.error || "Could not create transition",
      );
    },
    [clip.id],
  );

  const handleDrop = useCallback(
    async (e: React.DragEvent<HTMLDivElement>) => {
      setDragHover(null);

      const tryParse = <T,>(s: string | null): T | null => {
        if (!s) return null;
        try {
          return JSON.parse(s) as T;
        } catch {
          return null;
        }
      };

      const text = e.dataTransfer.getData("text/plain");
      const effectPayload = parseEditorEffectDropPayload(
        e.dataTransfer.getData(EFFECT_DRAG_MIME) || null,
        text,
      );
      const transitionPayload = tryParse<{
        transitionType: TransitionType;
        transitionParams?: Record<string, unknown>;
        transitionDuration?: number;
      }>(
        e.dataTransfer.getData(TRANSITION_DRAG_MIME) || null,
      );
      const isTransitionByText = text.startsWith("transition:");

      const effectType = effectPayload?.effectType ?? null;
      const transitionType =
        transitionPayload?.transitionType ??
        (isTransitionByText ? (text.slice(11) as TransitionType) : null);

      if (!effectType && !transitionType) {
        // Not for us — let the timeline's outer drop handler take it.
        return;
      }

      e.preventDefault();
      e.stopPropagation();

      if (effectType) {
        const result = await applyEditorEffectToClip(clip.id, { effectType, effectParams: effectPayload?.effectParams });
        if (effectType === "stabilize") {
          if (!result) toast.warning("Stabilization unavailable", "Select an unlocked video clip to configure stabilization.");
          return;
        }
        if (result) {
          toast.success("Effect applied", `${effectType} added`);
          // Auto-select the clip so the user sees the new effect in
          // the inspector.
          useUIStore.getState().select({ id: clip.id, type: "clip" });
        } else {
          toast.error("Effect failed", "Could not apply effect");
        }
        return;
      }

      if (transitionType) {
        const edge = computeTransitionEdge(e).endsWith("left") ? "left" : "right";
        applyTransitionAt(
          transitionType,
          edge,
          transitionPayload?.transitionParams,
          typeof transitionPayload?.transitionDuration === "number" && transitionPayload.transitionDuration > 0
            ? transitionPayload.transitionDuration
            : undefined,
        );
      }
    },
    [clip.id, applyTransitionAt, computeTransitionEdge],
  );

  const handleTrimMouseDown =
    (edge: "left" | "right") => (e: React.MouseEvent) => {
      if (touchGesture.shouldIgnoreMouse(e) || e.button !== 0) return false;
      if (track.locked || !onTrimClip || !editableTimelineIds([clip.id]).includes(clip.id)) return false;
      e.stopPropagation();
      useProjectStore.getState().beginHistoryGroup("Trim clips");
      trimGroupOpenRef.current = true;
      setIsTrimming(true);
      setTrimEdge(edge);
      trimStartRef.current = {
        mouseX: e.clientX,
        startTime: clip.startTime,
        duration: clip.duration,
      };
      document.body.style.cursor = "ew-resize";
    };

  useEffect(() => {
    if (!isPendingDrag) return;

    const handlePendingMouseMove = (e: MouseEvent) => {
      const dx = e.clientX - dragPendingRef.current.startX;
      const dy = e.clientY - dragPendingRef.current.startY;
      const distance = Math.sqrt(dx * dx + dy * dy);

      if (distance >= DRAG_THRESHOLD) {
        dragPendingRef.current.active = false;
        dragActivationEventRef.current = e;
        suppressDragReleaseClickRef.current = true;
        if (!dragGroupOpenRef.current) {
          useProjectStore.getState().beginHistoryGroup("Move clips");
          dragGroupOpenRef.current = true;
          setDragResolvesOverlap(true);
          dragOriginsRef.current = snapshotClipOrigins(useProjectStore.getState().getFullProject());
        }
        // Select + enter drag in ONE synchronous render: selecting first and then flushing the
        // drag state rendered the timeline twice on the first move (a ~40 ms frame at 400 clips).
        beginClipDragActivity();
        flushSync(() => {
          if (!useUIStore.getState().getSelectedClipIds().includes(clip.id)) onSelect(clip.id, false);
          setIsPendingDrag(false);
          setIsDragging(true);
        });
      }
    };

    const handlePendingMouseUp = (e: MouseEvent) => {
      dragPendingRef.current.active = false;
      setIsPendingDrag(false);
      onSelect(clip.id, e.shiftKey || e.metaKey);
    };

    const stopListening = listenTimelineGesture(touchGesture.pointerId, handlePendingMouseMove, handlePendingMouseUp, () => {
      dragPendingRef.current.active = false;
      setIsPendingDrag(false);
    });

    return () => {
      stopListening();
    };
  }, [isPendingDrag, clip.id, onSelect, touchGesture.pointerId]);

  useEffect(() => {
    if (!isDragging) return;
    beginClipDragActivity();

    let animationFrameId: number | null = null;
    const dragBatchKey = `drag-${clip.id}-${Date.now()}`;

    const scrollLoop = () => {
      if (!timelineRef.current) {
        animationFrameId = requestAnimationFrame(scrollLoop);
        return;
      }

      const timeline = timelineRef.current;
      const timelineRect = timeline.getBoundingClientRect();
      const mouseY = mousePositionRef.current.y;
      const timelineTop = timelineRect.top;
      const timelineBottom = timelineRect.bottom;
      const canScrollUp = timeline.scrollTop > 0;
      const canScrollDown = timeline.scrollTop < timeline.scrollHeight - timeline.clientHeight;

      const distanceFromTop = mouseY - timelineTop;
      const distanceFromBottom = timelineBottom - mouseY;

      if (distanceFromTop < AUTO_SCROLL_THRESHOLD && canScrollUp) {
        timeline.scrollTop -= AUTO_SCROLL_SPEED;
      } else if (distanceFromBottom < AUTO_SCROLL_THRESHOLD && canScrollDown) {
        timeline.scrollTop += AUTO_SCROLL_SPEED;
      }

      animationFrameId = requestAnimationFrame(scrollLoop);
    };

    animationFrameId = requestAnimationFrame(scrollLoop);

    const flushPendingCommit = () => {
      moveCommitRafRef.current = null;
      const commit = pendingCommitRef.current;
      pendingCommitRef.current = null;
      commit?.();
    };

    const handleMouseMove = (e: MouseEvent, firstMove = false) => {
      dropModifiersRef.current = { altKey: e.altKey, metaKey: e.metaKey, ctrlKey: e.ctrlKey };
      mousePositionRef.current.x = e.clientX;
      mousePositionRef.current.y = e.clientY;

      const rect = clipRef.current?.parentElement?.getBoundingClientRect();
      const timelineRect = timelineRef.current?.getBoundingClientRect();
      if (!rect || !timelineRect) return;

      const x = e.clientX - rect.left - dragOffset;
      const rawTime = Math.max(dragMinimumTimeRef.current, x / pixelsPerSecond);

      const dragSnapSettings = { ...snapSettings, snapToPlayhead: false };
      const snapResult = calculateSnap(
        rawTime,
        clip.id,
        readTracks(),
        useTimelineStore.getState().playheadPosition,
        dragSnapSettings,
        pixelsPerSecond,
        clip.duration,
      );
      snapResult.time = Math.max(dragMinimumTimeRef.current, snapResult.time);
      const currentScrollTop = timelineRef.current?.scrollTop || 0;
      const scrollDelta = currentScrollTop - dragStartRef.current.scrollTop;
      const yDelta = (e.clientY - dragStartRef.current.mouseY) + scrollDelta;
      setDragYOffset(yDelta);

      const scrollTop = timelineRef.current?.scrollTop || 0;
      const mouseY = e.clientY - timelineRect.top + scrollTop - trackTopInset;
      let targetTrackId: string | undefined;
      let hoveredTrackIsLocked = false;
      const dragTracks = readTracks();
      const hoveredId = trackIdAtOffset(dragTracks, rowHeights ?? trackHeights, mouseY);
      const hoveredTrack = dragTracks.find((t) => t.id === hoveredId);
      if (hoveredTrack) {
        hoveredTrackIsLocked = Boolean(hoveredTrack.locked);
        if (!hoveredTrack.locked && hoveredTrack.id !== track.id) targetTrackId = hoveredTrack.id;
      }

      setIsInvalidDrop(hoveredTrackIsLocked);

      pendingDropRef.current = { time: snapResult.time, targetTrackId };

      // Coalesce store commits to one per animation frame. A fast mouse
      // fires many mousemove events between frames; dispatching moveClip on
      // each one deep-clones the project and re-renders the whole editor
      // dozens of extra times per frame, which is what made sustained
      // dragging lag and eventually exhaust memory. We keep the latest move
      // in a ref and flush it once per frame.
      const moveTime = snapResult.time;
      // Keep the same origin as companion snapshots even when project updates
      // reinstall this effect during the gesture.
      const baseStartTime = dragStartTimeRef.current;
      const companions = multiDragSnapshotRef.current;
      const batchSnapshot = batchDragSnapshotRef.current;
      pendingCommitRef.current = () => {
        if (batchSnapshot) {
          // A big selection (select all, a marquee) is one batched move per frame: per-clip moves were O(clips)
          // each, so a 1000-clip drag never finished. The snapshot is the whole editable selection taken from the
          // store (linked partners included), so off-screen clips that are not mounted move with it.
          const deltaTime = moveTime - baseStartTime;
          dragCommitRef.current = moveSelectionBatch(
            batchSnapshot.map((snap) => ({ clipId: snap.clipId, startTime: snap.clipId === clip.id ? moveTime : Math.max(0, snap.startTime + deltaTime) })),
            dragBatchKey,
          );
          return;
        }
        dragCommitRef.current = Promise.resolve(onMoveClip(clip.id, moveTime, undefined));
        // Move every companion clip in the multi-selection by the same delta.
        if (companions.length > 0) {
          const deltaTime = moveTime - baseStartTime;
          for (const snap of companions) {
            const newStart = Math.max(0, snap.startTime + deltaTime);
            dragCommitRef.current = Promise.resolve(onMoveClip(snap.clipId, newStart, undefined));
          }
        }
      };
      if (moveCommitRafRef.current === null) {
        // The activating move has just rendered the drag state in this frame's input phase; committing the first
        // move in the same frame's rAF stacked two timeline renders into one ~50 ms frame. It lands a frame later.
        moveCommitRafRef.current = requestAnimationFrame(
          firstMove ? () => { moveCommitRafRef.current = requestAnimationFrame(flushPendingCommit); } : flushPendingCommit,
        );
      }

      onSnapIndicator(snapResult.snapped && snapResult.snapPoint ? snapResult.snapPoint.time : null);
    };

    const handleMouseUp = async (upEvent?: MouseEvent) => {
      if (upEvent && "altKey" in upEvent)
        dropModifiersRef.current = { altKey: upEvent.altKey, metaKey: upEvent.metaKey, ctrlKey: upEvent.ctrlKey };
      if (animationFrameId !== null) {
        cancelAnimationFrame(animationFrameId);
      }

      // Flush any move queued for the next frame so the clip settles at the
      // final dragged position instead of one frame behind.
      if (moveCommitRafRef.current !== null) {
        cancelAnimationFrame(moveCommitRafRef.current);
        moveCommitRafRef.current = null;
      }
      const pendingCommit = pendingCommitRef.current;
      pendingCommitRef.current = null;

      const { time, targetTrackId } = pendingDropRef.current;
      // A lone clip's queued move is superseded by the drop's own move to the same time, and a second store commit
      // re-renders the whole timeline (about 25 ms at 400 clips, a ~58 ms frame with the drop's). Companions and
      // batches still need the queued move: it is the only one that moves them.
      const lone = !batchDragSnapshotRef.current && multiDragSnapshotRef.current.length === 0;
      if (!lone) pendingCommit?.();
      // The batched path is queued off the gesture; the single-clip path must not yield here (a yield lets the
      // drag's history group close before the final move lands).
      if (batchDragSnapshotRef.current) await dragCommitRef.current;
      // Nothing to apply when the last live move already put the clip at the drop: no pending move, same time,
      // same track.
      const dropTrackId = targetTrackId ?? track.id;
      const placed = lone && !pendingCommit ? findPlacedClip(useProjectStore.getState().project, clip.id) : null;
      const alreadyThere = placed !== null && placed.trackId === dropTrackId && Math.abs(placed.startTime - time) < 1e-9;
      if (!alreadyThere) {
        dragCommitRef.current = Promise.resolve(onMoveClip(clip.id, time, dropTrackId));
        await dragCommitRef.current;
      }
      // Resolve overlaps inside the drag's history group: one undo step.
      const origins = dragOriginsRef.current;
      dragOriginsRef.current = null;
      if (origins) {
        // A drop that cannot be resolved must not leave overlapping clips:
        // put every moved clip back where the drag started.
        const revertDrop = async (reason: string) => {
          toast.warning("Drop not applied", reason);
          await restoreClipOrigins(origins);
        };
        try {
          const store = useProjectStore.getState();
          const plan = planClipDropResolution(
            store.getFullProject(),
            origins,
            clipDropOptionsFromModifiers(dropModifiersRef.current),
            uuidv4(),
          );
          if (plan.edits.length) {
            const result = store.commitTimelineToolEdit(plan);
            if (!result.success) await revertDrop(result.error?.message ?? "The drop could not be resolved.");
          }
        } catch (error) {
          await revertDrop(error instanceof Error ? error.message : "The drop could not be resolved.");
        }
      }
      await closeDragGroup();

      setIsDragging(false);
      setDragYOffset(0);
      setIsInvalidDrop(false);
      onSnapIndicator(null);
      multiDragSnapshotRef.current = [];
      batchDragSnapshotRef.current = null;
    };

    const cancelDrag = () => {
      const cancelledOrigins = dragOriginsRef.current;
      dragOriginsRef.current = null;
      // Live moves may overlap neighbours: put everything back.
      if (cancelledOrigins) dragCommitRef.current = Promise.resolve(dragCommitRef.current).then(() => restoreClipOrigins(cancelledOrigins));
      if (animationFrameId !== null) cancelAnimationFrame(animationFrameId);
      if (moveCommitRafRef.current !== null) cancelAnimationFrame(moveCommitRafRef.current);
      moveCommitRafRef.current = null;
      pendingCommitRef.current = null;
      setIsDragging(false);
      setDragYOffset(0);
      setIsInvalidDrop(false);
      onSnapIndicator(null);
      multiDragSnapshotRef.current = [];
      batchDragSnapshotRef.current = null;
      void closeDragGroup();
    };
    // A quick native drag may have only the movement that crossed the threshold.
    // Prime its final position before listening for the release.
    const activation = dragActivationEventRef.current;
    dragActivationEventRef.current = null;
    if (activation) handleMouseMove(activation, true);
    const stopListening = listenTimelineGesture(touchGesture.pointerId, (move) => handleMouseMove(move), handleMouseUp, cancelDrag);

    return () => {
      if (animationFrameId !== null) {
        cancelAnimationFrame(animationFrameId);
      }
      if (moveCommitRafRef.current !== null) {
        cancelAnimationFrame(moveCommitRafRef.current);
        moveCommitRafRef.current = null;
      }
      pendingCommitRef.current = null;
      stopListening();
      endClipDragActivity();
    };
  }, [
    isDragging,
    touchGesture.pointerId,
    dragOffset,
    pixelsPerSecond,
    clip.id,
    clip.duration,
    track.id,
    readTracks,
    trackHeights,
    rowHeights,
    timelineRef,
    trackTopInset,
    snapSettings,
    onMoveClip,
    onSnapIndicator,
    closeDragGroup,
  ]);

  useEffect(() => {
    if (!isTrimming || !trimEdge || !onTrimClip) return;

    const handleMouseMove = (e: MouseEvent) => {
      const deltaX = e.clientX - trimStartRef.current.mouseX;
      const deltaTime = deltaX / pixelsPerSecond;

      if (trimEdge === "left") {
        const newStartTime = Math.max(
          0,
          trimStartRef.current.startTime + deltaTime,
        );
        const maxStartTime =
          trimStartRef.current.startTime + trimStartRef.current.duration - 0.1;
        const clampedStartTime = Math.min(newStartTime, maxStartTime);
        trimCommitRef.current = Promise.resolve(onTrimClip(clip.id, "left", clampedStartTime));
      } else {
        const newEndTime =
          trimStartRef.current.startTime +
          trimStartRef.current.duration +
          deltaTime;
        const minEndTime = trimStartRef.current.startTime + 0.1;
        const clampedEndTime = Math.max(newEndTime, minEndTime);
        trimCommitRef.current = Promise.resolve(onTrimClip(clip.id, "right", clampedEndTime));
      }
    };

    const closeTrimGroup = async () => {
      await trimCommitRef.current;
      if (trimGroupOpenRef.current) {
        trimGroupOpenRef.current = false;
        useProjectStore.getState().endHistoryGroup();
      }
    };
    const handleMouseUp = async () => {
      await closeTrimGroup();
      setIsTrimming(false);
      setTrimEdge(null);
      document.body.style.cursor = "";
    };

    const stopListening = listenTimelineGesture(touchGesture.pointerId, handleMouseMove, handleMouseUp);

    return () => {
      stopListening();
      void closeTrimGroup();
      document.body.style.cursor = "";
    };
  }, [isTrimming, trimEdge, clip.id, pixelsPerSecond, onTrimClip, touchGesture.pointerId]);

  const thumbnailCount = Math.max(1, Math.floor(width / 60));
  const thumbnailRange = getVisibleRepeatRange(
    left,
    width,
    scrollX,
    viewportWidth,
    thumbnailCount,
  );
  const thumbnailIndices = Array.from(
    { length: thumbnailRange.end - thumbnailRange.start },
    (_, index) => thumbnailRange.start + index,
  );
  const channelWaveform = useChannelWaveform(clip, mediaItem, drawWaveform);
  const waveformBarCount = Math.max(1, Math.floor((width - 8) / 3));
  const waveformRange = getVisibleRepeatRange(
    left,
    width,
    scrollX,
    viewportWidth,
    waveformBarCount,
  );
  const waveformAmplitudes = React.useMemo(
    () =>
      drawWaveform
        ? getClipWaveformBarAmplitudes(channelWaveform, {
            barCount: waveformBarCount,
            startBar: waveformRange.start,
            endBar: waveformRange.end,
            mediaDuration: mediaItem?.metadata.duration ?? 0,
            inPoint: clip.inPoint,
            outPoint: clip.outPoint,
            reversed: clip.reversed,
          })
        : [],
    [
      drawWaveform,
      channelWaveform,
      mediaItem?.metadata.duration,
      waveformBarCount,
      waveformRange.start,
      waveformRange.end,
      clip.inPoint,
      clip.outPoint,
      clip.reversed,
    ],
  );
  const clipName =
    motionComposition?.name ||
    (typeof clip.metadata?.compoundClipName === "string"
      ? clip.metadata.compoundClipName
      : undefined) ||
    mediaItem?.name ||
    clip.mediaId.slice(0, 8);

  const hasLeadingTransitionBadge = info.leadingTransitionBadge;
  const hasTrailingTransitionBadge = info.trailingTransitionBadge;

  const isInteracting = isDragging || isTrimming;
  const keepMounted = isInteracting || isPendingDrag;
  // Lane virtualization must not unmount the element that owns a live gesture.
  useEffect(() => {
    if (!keepMounted) return undefined;
    return pinTimelineClip(clip.id);
  }, [keepMounted, clip.id]);
  const isApplyingEffect = effectApplicationClipId === clip.id;
  const showGainLine = useTimelineStore((state) => state.gainLineTracks[track.id] === true);
  const gainLineTrackHeight = trackHeights.get(track.id) ?? 62;
  const trackBadge = info.trackBadge;
  const hasConfiguredVideoEffects = clip.effects.length > 0 || !!(clip.colorGrading && Object.keys(clip.colorGrading).length);

  return (
    <ContextMenu onOpenChange={setContextMenuOpen}>
      <ContextMenuTrigger asChild>
        <div
          ref={clipRef}
          role="button"
          tabIndex={track.locked ? -1 : 0}
          aria-label={`Select clip ${clipName}`}
          aria-pressed={isSelected}
          onClick={handleClick}
          onDoubleClick={isCompoundClip ? (event) => { event.stopPropagation(); void openNestClip(clip.id); } : undefined}
          data-timeline-clip
          data-timeline-item-id={clip.id}
          data-clip-label={clipLabel?.id ?? "none"}
          data-clip-kind={isAudio ? "audio" : isImage ? "image" : "video"}
          data-timeline-interacting={Boolean(isInteracting)}
          data-applying-effect={isApplyingEffect}
          data-track-badge={trackBadge}
          data-track-role={track.role}
          data-locked={track.locked}
          onPointerDown={touchGesture.bodyPointerDown}
          onMouseDown={handleMouseDown}
          onKeyDown={(event) => {
            if (track.locked || (event.key !== "Enter" && event.key !== " ")) return;
            event.preventDefault();
            event.stopPropagation();
            onSelect(clip.id, event.shiftKey || event.metaKey || event.ctrlKey);
          }}
          onDragOver={handleDragOver}
          onDragLeave={handleDragLeave}
          onDrop={handleDrop}
          className={`group absolute top-[4px] rounded-[4px] overflow-hidden ${
            isDragging
              ? `cursor-grabbing z-50 ${isInvalidDrop ? "opacity-50 ring-2 ring-red-500" : "opacity-90 shadow-lg"}`
              : "cursor-grab"
          } ${
            isSelected && !isDragging
              ? isApplyingEffect
                ? "ring-2 ring-amber-400 z-10"
                : "ring-2 ring-accent z-10"
              : !isDragging ? "hover:brightness-[1.04]" : ""
          } ${clipStyle.bg} border ${clipStyle.border} ${
            track.locked ? "cursor-not-allowed opacity-60" : ""
          }`}
          style={{
            transform: isDragging
              ? `translate(${left}px, ${dragYOffset}px)`
              : `translateX(${left}px)`,
            cursor: tool === "blade" ? "crosshair" : undefined,
            backgroundColor: clipLabel
              ? `color-mix(in srgb, ${clipLabel.color} 42%, #15171b)`
              : track.role === "music" ? "var(--c-music)" : undefined,
            ...(clipLabel ? { borderColor: clipLabel.color } : {}),
            width: `max(1px, calc(${width}px - var(--timeline-clip-inset, 0px) * 2))`,
            marginLeft: "var(--timeline-clip-inset, 0px)",
            height: `${Math.max(20,(trackHeights.get(track.id) ?? 62)-8)}px`,
            willChange: isInteracting ? 'transform, width' : 'auto',
            transition: isInteracting ? 'none' : 'opacity 150ms, box-shadow 150ms',
            // Cross-track targeting uses timeline geometry. Keep the release
            // click on this clip so it cannot clear selection on the background.
            pointerEvents: 'auto',
          }}
        >
      {isSelected && !track.locked && <TimelineTouchMoveHandle label={`Move ${clipName}`} onPointerDown={(event) => touchGesture.start(event, handleMouseDown)} />}
      <RemoteClipSelection clipId={clip.id} />
      {isSelected && <span className="mobile-clip-duration">{clip.duration.toFixed(1)}s</span>}
      {clipLabel && <div data-testid="clip-label-bar" className="pointer-events-none absolute inset-x-0 top-0 z-20 h-[4px]" style={{ backgroundColor: clipLabel.color }} />}
      {isApplyingEffect && (
        <>
          <div className="absolute -inset-px rounded-lg border border-amber-300/80 shadow-[0_0_18px_rgba(251,191,36,0.55)] pointer-events-none animate-pulse" />
          <div className="absolute inset-0 bg-[linear-gradient(110deg,transparent_0%,rgba(255,255,255,0.08)_28%,rgba(251,191,36,0.28)_50%,rgba(255,255,255,0.08)_72%,transparent_100%)] pointer-events-none animate-pulse" />
          <div className="absolute top-1 right-1 rounded-full bg-black/70 px-2 py-0.5 text-[9px] font-medium uppercase tracking-[0.12em] text-amber-200 pointer-events-none">
            {effectApplicationLabel ?? "Applying effect"}
          </div>
        </>
      )}

      {/* Drag-drop hover indicators for effects/transitions */}
      {dragHover === "effect" && (
        <div className="absolute inset-0 ring-2 ring-accent ring-inset rounded-lg bg-accent/15 pointer-events-none z-20" />
      )}
      {dragHover === "transition-left" && (
        <div className="absolute inset-y-0 left-0 w-1/3 pointer-events-none z-20 bg-gradient-to-r from-accent/60 to-transparent">
          <div className="absolute left-0 top-0 bottom-0 w-1 bg-accent" />
        </div>
      )}
      {dragHover === "transition-right" && (
        <div className="absolute inset-y-0 right-0 w-1/3 pointer-events-none z-20 bg-gradient-to-l from-accent/60 to-transparent">
          <div className="absolute right-0 top-0 bottom-0 w-1 bg-accent" />
        </div>
      )}

      {isVideo &&
        (mediaItem?.filmstripThumbnails?.length || mediaItem?.thumbnailUrl) && (
          <div className="absolute inset-0 pointer-events-none">
            {mediaItem?.filmstripThumbnails &&
            mediaItem.filmstripThumbnails.length > 0
              ? thumbnailIndices.map((i) => {
                  const clipProgress = i / Math.max(1, thumbnailCount - 1);
                  const thumbIndex = Math.min(
                    Math.floor(
                      clipProgress * mediaItem.filmstripThumbnails!.length,
                    ),
                    mediaItem.filmstripThumbnails!.length - 1,
                  );
                  const thumb = mediaItem.filmstripThumbnails![thumbIndex];
                  return (
                    <div
                      key={i}
                      className="absolute h-full bg-cover bg-center opacity-70"
                      style={{
                        left: (i * width) / thumbnailCount,
                        width: width / thumbnailCount,
                        backgroundImage: `url(${thumb.url})`,
                        borderRight:
                          i < thumbnailCount - 1
                            ? "1px solid rgba(0,0,0,0.2)"
                            : "none",
                      }}
                    />
                  );
                })
              : thumbnailIndices.map((i) => (
                  <div
                    key={i}
                    className="absolute h-full bg-cover bg-center opacity-60"
                    style={{
                      left: (i * width) / thumbnailCount,
                      width: width / thumbnailCount,
                      backgroundImage: `url(${mediaItem.thumbnailUrl})`,
                      borderRight:
                        i < thumbnailCount - 1
                          ? "1px solid rgba(0,0,0,0.2)"
                          : "none",
                    }}
                  />
                ))}
          </div>
        )}

      {isVideo && !mediaItem?.thumbnailUrl && (
        <div className="absolute inset-0 bg-gradient-to-r from-primary/20 to-primary/10 pointer-events-none" />
      )}

      {isImage && (
        <div className="absolute inset-0 bg-gradient-to-r from-primary/20 to-primary/10 flex items-center justify-center pointer-events-none">
          {mediaItem?.thumbnailUrl ? (
            <img
              src={mediaItem.thumbnailUrl}
              alt={clipName}
              className="h-full object-cover opacity-60"
            />
          ) : (
            <Image size={24} className="text-primary/50" />
          )}
        </div>
      )}

      {isMotionClip && (
        <div className="absolute inset-0 flex items-center justify-center bg-gradient-to-r from-teal-500/30 via-cyan-500/20 to-slate-500/20 pointer-events-none">
          <Box size={22} className="text-teal-100/70" />
        </div>
      )}

      {isCompoundClip && (
        <div
          className="absolute inset-0 flex items-center justify-center bg-gradient-to-r from-violet-600/80 via-fuchsia-600/65 to-violet-500/70 pointer-events-none"
          style={
            typeof clip.metadata?.compoundClipColor === "string"
              ? { backgroundColor: clip.metadata.compoundClipColor }
              : undefined
          }
        >
          <Layers size={22} className="text-white/75" />
        </div>
      )}

      <span
        className={`workspace-clip-label absolute truncate z-10 pointer-events-none text-[11px] font-semibold ${
          isAudio ? "top-0.5" : "top-0.5"
        } ${hasLeadingTransitionBadge ? "left-[18px]" : "left-1.5"} ${
          hasTrailingTransitionBadge ? "right-[18px]" : "right-2"
        } ${
          isSelected ? clipStyle.selectedText : clipStyle.text
        }`}
        style={isAudio ? undefined : { background: "var(--c-video)", left: 0, right: 0, top: 0, padding: "var(--timeline-video-label-padding, 1px 5px)", height: "var(--timeline-video-label-height, 17px)" }}
      >
        <span className="min-w-0 truncate">
        {clipName}
        {isAudio && Math.abs(clip.volume - 1) > 0.0001 && (
          <> · {clip.volume > 0 ? `${(20 * Math.log10(clip.volume)).toFixed(1).replace(/\.0$/, "").replace("-", "−")} dB` : "−∞ dB"}</>
        )}
        </span>
        {!isAudio && hasConfiguredVideoEffects && <span role="img" aria-label="Video effects configured" className="workspace-timeline-effect-badge">fx</span>}
        {clip.audioType && (
          <span
            data-testid="clip-audio-type-chip"
            data-audio-type={clip.audioType}
            title={`Audio type: ${AUDIO_TYPE_LABELS[clip.audioType]}`}
            className="ml-1 inline-block rounded-[3px] bg-black/45 px-1 align-middle text-[8px] font-bold uppercase leading-[12px] tracking-wide text-white/90"
          >
            {AUDIO_TYPE_LABELS[clip.audioType]}
          </span>
        )}
      </span>

      {drawWaveform && (
        <svg
          className="absolute left-0 bottom-0 w-full pointer-events-none"
          data-clip-waveform={isAudio ? "audio" : "embedded"}
          aria-hidden
          height={isAudio ? 28 : 18}
          style={isAudio ? undefined : { opacity: 0.75, background: "linear-gradient(transparent, #0a0a0c99)" }}
          preserveAspectRatio="none"
          viewBox={`0 0 ${Math.max(1, width)} 28`}
        >
          {waveformAmplitudes.map((amplitude, i) => {
            const h = Math.min(24, amplitude * 26);
            return (
              <rect
                key={waveformRange.start + i}
                x={(waveformRange.start + i) * 3 + 4}
                y={14 - h / 2}
                width="2"
                rx="1"
                height={h}
                fill={track.role === "music" ? "var(--c-music-waveform)" : "var(--c-audio-waveform)"}
              />
            );
          })}
        </svg>
      )}

      {isAudio && <AudioClipFade clip={clip} width={width} music={track.role === "music"} />}
      {isAudio && showGainLine && gainLineTrackHeight >= GAIN_LINE_MIN_TRACK_HEIGHT && (
        <ClipGainLine
          clip={clip}
          width={width}
          height={Math.max(20, gainLineTrackHeight - 8) - 2}
          locked={Boolean(track.locked)}
          music={track.role === "music"}
        />
      )}

      {clip.keyframes && clip.keyframes.length > 0 && (
        <div className="absolute bottom-0 left-0 right-0 h-3 flex items-center pointer-events-none">
          {clip.keyframes.map((kf) => {
            const relativeTime = kf.time - clip.startTime;
            if (relativeTime < 0 || relativeTime > clip.duration) return null;
            const posPercent = (relativeTime / clip.duration) * 100;
            return (
              <div
                key={kf.id}
                className="absolute w-2 h-2 bg-yellow-400 rotate-45 border border-yellow-600"
                style={{ left: `${posPercent}%`, marginLeft: "-4px" }}
                title={`${kf.property} @ ${kf.time.toFixed(2)}s`}
              />
            );
          })}
        </div>
      )}

      {(clip.markers?.length || mediaItem?.markers?.length) ? (
        <ClipMarkerFlags clip={clip} media={mediaItem} pixelsPerSecond={pixelsPerSecond} />
      ) : null}
      {splitOffset && <SplitEditBadge offsets={splitOffset} frameRate={frameRate} />}
      {(isVideo || isImage || isAudio) && onTrimClip && (
        <>
          <div
            data-timeline-trim="left"
            aria-label={`Trim start of ${clipName}`}
            onPointerDown={(event) => touchGesture.start(event, handleTrimMouseDown("left"))}
            onMouseDown={handleTrimMouseDown("left")}
            data-edit-point-selected={editPointEdge === "left" ? editPointKind : undefined}
            className={`absolute left-0 top-0 bottom-0 w-2 cursor-ew-resize z-20 flex items-center justify-center transition-opacity ${
              isSelected || editPointEdge === "left" ? "opacity-100" : "opacity-0 group-hover:opacity-100"
            } ${editPointEdge === "left" ? (editPointKind === "roll" ? "bg-amber-400" : "bg-red-500") : isSelected ? "bg-primary" : isAudio ? "hover:bg-blue-400/50" : isVideo ? "hover:bg-green-400/50" : "hover:bg-primary/50"}`}
            style={{ borderRadius: "6px 0 0 6px" }}
            onClick={handleEditPointClick("left")}
          >
            {isSelected && (
              <div className="w-0.5 h-3 bg-primary-foreground/80 rounded-full" />
            )}
          </div>
          <div
            data-timeline-trim="right"
            aria-label={`Trim end of ${clipName}`}
            onPointerDown={(event) => touchGesture.start(event, handleTrimMouseDown("right"))}
            onMouseDown={handleTrimMouseDown("right")}
            data-edit-point-selected={editPointEdge === "right" ? editPointKind : undefined}
            className={`absolute right-0 top-0 bottom-0 w-2 cursor-ew-resize z-20 flex items-center justify-center transition-opacity ${
              isSelected || editPointEdge === "right" ? "opacity-100" : "opacity-0 group-hover:opacity-100"
            } ${editPointEdge === "right" ? (editPointKind === "roll" ? "bg-amber-400" : "bg-red-500") : isSelected ? "bg-primary" : isAudio ? "hover:bg-blue-400/50" : isVideo ? "hover:bg-green-400/50" : "hover:bg-primary/50"}`}
            style={{ borderRadius: "0 6px 6px 0" }}
            onClick={handleEditPointClick("right")}
          >
            {isSelected && (
              <div className="w-0.5 h-3 bg-primary-foreground/80 rounded-full" />
            )}
          </div>
        </>
      )}

        </div>
      </ContextMenuTrigger>
      {contextMenuOpen && <ClipContextMenu clip={clip} track={liveTrackFor(track)} />}
    </ContextMenu>
  );
};

/** The context menu reads sibling clips: give it the current track, not the one from the last render. */
function liveTrackFor(track: Track): Track {
  return useProjectStore.getState().project.timeline.tracks.find((candidate) => candidate.id === track.id) ?? track;
}

type ClipProps = React.ComponentProps<typeof ClipComponentImpl>;

/**
 * With `laneInfo` supplied the lane has already folded every cross-clip input into
 * primitives, so the track list identity and the track's clip array (both replaced by
 * any move on any lane) are irrelevant to this clip. Everything else compares shallowly.
 */
function areClipPropsEqual(prev: ClipProps, next: ClipProps): boolean {
  const lane = next.laneInfo !== undefined && next.getAllTracks !== undefined;
  const keys = new Set([...Object.keys(prev), ...Object.keys(next)]) as Set<keyof ClipProps>;
  for (const key of keys) {
    if (Object.is(prev[key], next[key])) continue;
    if (lane && key === "allTracks") continue;
    if (lane && key === "track") {
      const a = prev.track;
      const b = next.track;
      if (a.id === b.id && a.type === b.type && a.locked === b.locked && a.role === b.role && a.name === b.name) continue;
    }
    return false;
  }
  return true;
}

/** Companions at or above this count move through one batched store action instead of one per clip. */
const BATCH_DRAG_COMPANIONS = 8;

let batchQueue: Promise<unknown> = Promise.resolve();
/** Serialised, one-history-entry-per-drag batch move of a big selection (media clips; overlays follow singly). */
function moveSelectionBatch(
  moves: ReadonlyArray<{ clipId: string; startTime: number }>,
  coalesceKey: string,
): Promise<void> {
  const run = batchQueue.then(async () => {
    const store = useProjectStore.getState();
    const mediaClips = new Map<string, Clip>();
    for (const track of store.project.timeline.tracks) for (const c of track.clips) mediaClips.set(c.id, c);
    const mediaMoves = moves.filter((move) => mediaClips.has(move.clipId));
    const overlayMoves = moves.filter((move) => !mediaClips.has(move.clipId));
    const captions = (store.project.textClips?.length ?? 0) > 0
      ? mediaMoves.map((move) => ({ source: mediaClips.get(move.clipId)!, startTime: move.startTime }))
      : [];
    if (mediaMoves.length) {
      const result = await store.moveClips([...mediaMoves], { coalesceKey });
      if (result.success) {
        // Captions follow their source clip, each caption once (the per-clip path does the same).
        const moved = new Set<string>();
        for (const { source, startTime } of captions) {
          const now = useProjectStore.getState();
          moveLinkedCaptions(
            {
              project: now.project,
              getAllTextClips: () => now.getAllTextClips().filter((caption) => !moved.has(caption.id)),
              updateOverlayClipTiming: (id, updates) => { moved.add(id); return now.updateOverlayClipTiming(id, updates); },
              deleteTextClip: () => false,
            },
            source,
            startTime,
          );
        }
      }
    }
    for (const move of overlayMoves) {
      // Text, shape, SVG and sticker clips keep their per-item timing update.
      useProjectStore.getState().updateOverlayClipTiming(move.clipId, { startTime: move.startTime });
    }
  }).catch((error: unknown) => {
    toast.error("Move failed", error instanceof Error ? error.message : "Please try again.");
  });
  batchQueue = run;
  return run;
}

/** Move every clip that left its drag origin back to it. */
async function restoreClipOrigins(origins: ReadonlyMap<string, ClipOrigin>): Promise<void> {
  const store = useProjectStore.getState();
  const moves: Array<{ clipId: string; startTime: number; trackId: string }> = [];
  for (const t of store.getFullProject().timeline.tracks)
    for (const c of t.clips) {
      const o = origins.get(c.id);
      if (o && (o.trackId !== t.id || Math.abs(o.startTime - c.startTime) > 1e-6))
        moves.push({ clipId: c.id, startTime: o.startTime, trackId: o.trackId });
    }
  if (moves.length) await store.moveClips(moves);
}

export const ClipComponent = React.memo(ClipComponentImpl, areClipPropsEqual);