// Componente raiz — monta todas as seções
function App() {
  window.useReveal();

  const [configLoaded, setConfigLoaded] = React.useState(false);
  const [showIntro, setShowIntro] = React.useState(
    () => !sessionStorage.getItem('envelope-seen')
  );
  const [playing, setPlaying] = React.useState(false);
  const [volume,  setVolume]  = React.useState(0.1);
  const audioRef = React.useRef(null);

  // Carrega config do Firestore e mescla em window.CONFIG antes de renderizar
  React.useEffect(() => {
    if (!window.db) { setConfigLoaded(true); return; }
    window.db.collection('config').doc('site').get()
      .then(doc => {
        if (doc.exists) {
          const data = doc.data();
          Object.assign(window.CONFIG, data);
          if (data.metaSurpresa) window.CONFIG.cotas[0].meta = data.metaSurpresa;
        }
        setConfigLoaded(true);
      })
      .catch(() => setConfigLoaded(true));
  }, []);

  // Pausa ao sair da aba, retoma ao voltar (só se estava tocando)
  React.useEffect(() => {
    const handleVisibility = () => {
      const audio = audioRef.current;
      if (!audio) return;
      if (document.hidden) {
        audio.pause();
      } else if (!audio.paused) {
        // já estava tocando — não precisa fazer nada
      }
    };
    document.addEventListener('visibilitychange', handleVisibility);
    return () => document.removeEventListener('visibilitychange', handleVisibility);
  }, []);

  if (!configLoaded) return null;

  function handleEnvelopeOpen() {
    const audio = audioRef.current;
    if (!audio) return;
    audio.volume = 0.1;
    audio.currentTime = 180; // começa do minuto 3
    audio.play().then(() => setPlaying(true)).catch(() => {});
  }

  function handleComplete() {
    sessionStorage.setItem('envelope-seen', '1');
    setShowIntro(false);
  }

  function toggleMusic() {
    const audio = audioRef.current;
    if (!audio) return;
    if (audio.paused) {
      audio.play().then(() => setPlaying(true)).catch(() => {});
    } else {
      audio.pause();
      setPlaying(false);
    }
  }

  function handleVolume(e) {
    const val = parseFloat(e.target.value);
    setVolume(val);
    if (audioRef.current) audioRef.current.volume = val;
  }

  return (
    <>
      <audio ref={audioRef} src="assets/musica.mp3" preload="none"
             onEnded={() => {
               const a = audioRef.current;
               if (a) { a.currentTime = 180; a.play().catch(() => {}); }
             }} />

      {showIntro && (
        <EnvelopeIntro onOpen={handleEnvelopeOpen} onComplete={handleComplete} />
      )}

      {/* Botão flutuante de música */}
      {!showIntro && (
        <div className="music-widget">
          <button
            className={`music-btn ${playing ? 'music-btn--playing' : ''}`}
            onClick={toggleMusic}
            aria-label={playing ? 'Pausar música' : 'Tocar música'}
          >
            {playing ? (
              <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor">
                <rect x="6" y="4" width="4" height="16" rx="1"/>
                <rect x="14" y="4" width="4" height="16" rx="1"/>
              </svg>
            ) : (
              <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor">
                <path d="M9 3.6L19.4 12 9 20.4V3.6z"/>
              </svg>
            )}
            <span className="music-btn-label">{playing ? 'Pausar' : 'Música'}</span>
          </button>
          <input
            className="music-volume"
            type="range" min="0" max="1" step="0.01"
            value={volume}
            onChange={handleVolume}
            aria-label="Volume"
            title={`Volume: ${Math.round(volume * 100)}%`}
            style={{ background: `linear-gradient(to right, #711312 ${volume*100}%, #e0d6cc ${volume*100}%)` }}
          />
        </div>
      )}

      <Navbar />
      <main>
        <Hero />
        <Rsvp />
        <EventInfo />
        <DressCode />
        <GiftList />
        <Gallery />
      </main>
      <Footer />

      <style>{`
        .music-widget {
          position: fixed;
          bottom: 24px;
          right: 24px;
          z-index: 1000;
          display: flex;
          align-items: center;
          gap: 8px;
          background: #ffffff;
          border: 1px solid rgba(113,19,18,0.2);
          border-radius: 999px;
          padding: 8px 14px;
          box-shadow: 0 4px 16px -4px rgba(0,0,0,0.15);
          animation: fadeInUp 0.4s ease both;
        }
        .music-volume {
          -webkit-appearance: none;
          appearance: none;
          width: 72px; height: 3px;
          border-radius: 999px;
          background: linear-gradient(to right, #711312 calc(var(--val, 10%) ), #e0d6cc calc(var(--val, 10%)));
          outline: none; cursor: pointer;
          flex-shrink: 0;
        }
        .music-volume::-webkit-slider-thumb {
          -webkit-appearance: none;
          width: 13px; height: 13px;
          border-radius: 50%;
          background: #711312;
          cursor: pointer;
          border: 2px solid #fff;
          box-shadow: 0 1px 4px rgba(0,0,0,0.2);
        }
        .music-volume::-moz-range-thumb {
          width: 13px; height: 13px;
          border-radius: 50%;
          background: #711312;
          cursor: pointer;
          border: 2px solid #fff;
        }
        .music-btn {
          display: flex;
          align-items: center;
          gap: 6px;
          background: none;
          border: none;
          padding: 0;
          color: #711312;
          font-family: 'Lato', sans-serif;
          font-size: 11px;
          letter-spacing: 1.5px;
          text-transform: uppercase;
          cursor: pointer;
          flex-shrink: 0;
          z-index: 1000;
          display: flex;
          align-items: center;
          gap: 7px;
          padding: 10px 16px;
          border-radius: 999px;
          background: #ffffff;
          border: 1px solid rgba(113,19,18,0.2);
          color: #711312;
          box-shadow: 0 4px 16px -4px rgba(0,0,0,0.15);
          font-family: 'Lato', sans-serif;
          font-size: 11px;
          letter-spacing: 1.5px;
          text-transform: uppercase;
          cursor: pointer;
          transition: background 0.2s, box-shadow 0.2s, transform 0.15s;
          animation: fadeInUp 0.4s ease both;
        }
        .music-btn:hover { opacity: 0.75; }
        .music-btn--playing { color: #711312; }
        .music-btn-label { line-height: 1; }
        @media (max-width: 480px) {
          .music-widget { bottom: 16px; right: 16px; padding: 7px 12px; gap: 6px; }
          .music-btn-label { display: none; }
          .music-volume { width: 56px; }
        }
      `}</style>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
