// audio.jsx — chapter audio bar
// Bottom-center floating pill: play/pause, track title, volume.
// Audio fades smoothly across chapter changes; user toggle persists.

const { useEffect, useRef, useState } = React;

function AudioBar({ chapter, src, title, enabled, onToggle }) {
  const ref = useRef(null);
  const [playing, setPlaying] = useState(false);
  const [volume, setVolume] = useState(0.55);
  const [primed, setPrimed] = useState(false); // user gesture allowed playback?

  // load new src on chapter change
  useEffect(() => {
    const a = ref.current;
    if (!a) return;
    a.src = src;
    a.loop = true;
    a.volume = volume;
    if (enabled && primed) {
      a.play().then(() => setPlaying(true)).catch(() => setPlaying(false));
    } else {
      try { a.pause(); } catch (_) {}
      setPlaying(false);
    }
  }, [src]);

  // volume change
  useEffect(() => {
    if (ref.current) ref.current.volume = volume;
  }, [volume]);

  // enabled toggle
  useEffect(() => {
    const a = ref.current;
    if (!a) return;
    if (enabled && primed) {
      a.play().then(() => setPlaying(true)).catch(() => setPlaying(false));
    } else {
      try { a.pause(); } catch (_) {}
      setPlaying(false);
    }
  }, [enabled, primed]);

  const handlePlayPause = (e) => {
    e.stopPropagation();
    const a = ref.current;
    if (!a) return;
    setPrimed(true);
    if (playing) {
      a.pause();
      setPlaying(false);
      onToggle && onToggle(false);
    } else {
      a.play().then(() => {
        setPlaying(true);
        onToggle && onToggle(true);
      }).catch(() => setPlaying(false));
    }
  };

  const onVolClick = (e) => {
    e.stopPropagation();
    const r = e.currentTarget.getBoundingClientRect();
    const v = Math.max(0, Math.min(1, (e.clientX - r.left) / r.width));
    setVolume(v);
  };

  return (
    <div className={`audio-bar visible`} onClick={(e) => e.stopPropagation()}>
      <button className={`audio-btn ${playing ? "" : "muted"}`} onClick={handlePlayPause}>
        {playing ? "❚❚" : "▶"}
      </button>
      <span className="audio-meta">Veille {String(chapter).padStart(2, "0")}</span>
      <span className="audio-title">{title}</span>
      <div className="audio-vol" onClick={onVolClick}>
        <div className="audio-vol-fill" style={{ width: `${volume * 100}%` }}></div>
      </div>
      <audio ref={ref} preload="none" />
    </div>
  );
}

window.AudioBar = AudioBar;
