/* global React */

// ===== AUDIO MODE F1 (shared) — toggle opt-in =====
// - Ambient: assets/f1-theme.mp3 si existe (loop volume 0.25)
// - Engine trigger: assets/sonidos-de motores-de F1.mp3 al entrar formato-cards en viewport
// Estado persistido en sessionStorage ('vn-audio-mode'). Default OFF.

const ENGINE_SRC = 'assets/sonidos-de motores-de F1.mp3';
const THEME_SRC  = 'assets/f1-theme.mp3';
const STORAGE_KEY = 'vn-audio-mode';
const ENGINE_BURST_MS = 1200;

function AudioMode() {
  const [on, setOn] = React.useState(false);
  const themeRef = React.useRef(null);
  const engineRef = React.useRef(null);
  const triggeredRef = React.useRef(new WeakSet());

  // Init: read sessionStorage + create audio elements lazily
  React.useEffect(() => {
    try {
      const saved = sessionStorage.getItem(STORAGE_KEY);
      if (saved === 'on') setOn(true);
    } catch (e) {}
  }, []);

  // Apply on/off
  React.useEffect(() => {
    try { sessionStorage.setItem(STORAGE_KEY, on ? 'on' : 'off'); } catch (e) {}

    if (on) {
      // Theme ambient
      if (!themeRef.current) {
        const a = new Audio(THEME_SRC);
        a.loop = true;
        a.volume = 0.15;
        a.preload = 'auto';
        themeRef.current = a;
      }
      themeRef.current.play().catch(() => {
        // No theme file yet — silencioso, los triggers siguen funcionando
      });
      if (!engineRef.current) {
        const e = new Audio(ENGINE_SRC);
        e.preload = 'auto';
        e.volume = 0.4;
        engineRef.current = e;
      }
    } else {
      if (themeRef.current) {
        themeRef.current.pause();
        themeRef.current.currentTime = 0;
      }
      if (engineRef.current) {
        engineRef.current.pause();
        engineRef.current.currentTime = 0;
      }
    }
  }, [on]);

  // Pause theme cuando la pestaña queda en background
  React.useEffect(() => {
    const onVis = () => {
      if (!themeRef.current) return;
      if (document.hidden) themeRef.current.pause();
      else if (on) themeRef.current.play().catch(() => {});
    };
    document.addEventListener('visibilitychange', onVis);
    return () => document.removeEventListener('visibilitychange', onVis);
  }, [on]);

  const toggle = () => setOn(v => !v);

  return (
    <button
      type="button"
      className={`audio-mode ${on ? 'on' : ''}`}
      onClick={toggle}
      aria-pressed={on}
      aria-label={on ? 'Apagar modo F1' : 'Activar modo F1'}
      title={on ? 'Modo F1 activo · sonidos de motor al scrollear' : 'Activar Modo F1 (sonidos de motor)'}
    >
      <span className="am-icon" aria-hidden="true">{on ? '🔊' : '🔇'}</span>
      <span>Modo F1</span>
    </button>
  );
}

window.AudioMode = AudioMode;
