// Pick the topmost video clip that contains the playhead.

import { useEditor } from '@/store/editor';

export interface ActiveVideo {
  clipId: string;
  assetId: string;
  url: string;
  sourceIn: number;
  start: number;
  duration: number;
  trackId: string;
  background?: { color: string; blur: boolean };
}

/**
 * Walks video tracks top-down so the last-encountered clip wins — this
 * mirrors how the export overlays them in `lib/ffmpeg/filter-graph`.
 */
export function findActiveVideo(
  state: ReturnType<typeof useEditor.getState>,
  t: number,
): ActiveVideo | null {
  const videoTracks = state.tracks.filter((tr) => tr.kind === 'video');
  for (let i = videoTracks.length - 1; i >= 0; i--) {
    const track = videoTracks[i];
    const clip = state.clips.find(
      (c) => c.trackId === track.id && t >= c.start && t < c.start + c.duration,
    );
    if (!clip) continue;
    const asset = state.assets.find((a) => a.id === clip.assetId);
    if (!asset) continue;
    return {
      clipId: clip.id,
      assetId: asset.id,
      url: asset.url,
      sourceIn: clip.sourceIn,
      start: clip.start,
      duration: clip.duration,
      trackId: track.id,
      background: track.background,
    };
  }
  return null;
}