// audio.jsx — Audio orchestration for the sizzle reel.
// Tracks are cued to scene ranges; the audio element's currentTime is
// driven by the reel's timeline state so scrubbing works.

// Tracks: each has {src, startIn (in song), startReel, endReel, fadeIn, fadeOut, label}
// currentTime offset: when reel hits startReel, song plays from startIn.
const AUDIO_TRACKS = [
  {
    id: 'thing-of-beauty',
    src: (window.__ASSETS && window.__ASSETS['thing-of-beauty']) || 'audio/thing-of-beauty.mp3',
    label: 'Thing of Beauty — Danger Twins',
    startIn: 54,        // hook at 0:54 of song
    startReel: 0,       // plays from reel time 0
    endReel: 60,        // runs the whole reel
    fadeIn: 0.6,
    fadeOut: 2.0,
    volume: 0.85,
  },
];

function AudioController() {
  const { time, playing } = useTimeline();
  const [armed, setArmed] = React.useState(false);   // user gesture received
  const [muted, setMuted] = React.useState(false);
  const audioRefs = React.useRef({});

  // Build one <audio> per track, keyed by id
  React.useEffect(() => {
    AUDIO_TRACKS.forEach(t => {
      if (!audioRefs.current[t.id]) {
        const a = new Audio(t.src);
        a.preload = 'auto';
        a.volume = 0;
        audioRefs.current[t.id] = a;
      }
    });
    return () => {
      Object.values(audioRefs.current).forEach(a => { try { a.pause(); } catch {} });
    };
  }, []);

  // Sync each track to the timeline
  React.useEffect(() => {
    if (!armed) return;
    AUDIO_TRACKS.forEach(t => {
      const a = audioRefs.current[t.id];
      if (!a) return;
      const inRange = time >= t.startReel && time < t.endReel;

      if (inRange && playing && !muted) {
        // Compute where in the song we should be
        const targetTime = t.startIn + (time - t.startReel);
        // Only re-seek if drift > 0.25s to avoid jitter
        if (Math.abs(a.currentTime - targetTime) > 0.25 && Number.isFinite(targetTime)) {
          try { a.currentTime = targetTime; } catch {}
        }

        // Fade volume at edges
        const fadeInAmt = clamp((time - t.startReel) / t.fadeIn, 0, 1);
        const fadeOutAmt = clamp((t.endReel - time) / t.fadeOut, 0, 1);
        const vol = Math.min(fadeInAmt, fadeOutAmt) * (t.volume ?? 1);
        a.volume = muted ? 0 : vol;

        if (a.paused) { a.play().catch(() => {}); }
      } else {
        if (!a.paused) { try { a.pause(); } catch {} }
      }
    });
  }, [time, playing, armed, muted]);

  // Arm on first user gesture anywhere on the page
  React.useEffect(() => {
    if (armed) return;
    const arm = () => setArmed(true);
    window.addEventListener('click', arm, { once: true });
    window.addEventListener('keydown', arm, { once: true });
    return () => {
      window.removeEventListener('click', arm);
      window.removeEventListener('keydown', arm);
    };
  }, [armed]);

  // UI: sound toggle + initial "tap for sound" hint
  return (
    <>
      {!armed && (
        <div
          onClick={() => setArmed(true)}
          style={{
            position: 'absolute',
            inset: 0,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            background: 'rgba(0,0,0,0.45)',
            cursor: 'pointer',
            zIndex: 50,
            backdropFilter: 'blur(4px)',
          }}
        >
          <div style={{
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 18,
            padding: '36px 56px',
            border: '1px solid rgba(212, 184, 138, 0.4)',
            background: 'rgba(12,10,8,0.72)',
          }}>
            <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="#d4b88a" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
              <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/>
              <path d="M15.54 8.46a5 5 0 0 1 0 7.07"/>
              <path d="M19.07 4.93a10 10 0 0 1 0 14.14"/>
            </svg>
            <div style={{
              fontFamily: 'Nimbus Sans, Helvetica Neue, sans-serif',
              fontSize: 12, letterSpacing: '0.35em',
              color: '#d4b88a', textTransform: 'uppercase',
            }}>
              Click to play with sound
            </div>
            <div style={{
              fontFamily: 'Nimbus Sans, Helvetica Neue, sans-serif',
              fontSize: 10, letterSpacing: '0.22em',
              color: 'rgba(246,241,228,0.5)', textTransform: 'uppercase',
            }}>
              Thing of Beauty  ·  Danger Twins
            </div>
          </div>
        </div>
      )}

      {armed && (
        <div
          onClick={(e) => { e.stopPropagation(); setMuted(m => !m); }}
          title={muted ? 'Unmute' : 'Mute'}
          style={{
            position: 'absolute',
            top: 44, right: 170,
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '8px 14px',
            border: '1px solid rgba(212, 184, 138, 0.28)',
            background: 'rgba(12,10,8,0.55)',
            cursor: 'pointer',
            zIndex: 40,
          }}
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#d4b88a" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
            {muted ? (
              <>
                <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/>
                <line x1="23" y1="9" x2="17" y2="15"/>
                <line x1="17" y1="9" x2="23" y2="15"/>
              </>
            ) : (
              <>
                <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/>
                <path d="M15.54 8.46a5 5 0 0 1 0 7.07"/>
              </>
            )}
          </svg>
          <div style={{
            fontFamily: 'Nimbus Sans, Helvetica Neue, sans-serif',
            fontSize: 9, letterSpacing: '0.3em',
            color: '#d4b88a', textTransform: 'uppercase',
          }}>
            {muted ? 'Muted' : 'Sound on'}
          </div>
        </div>
      )}
    </>
  );
}

Object.assign(window, { AudioController, AUDIO_TRACKS });
