/* Assembles the pitch + drives the progress rail and adaptive top bar.
   Chrome state is updated via direct DOM (not React state) so it stays correct
   even when the React scheduler is throttled. */

const RAIL = [
  { id: 'fu-cover', label: 'Follow-up' },
  { id: 'followup', label: 'Thank you' },
  { id: 'q-scope', label: 'Scope' },
  { id: 'q-rights', label: 'Usage rights' },
  { id: 'q-perf', label: 'Performance' },
  { id: 'q-cleanroom', label: 'Clean room' },
  { id: 'q-eighty', label: 'The 80%' },
  { id: 'cover', label: 'Cover' },
  { id: 'room', label: 'In the room' },
  { id: 'ask', label: 'Your ask' },
  { id: 'boldstory', label: 'Our Bold story' },
  { id: 'bionic', label: 'Bionic Diamond' },
  { id: 'aifirst', label: 'AI-first' },
  { id: 'boldai', label: 'Bold ai' },
  { id: 'claim', label: 'The bar' },
  { id: 'pov', label: 'Our POV' },
  { id: 'half-ai', label: 'Half-truths' },
  { id: 'metric', label: 'The metric' },
  { id: 'problem', label: 'The problem' },
  { id: 'whyflywheel', label: 'Why Flywheel' },
  { id: 'advertorial', label: 'The big picture' },
  { id: 'ch-thread', label: '01 · Source of truth' },
  { id: 'ch-brand', label: '02 · Brand intelligence' },
  { id: 'ch-tools', label: '03 · Brand-compliant' },
  { id: 'ch-human', label: '04 · Human roles' },
  { id: 'cases', label: 'Case studies' },
  { id: 'ceiling', label: '20 is not 80' },
  { id: 'winning', label: 'Why we win' },
  { id: 'samsung-offer', label: 'The offer' },
  { id: 'close', label: 'Questions' },
  { id: 'appendix', label: 'Appendix' },
];

function PitchApp() {
  const { useEffect, useRef, useCallback } = React;
  const { useTweaks } = window;
  const TWEAK_DEFAULTS = {
    accent: ['#91d10b', '#437810'],
    headline: 'editorial',
    motion: 'cinematic',
  };
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const barRef = useRef(null), logoRef = useRef(null), railRef = useRef(null), samRef = useRef(null);

  // Accent → --lime / --lime-deep across the whole deck
  useEffect(() => {
    const acc = Array.isArray(t.accent) ? t.accent : [t.accent, t.accent];
    document.documentElement.style.setProperty('--lime', acc[0]);
    document.documentElement.style.setProperty('--lime-deep', acc[1] || acc[0]);
  }, [t.accent]);

  // Headline typeface → swap the display serif for the sans across all headings
  useEffect(() => {
    document.documentElement.style.setProperty('--font-serif',
      t.headline === 'modern'
        ? "'Hanken Grotesk', system-ui, -apple-system, sans-serif"
        : "'Newsreader', Georgia, 'Times New Roman', serif");
  }, [t.headline]);

  // Motion → still mode flattens all entrance animation
  useEffect(() => {
    document.documentElement.classList.toggle('tw-still', t.motion === 'still');
  }, [t.motion]);

  // Hide the top bar when the mouse goes idle; bring it back instantly on activity
  useEffect(() => {
    let t;
    const hide = () => { if (barRef.current) barRef.current.classList.add('idle-hide'); };
    const wake = () => {
      if (barRef.current) barRef.current.classList.remove('idle-hide');
      clearTimeout(t);
      t = setTimeout(hide, 2500);
    };
    const evs = ['mousemove', 'mousedown', 'wheel', 'keydown', 'touchstart'];
    evs.forEach((ev) => window.addEventListener(ev, wake, { passive: true }));
    t = setTimeout(hide, 2500);
    return () => { clearTimeout(t); evs.forEach((ev) => window.removeEventListener(ev, wake)); };
  }, []);

  useEffect(() => {
    if (window.initReveals) window.initReveals();
    const update = () => {
      const toned = [...document.querySelectorAll('[data-tone]')];
      let cur = toned[0];
      for (const s of toned) { if (s.getBoundingClientRect().top <= 90) cur = s; }
      const tone = cur ? cur.dataset.tone : 'light';
      const onDark = tone === 'dark' || tone === 'ink';
      const solid = window.scrollY > 40;
      const bar = barRef.current, logo = logoRef.current, rail = railRef.current;
      if (bar) { bar.classList.toggle('on-dark', onDark); bar.classList.toggle('solid', solid); }
      if (logo) {
        const want = onDark ? 'assets/flywheel-logo-white.png' : 'assets/flywheel-logo-trans.png';
        if (!logo.getAttribute('src').endsWith(want)) logo.setAttribute('src', want);
      }
      const sam = samRef.current;
      if (sam) {
        const wantS = onDark ? 'assets/samsung-logo-white.png' : 'assets/samsung-logo-black.png';
        if (!sam.getAttribute('src').endsWith(wantS)) sam.setAttribute('src', wantS);
      }
      if (rail) {
        rail.classList.toggle('on-dark', onDark);
        const mid = window.innerHeight * 0.42;
        let act = RAIL[0].id;
        for (const r of RAIL) { const el = document.getElementById(r.id); if (el && el.getBoundingClientRect().top <= mid) act = r.id; }
        rail.querySelectorAll('button').forEach((b) => b.classList.toggle('active', b.dataset.id === act));
      }
    };
    let t = 0;
    const h = () => { const n = Date.now(); if (n - t > 40) { t = n; update(); } };
    update();
    window.addEventListener('scroll', h, { passive: true });
    window.addEventListener('resize', h);
    const iv = setInterval(update, 250);
    return () => { window.removeEventListener('scroll', h); window.removeEventListener('resize', h); clearInterval(iv); };
  }, []);

  const go = useCallback((id) => {
    const el = document.getElementById(id);
    if (!el) return;
    window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY + 2, behavior: 'smooth' });
  }, []);

  return (
    <React.Fragment>
      <header ref={barRef} className="topbar on-dark">
        <img ref={logoRef} className="fw" src="assets/flywheel-logo-white.png" alt="Flywheel" />
        <nav ref={railRef} className="topnav on-dark">
          {RAIL.map((r) => (
            <button key={r.id} data-id={r.id} onClick={() => go(r.id)} aria-label={r.label}>
              <span className="tick" />
              <span className="label">{r.label}</span>
            </button>
          ))}
        </nav>
        <div className="cobrand">
          <img ref={samRef} className="sam" src="assets/samsung-logo-white.png" alt="Samsung" />
        </div>
      </header>

      <main>
        <FollowupCover />
        <FollowupIntro />
        <FollowupScope />
        <FollowupRights />
        <FollowupPerformance />
        <FollowupCleanroom />
        <FollowupEighty />
        <Cover />
        <Room />
        <TheAsk />
        <BoldStoryTitle />
        <BionicDiamond />
        <AiFirstQuote />
        <IntroBoldAi />
        <Claim />
        <Pov />
        <HalfTruthAI />
        <HalfTruthProducers />
        <Metric />
        <Problem />
        <WhyFlywheel />
        <Advertorial />
        <PaperTrail />
        <ChBrand />
        <ChTools />
        <ChHumanRoles />
        <CaseDivider />
        <CaseStudies />
        <WinningCombination />
        <Offer />
        <Close />
        <Appendix />
      </main>
      <TweaksUI t={t} setTweak={setTweak} />
    </React.Fragment>
  );
}

function TweaksUI({ t, setTweak }) {
  const { TweaksPanel, TweakSection, TweakColor, TweakRadio } = window;
  if (!TweaksPanel) return null;
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Brand" />
      <TweakColor label="Accent" value={t.accent}
        options={[['#91d10b', '#437810'], ['#b6f000', '#5c9e00'], ['#7ed957', '#2f7d32'], ['#c8e85a', '#6e8f12']]}
        onChange={(v) => setTweak('accent', v)} />
      <TweakSection label="Type" />
      <TweakRadio label="Headline" value={t.headline}
        options={['editorial', 'modern']}
        onChange={(v) => setTweak('headline', v)} />
      <TweakSection label="Motion" />
      <TweakRadio label="Entrance" value={t.motion}
        options={['cinematic', 'still']}
        onChange={(v) => setTweak('motion', v)} />
    </TweaksPanel>
  );
}

Object.assign(window, { PitchApp });
