// Background song: starts on the first tap (browsers block autoplay),
// loops, fades in, and can be muted from a small corner button.
(function () {
  const { useRef, useState, useCallback, useEffect } = React;

  const SONG_URL =
    "https://pub-790262e0aebb4a07bab23513f2058a1b.r2.dev/wave%20to%20earth%20-%20love.%20(Official%20Lyric%20Video).mp3";
  const TARGET_VOLUME = 0.6;
  const FADE_MS = 2500;
  const FADE_STEP_MS = 50;

  function useBackgroundMusic() {
    const audioRef = useRef(null);
    const fadeRef = useRef(null);
    const [isMuted, setIsMuted] = useState(false);
    const [hasFailed, setHasFailed] = useState(false);

    useEffect(() => {
      const audio = new Audio(SONG_URL);
      audio.loop = true;
      audio.preload = "auto";
      audio.volume = 0;
      const onError = () => setHasFailed(true);
      audio.addEventListener("error", onError);
      audioRef.current = audio;
      return () => {
        clearInterval(fadeRef.current);
        audio.removeEventListener("error", onError);
        audio.pause();
      };
    }, []);

    // Must be called from a click handler so the browser allows sound.
    const play = useCallback(() => {
      const audio = audioRef.current;
      if (!audio || !audio.paused) return;
      audio.volume = 0;
      audio.play().catch((err) => {
        console.warn("Background music could not start:", err);
        setHasFailed(true);
      });
      clearInterval(fadeRef.current);
      const step = TARGET_VOLUME / (FADE_MS / FADE_STEP_MS);
      fadeRef.current = setInterval(() => {
        const next = Math.min(TARGET_VOLUME, audio.volume + step);
        audio.volume = next;
        if (next >= TARGET_VOLUME) clearInterval(fadeRef.current);
      }, FADE_STEP_MS);
    }, []);

    const toggleMute = useCallback(() => {
      const audio = audioRef.current;
      if (!audio) return;
      const nextMuted = !audio.muted;
      audio.muted = nextMuted;
      setIsMuted(nextMuted);
      if (!nextMuted && audio.paused) play();
    }, [play]);

    return { play, toggleMute, isMuted, hasFailed };
  }

  function MusicToggle({ isMuted, onToggle }) {
    return (
      <button
        className="music-toggle"
        onClick={onToggle}
        aria-label={isMuted ? "Unmute music" : "Mute music"}
        aria-pressed={isMuted}
        title={isMuted ? "Unmute music" : "Mute music"}
      >
        <span className={isMuted ? "" : "music-note-playing"}>♪</span>
        {isMuted && <span className="music-slash" aria-hidden="true" />}
      </button>
    );
  }

  window.Music = Object.freeze({ useBackgroundMusic, MusicToggle });
})();
