/* global React */
// Stadium-anthem music toggle in the nav.
// Browser autoplay policy: audio must start muted OR follow a user click.
// We attempt muted autoplay on mount, then a click on the speaker icon unmutes.
const { useState: useS_MUSIC, useEffect: useFX_MUSIC, useRef: useREF_MUSIC } = React;

function MusicToggle() {
  const ref = useREF_MUSIC(null);
  const [playing, setPlaying] = useS_MUSIC(false);
  const [muted, setMuted] = useS_MUSIC(true);
  const [failed, setFailed] = useS_MUSIC(false);

  // Only set src if BGM is explicitly configured — otherwise we'd log a 404 for assets/anthem.mp3.
  const src = (window.GB_CONFIG && window.GB_CONFIG.bgm) || null;
  const startSec = (window.GB_CONFIG && window.GB_CONFIG.bgmStartSec) || 0;

  useFX_MUSIC(() => {
    if (!src) { setFailed(true); return; }
    const a = ref.current;
    if (!a) return;
    a.volume = 0.55;
    a.loop = true;
    a.muted = true;
    const onCanPlay = () => {
      if (startSec > 0 && a.currentTime < startSec) {
        try { a.currentTime = startSec; } catch (e) {}
      }
    };
    const onError = () => setFailed(true);
    a.addEventListener("canplay", onCanPlay);
    a.addEventListener("error", onError);
    // Loop back to start point, not to track origin (so the intro stays skipped)
    a.addEventListener("ended", () => { try { a.currentTime = startSec; a.play(); } catch (e) {} });
    a.play().then(() => setPlaying(true)).catch(() => setPlaying(false));

    // Unmute on first user gesture — wallet click, anywhere click, touch, keypress.
    // Browser autoplay policy allows audio with sound once user has interacted.
    let done = false;
    const unmute = () => {
      if (done) return;
      done = true;
      if (a.paused) { a.play().catch(() => {}); }
      a.muted = false;
      setMuted(false);
      setPlaying(true);
      window.removeEventListener("click", unmute);
      window.removeEventListener("touchstart", unmute);
      window.removeEventListener("keydown", unmute);
      window.removeEventListener("gb:unmute-bgm", unmute);
    };
    window.addEventListener("click", unmute, { once: true, passive: true });
    window.addEventListener("touchstart", unmute, { once: true, passive: true });
    window.addEventListener("keydown", unmute, { once: true, passive: true });
    // Explicit hook — wallet button + other deliberate triggers fire this event
    window.addEventListener("gb:unmute-bgm", unmute);

    return () => {
      a.removeEventListener("canplay", onCanPlay);
      a.removeEventListener("error", onError);
      window.removeEventListener("click", unmute);
      window.removeEventListener("touchstart", unmute);
      window.removeEventListener("keydown", unmute);
      window.removeEventListener("gb:unmute-bgm", unmute);
    };
  }, []);

  const toggle = () => {
    const a = ref.current;
    if (!a || failed || !src) {
      alert("BGM 未配置 — 请把 mp3 放到 assets/anthem.mp3 或在 HTML 中设置 window.GB_CONFIG.bgm");
      return;
    }
    if (!playing) {
      a.play().then(() => { setPlaying(true); a.muted = false; setMuted(false); });
    } else if (muted) {
      a.muted = false;
      setMuted(false);
    } else {
      a.muted = true;
      setMuted(true);
    }
  };

  return (
    <>
      {src && <audio ref={ref} src={src} preload="auto"></audio>}
      <button className={`b-music ${playing && !muted ? 'live' : ''} ${failed ? 'failed' : ''}`} onClick={toggle} title={failed ? "BGM not configured" : muted ? "Tap to unmute anthem" : "Mute"}>
        {muted || failed ? (
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M11 5 L6 9 H2 V15 H6 L11 19 Z"/>
            <path d="M22 9 L16 15 M16 9 L22 15"/>
          </svg>
        ) : (
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M11 5 L6 9 H2 V15 H6 L11 19 Z"/>
            <path d="M15.5 8.5 A4 4 0 0 1 15.5 15.5"/>
            <path d="M18.5 5.5 A8 8 0 0 1 18.5 18.5"/>
          </svg>
        )}
        <span className="b-music-label">{failed ? "Anthem · setup" : muted ? "Anthem" : "♪ Anthem"}</span>
      </button>
    </>
  );
}

window.MusicToggle = MusicToggle;
