/* Chapter-aware audio chip + now-playing toast.
   - Single <audio> element. Tracks change per active chapter.
   - User must click chip once to enable playback (browser autoplay policy).
   - Once enabled, chapter changes cross-fade tracks automatically.
   - Toast surfaces briefly when track changes ("now playing — Built for Love · PJ Morton"). */

const { useState: useStateAudio, useEffect: useEffectAudio, useRef: useRefAudio } = React;

function ChapterAudio({ activeChapter, chapters }) {
  const audioRef = useRefAudio(null);
  const [enabled, setEnabled] = useStateAudio(false);
  const [muted,   setMuted]   = useStateAudio(false);
  const [toast,   setToast]   = useStateAudio(null);
  const lastChapterId = useRefAudio(null);
  const fadeTimer = useRefAudio(null);
  const duckedRef = useRefAudio(0); // count of videos currently unmuted

  // duck/restore when a video unmutes/mutes
  useEffectAudio(() => {
    function onPause() {
      duckedRef.current += 1;
      const a = audioRef.current;
      if (a && enabled && !muted) fadeTo(a, 0, 250);
    }
    function onResume() {
      duckedRef.current = Math.max(0, duckedRef.current - 1);
      if (duckedRef.current > 0) return;
      const a = audioRef.current;
      if (a && enabled && !muted) fadeTo(a, 1, 400);
    }
    window.addEventListener('chapter-audio-pause', onPause);
    window.addEventListener('chapter-audio-resume', onResume);
    return () => {
      window.removeEventListener('chapter-audio-pause', onPause);
      window.removeEventListener('chapter-audio-resume', onResume);
    };
  }, [enabled, muted]);

  // when activeChapter changes (and audio is enabled), cross-fade to new track
  useEffectAudio(() => {
    if (!enabled) return;
    if (!activeChapter) return;
    if (lastChapterId.current === activeChapter.id) return;
    lastChapterId.current = activeChapter.id;

    const a = audioRef.current;
    if (!a) return;

    const next = activeChapter.track || {};
    if (!next.file) {
      // no audio file yet — show toast anyway
      showToast(next, true);
      return;
    }

    // fade out current, swap src, fade in
    fadeTo(a, 0, 400, () => {
      a.src = next.file;
      a.loop = true;
      const p = a.play();
      if (p && p.catch) p.catch(() => {});
      fadeTo(a, muted ? 0 : 1, 600);
      showToast(next, false);
    });
  }, [activeChapter && activeChapter.id, enabled]);

  function fadeTo(a, target, ms, done) {
    if (fadeTimer.current) clearInterval(fadeTimer.current);
    const start = a.volume;
    const steps = 20;
    let i = 0;
    fadeTimer.current = setInterval(() => {
      i++;
      a.volume = Math.max(0, Math.min(1, start + (target - start) * (i / steps)));
      if (i >= steps) {
        clearInterval(fadeTimer.current);
        if (done) done();
      }
    }, ms / steps);
  }

  function showToast(track, fileMissing) {
    setToast({ ...track, fileMissing });
    setTimeout(() => setToast(null), 4200);
  }

  function handleEnable() {
    setEnabled(true);
    // immediately load + play current chapter's track
    const a = audioRef.current;
    if (a && activeChapter && activeChapter.track && activeChapter.track.file) {
      a.src = activeChapter.track.file;
      a.loop = true;
      a.volume = 0;
      const p = a.play();
      if (p && p.catch) p.catch(() => {});
      fadeTo(a, 1, 600);
      showToast(activeChapter.track, false);
      lastChapterId.current = activeChapter.id;
    } else if (activeChapter && activeChapter.track) {
      showToast(activeChapter.track, true);
      lastChapterId.current = activeChapter.id;
    }
  }

  function toggleMute() {
    const a = audioRef.current;
    if (!a) return;
    const next = !muted;
    setMuted(next);
    fadeTo(a, next ? 0 : 1, 250);
  }

  return (
    <>
      {/* Chip */}
      <div
        className={`audio-chip${enabled && !muted ? ' playing' : ''}`}
        onClick={enabled ? toggleMute : handleEnable}
        role="button" tabIndex={0}
        onKeyDown={(e) => (e.key === 'Enter' || e.key === ' ') && (enabled ? toggleMute() : handleEnable())}
        title={enabled ? (muted ? 'unmute' : 'mute') : 'tap to begin the soundtrack'}
      >
        <span className="dot" />
        <span style={{ fontStyle: 'italic' }}>
          {!enabled
            ? 'tap to begin'
            : muted
              ? 'muted — tap to unmute'
              : (activeChapter && activeChapter.track
                  ? `now playing — ${activeChapter.track.title}`
                  : 'soundtrack on')}
        </span>
        <audio ref={audioRef} />
      </div>

      {/* Now-playing toast */}
      {toast && (
        <div className="np-toast">
          <div className="np-eyebrow">NOW PLAYING</div>
          <div className="np-title">{toast.title || '—'}</div>
          <div className="np-artist">{toast.artist || ''}</div>
          {toast.fileMissing && (
            <div className="np-missing">drop the .mp3 in /audio to enable</div>
          )}
        </div>
      )}
    </>
  );
}

window.ChapterAudio = ChapterAudio;
