// app.jsx — orchestrator: intro → unlock scroll → chapters → tweaks
const { useState, useEffect, useRef } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "speed": 1,
  "intensity": 1,
  "modulesLayout": "orbital",
  "accent": "sun",
  "background": "deep-teal",
  "launchDate": "2026-09-15"
}/*EDITMODE-END*/;

const CHAPTERS = [
  { num: '01', label: 'Hoje' },
  { num: '02', label: 'Convergência' },
  { num: '03', label: 'Ecossistema' },
  { num: '04', label: 'Highlights' },
  { num: '05', label: 'Avise-me' },
];

// Data de abertura do Acesso Antecipado: vem da query (?abertura=YYYY-MM-DD),
// injetada pela página /sm2 a partir de DATA_ABERTURA. Fallback: 06/07/2026.
function getAberturaDate(){
  try {
    const q = new URLSearchParams(window.location.search).get('abertura');
    if (q && /^\d{4}-\d{2}-\d{2}$/.test(q)) return q;
  } catch (e) { /* ignore */ }
  return '2026-07-06';
}
const ABERTURA_DATE = getAberturaDate();

function App(){
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [gateOpen, setGateOpen] = useState(false);     // user clicked the CTA
  const [introDone, setIntroDone] = useState(false);
  const [revealing, setRevealing] = useState(false);   // post-intro reveal animation
  const [activeChapter, setActiveChapter] = useState(-1);

  // Lock body while gate OR intro is up
  useEffect(() => {
    const locked = !gateOpen || !introDone;
    document.body.classList.toggle('intro-locked', locked);
  }, [gateOpen, introDone]);

  // Stage the reveal: while intro is up, chapters are hidden (pre-reveal).
  // When intro ends, curtain retracts → chapter 1 fades in (revealing → post-reveal).
  useEffect(() => {
    if (!introDone){
      document.body.classList.add('pre-reveal');
      document.body.classList.remove('revealing');
      document.body.classList.remove('post-reveal');
      return;
    }
    // intro is done — start reveal sequence
    const t1 = setTimeout(() => {
      document.body.classList.remove('pre-reveal');
      document.body.classList.add('revealing');
    }, 80);
    const t2 = setTimeout(() => {
      document.body.classList.remove('revealing');
      document.body.classList.add('post-reveal');
    }, 1300);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [introDone]);

  // Mount chrome (top brand mark + actions + scroll rail) once intro done
  useEffect(() => {
    if (!introDone) return;
    document.getElementById('brand-mark').classList.add('in');
    document.getElementById('top-actions').classList.add('in');
    document.getElementById('scroll-rail').classList.add('in');
    document.getElementById('scroll-cue').classList.add('in');

    // Auto-scroll to chapter 01 after intro fades out
    const firstCh = document.querySelector('.ch');
    if (firstCh){
      setTimeout(() => {
        firstCh.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }, 850);
    }

    // Build scroll rail dots
    const rail = document.getElementById('scroll-rail');
    rail.innerHTML = '';
    CHAPTERS.forEach((c, i) => {
      const el = document.createElement('button');
      el.className = 'dot';
      el.setAttribute('aria-label', `Capítulo ${c.num}`);
      el.title = `${c.num} · ${c.label}`;
      el.addEventListener('click', () => {
        const sec = document.querySelectorAll('.ch')[i];
        if (sec) sec.scrollIntoView({ behavior: 'smooth', block: 'start' });
      });
      rail.appendChild(el);
    });
  }, [introDone]);

  // Track active chapter via IntersectionObserver
  useEffect(() => {
    if (!introDone) return;
    const secs = Array.from(document.querySelectorAll('.ch'));
    const dots = Array.from(document.querySelectorAll('#scroll-rail .dot'));
    if (!secs.length) return;

    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting){
          const idx = secs.indexOf(e.target);
          setActiveChapter(idx);
          dots.forEach((d, i) => d.classList.toggle('active', i === idx));
        }
      });
    }, { threshold: 0.5 });
    secs.forEach(s => io.observe(s));

    // Scroll cue → click to advance one viewport
    const cue = document.getElementById('scroll-cue');
    function advance(){
      window.scrollBy({ top: window.innerHeight * 0.9, behavior: 'smooth' });
    }
    cue.addEventListener('click', advance);
    cue.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); advance(); } });

    // Hide scroll cue once user is past first viewport, restore near top
    function onScroll(){
      const past = window.scrollY > window.innerHeight * 0.6;
      const nearBottom = (window.innerHeight + window.scrollY) >= document.body.offsetHeight - 20;
      if (past || nearBottom) cue.classList.add('hidden');
      else cue.classList.remove('hidden');
    }
    window.addEventListener('scroll', onScroll, { passive: true });

    return () => {
      io.disconnect();
      window.removeEventListener('scroll', onScroll);
      cue.removeEventListener('click', advance);
    };
  }, [introDone]);

  // FX lifecycle
  useEffect(() => {
    if (window.FX){
      window.FX.start();
      window.FX.setIntensity(t.intensity);
    }
    return () => { /* keep running across rerenders */ };
  }, []);
  useEffect(() => {
    if (window.FX) window.FX.setIntensity(t.intensity);
  }, [t.intensity]);

  // Background tweak — apply to CSS var
  useEffect(() => {
    const root = document.documentElement;
    if (t.background === 'pure-black'){
      root.style.setProperty('--bg', '#000000');
      root.style.setProperty('--bg-deep', '#000000');
    } else if (t.background === 'midnight'){
      root.style.setProperty('--bg', '#040A12');
      root.style.setProperty('--bg-deep', '#02050B');
    } else { /* deep-teal default */
      root.style.setProperty('--bg', '#050B0D');
      root.style.setProperty('--bg-deep', '#02060A');
    }
  }, [t.background]);

  // Accent tweak
  useEffect(() => {
    const root = document.documentElement;
    if (t.accent === 'none'){
      root.style.setProperty('--accent', '#4EB3C4'); /* fall back to teal */
    } else if (t.accent === 'cyan'){
      root.style.setProperty('--accent', '#8ED1DC');
    } else {
      root.style.setProperty('--accent', '#FBB03B');
    }
  }, [t.accent]);

  // Wire replay button (once). Áudio removido — só sobra o "rever intro".
  useEffect(() => {
    const replayBtn = document.getElementById('replay-btn');
    if (!replayBtn) return;
    function onReplay(){
      window.scrollTo({ top: 0, behavior: 'smooth' });
      setTimeout(() => {
        setIntroDone(false);
        setTimeout(() => { setIntroDone(false); }, 50);
        // Force remount intro by toggling
      }, 600);
    }
    replayBtn.onclick = onReplay;
    return () => { replayBtn.onclick = null; };
  }, []);

  return (
    <>
      {!gateOpen && <Gate key="gate" onOpen={() => {
        setGateOpen(true);
      }} />}
      {gateOpen && !introDone && <Intro key="intro" speed={t.speed} onDone={() => setIntroDone(true)} />}

      {/* Reveal curtain — sits above chapters, below intro */}
      <div className="reveal-curtain" aria-hidden>
        <span className="bar bar-top"></span>
        <span className="bar bar-bot"></span>
        <span className="flash"></span>
      </div>

      {/* Chapters are mounted from the start; intro sits above them.
          After intro fades out the scroll lock releases. */}
      <main>
        <ChapterOne />
        <ChapterTwo />
        <ChapterThree layout={t.modulesLayout} />
        <ChapterFour />
        <ChapterFive targetDate={ABERTURA_DATE + 'T10:00:00-03:00'} />
      </main>

      <TweaksPanel>
        <TweakSection label="Experiência" />
        <TweakSlider
          label="Velocidade da intro"
          value={t.speed} min={0.5} max={2} step={0.1}
          onChange={(v) => setTweak('speed', v)}
        />
        <TweakSlider
          label="Intensidade visual"
          value={t.intensity} min={0} max={1.6} step={0.1}
          onChange={(v) => setTweak('intensity', v)}
        />

        <TweakSection label="Capítulo 3 · Módulos" />
        <TweakRadio
          label="Layout"
          value={t.modulesLayout}
          options={[
            { value: 'orbital', label: 'Orbital' },
            { value: 'cards',   label: 'Cards' },
            { value: 'stream',  label: 'Stream' },
          ]}
          onChange={(v) => setTweak('modulesLayout', v)}
        />

        <TweakSection label="Estilo" />
        <TweakRadio
          label="Fundo"
          value={t.background}
          options={[
            { value: 'deep-teal', label: 'Teal' },
            { value: 'midnight',  label: 'Night' },
            { value: 'pure-black',label: 'Black' },
          ]}
          onChange={(v) => setTweak('background', v)}
        />
        <TweakColor
          label="Cor de destaque"
          value={t.accent === 'sun' ? '#FBB03B' : t.accent === 'cyan' ? '#8ED1DC' : '#4EB3C4'}
          options={['#FBB03B', '#8ED1DC', '#4EB3C4']}
          onChange={(v) => {
            if (v === '#FBB03B') setTweak('accent', 'sun');
            else if (v === '#8ED1DC') setTweak('accent', 'cyan');
            else setTweak('accent', 'none');
          }}
        />

        <TweakSection label="Abertura" />
        <TweakText
          label="Data anunciada (só leitura)"
          value={ABERTURA_DATE}
          onChange={() => { /* controlada no Portal GTM (DATA_ABERTURA) */ }}
        />

        <TweakButton
          label="Rever a intro"
          onClick={() => {
            window.scrollTo({ top: 0, behavior: 'instant' });
            setGateOpen(false);
            setIntroDone(false);
          }}
        />
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('app')).render(<App />);
