// Audio controller — plays narration + SFX in sync with the Stage playhead.
// Uses useTime() to read the current time and triggers/seeks audio elements
// based on scheduled start times.

const AUDIO_TRACKS = [
  { id: 'vo1',   src: 'assets/audio/vo_01_hook.mp3',    start: 0.4,  vol: 0.95, kind: 'vo' },
  { id: 'vo2',   src: 'assets/audio/vo_02_anatomy.mp3', start: 5.3,  vol: 0.95, kind: 'vo' },
  { id: 'vo3',   src: 'assets/audio/vo_03_phone.mp3',   start: 16.3, vol: 0.95, kind: 'vo' },
  { id: 'vo4',   src: 'assets/audio/vo_04_report.mp3',  start: 30.4, vol: 0.95, kind: 'vo' },
  { id: 'vo5',   src: 'assets/audio/vo_05_cta.mp3',     start: 42.3, vol: 1.0,  kind: 'vo' },
  { id: 'thunk', src: 'assets/audio/sfx_thunk.mp3',     start: 1.1,  vol: 0.55, kind: 'sfx' },
  { id: 'ding',  src: 'assets/audio/sfx_ding.mp3',      start: 30.6, vol: 0.35, kind: 'sfx' },
];

function AudioController({ muted, volume }) {
  const { time, playing } = useTimeline();
  const elsRef = React.useRef({});
  const lastTimeRef = React.useRef(0);

  // Create audio elements once
  React.useEffect(() => {
    AUDIO_TRACKS.forEach(t => {
      if (!elsRef.current[t.id]) {
        const a = new Audio(t.src);
        a.preload = 'auto';
        elsRef.current[t.id] = a;
      }
    });
    return () => {
      Object.values(elsRef.current).forEach(a => { try { a.pause(); } catch {} });
    };
  }, []);

  // Apply mute + volume
  React.useEffect(() => {
    AUDIO_TRACKS.forEach(t => {
      const a = elsRef.current[t.id];
      if (!a) return;
      a.muted = muted;
      a.volume = Math.max(0, Math.min(1, t.vol * volume));
    });
  }, [muted, volume]);

  // Sync playback with timeline
  React.useEffect(() => {
    const prev = lastTimeRef.current;
    const cur = time;
    lastTimeRef.current = cur;

    AUDIO_TRACKS.forEach(t => {
      const a = elsRef.current[t.id];
      if (!a) return;
      const dur = isFinite(a.duration) ? a.duration : 60;
      const shouldPlay = playing && !muted && cur >= t.start && cur < t.start + dur;

      if (shouldPlay) {
        // If we just entered the window OR we scrubbed backward, (re)start
        const crossedStart = prev < t.start && cur >= t.start;
        const scrubbed = Math.abs(cur - prev) > 0.35;
        const targetTime = cur - t.start;

        if (a.paused || crossedStart || scrubbed) {
          try {
            a.currentTime = Math.max(0, targetTime);
            a.play().catch(() => {});
          } catch {}
        }
      } else {
        if (!a.paused) {
          try { a.pause(); } catch {}
        }
      }
    });
  }, [time, playing, muted]);

  return null;
}

window.AudioController = AudioController;
window.AUDIO_TRACKS = AUDIO_TRACKS;
