const { useState: useSt, useEffect: useEf } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "lang": "de",
  "density": "comfortable",
  "motion": true,
  "gridOverlay": false,
  "serifHeadlines": true
}/*EDITMODE-END*/;

function Nav({ copy, onToggleLang, lang }) {
  const [scrolled, setScrolled] = useSt(false);
  const [active, setActive] = useSt('');
  const [overDark, setOverDark] = useSt(false);
  useEf(() => {
    const ids = ['godos', 'proof', 'fleet', 'trevi'];
    let raf = 0;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = 0;
        setScrolled(window.scrollY > 16);
        let cur = '';
        ids.forEach(id => {
          const el = document.getElementById(id);
          if (el && el.getBoundingClientRect().top <= window.innerHeight * 0.4) cur = id;
        });
        setActive(cur);
        // nav inverts while a dark surface is behind the bar:
        // the Trevi band, the Proof "room", OR the immersed hero scene (product scaled up + vignette on)
        let dark = false;
        ['trevi', 'proof'].forEach(id => {
          const el = document.getElementById(id);
          if (el) { const r = el.getBoundingClientRect(); if (r.top <= 64 && r.bottom > 64) dark = true; }
        });
        const track = document.querySelector('.hero-track');
        if (track && !track.classList.contains('hero-static')) {
          const r = track.getBoundingClientRect();
          const denom = track.offsetHeight - window.innerHeight;
          const hpv = denom > 0 ? Math.min(1, Math.max(0, -r.top / denom)) : 0;
          if (hpv > 0.22 && r.bottom > window.innerHeight * 0.5) dark = true;
        }
        setOverDark(dark);
      });
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => { window.removeEventListener('scroll', onScroll); if (raf) cancelAnimationFrame(raf); };
  }, []);
  const n = copy.nav;
  const links = [['godos', n.godos], ['proof', n.proof], ['fleet', n.fleet], ['trevi', n.trevi]];
  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''} ${overDark ? 'over-dark' : ''}`}>
      <div className="container nav-inner">
        <a href="#top" className="logo">
          <span className="logo-mark"></span>
          <span>Business AI</span>
        </a>
        <div className="nav-links">
          {links.map(([id, label]) => (
            <a key={id} href={`#${id}`} className={active === id ? 'active' : ''}>
              <span className="nav-dot"></span>{label}
            </a>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <button className="lang-toggle mono" onClick={onToggleLang} title="Toggle language">
            <span className={lang === 'de' ? 'active' : ''}>DE</span>
            <span className="sep">/</span>
            <span className={lang === 'en' ? 'active' : ''}>EN</span>
          </button>
          <a href="#cta" className="btn btn-primary" style={{ padding: '10px 16px', fontSize: 13 }}>{n.cta} <span className="arrow">↗</span></a>
        </div>
      </div>
      <style>{`
        .lang-toggle {
          appearance: none;
          background: var(--paper-2);
          border: 1px solid var(--line);
          color: var(--ink-3);
          padding: 8px 12px;
          border-radius: 999px;
          font-size: 11px;
          cursor: pointer;
          display: flex; align-items: center; gap: 6px;
          letter-spacing: 0.06em;
          transition: border-color 0.2s;
        }
        .lang-toggle:hover { border-color: var(--line-2); }
        .lang-toggle .active { color: var(--ink); }
        .lang-toggle .sep { color: var(--ink-3); }

        /* ---- nav inverted over the dark Proof room ---- */
        .nav .logo, .nav-links a { transition: color 0.35s ease; }
        .nav.over-dark { background: color-mix(in oklab, #15120C 80%, transparent); }
        .nav.over-dark.scrolled { border-color: rgba(244,241,233,0.16); }
        .nav.over-dark .logo { color: #F4F1E9; }
        .nav.over-dark .logo-mark { background: #F4F1E9; }
        .nav.over-dark .logo-mark::after { background: #15120C; }
        .nav.over-dark .logo-mark::before { background: #F4F1E9; }
        .nav.over-dark .nav-links a { color: rgba(244,241,233,0.62); }
        .nav.over-dark .nav-links a:hover, .nav.over-dark .nav-links a.active { color: #F4F1E9; }
        .nav.over-dark .nav-links a::after { background: #6FA8C9; }
        .nav.over-dark .lang-toggle { background: rgba(255,255,255,0.06); border-color: rgba(244,241,233,0.18); color: rgba(244,241,233,0.55); }
        .nav.over-dark .lang-toggle .active { color: #F4F1E9; }
        .nav.over-dark .lang-toggle .sep { color: rgba(244,241,233,0.4); }
        .nav.over-dark .btn-primary { background: #F4F1E9; color: #15120C; border-color: #F4F1E9; }
        .nav.over-dark .btn-primary:hover { background: #fff; border-color: #fff; color: #15120C; }
      `}</style>
    </nav>
  );
}

function Footer({ copy }) {
  return (
    <footer>
      <div className="container footer-row">
        <div className="logo" style={{ fontSize: 13 }}>
          <span className="logo-mark" style={{ width: 18, height: 18 }}></span>
          Business AI
        </div>
        <div>{copy.footer.copy}</div>
        <div className="footer-links">
          {copy.footer.links.map(l => <a key={l} href="#">{l}</a>)}
        </div>
      </div>
    </footer>
  );
}

function App() {
  const [tw, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const copy = COPY[tw.lang] || COPY.de;

  const [reduced, setReduced] = useSt(false);
  useEf(() => {
    const mq = window.matchMedia('(prefers-reduced-motion: reduce), (max-width: 899px)');
    const update = () => setReduced(mq.matches);
    update();
    mq.addEventListener ? mq.addEventListener('change', update) : mq.addListener(update);
    return () => { mq.removeEventListener ? mq.removeEventListener('change', update) : mq.removeListener(update); };
  }, []);

  const motionOn = tw.motion && !reduced;

  useEf(() => { document.body.classList.toggle('no-motion', !motionOn); }, [motionOn]);

  useEf(() => {
    const density = tw.density === 'compact' ? 0.8 : tw.density === 'spacious' ? 1.25 : 1;
    document.documentElement.style.setProperty('--density', String(density));
  }, [tw.density]);

  useEf(() => {
    document.body.classList.toggle('grid-overlay', !!tw.gridOverlay);
  }, [tw.gridOverlay]);

  useEf(() => {
    document.documentElement.style.setProperty('--serif', tw.serifHeadlines ? "'Instrument Serif', 'Times New Roman', serif" : "'Geist', system-ui, sans-serif");
  }, [tw.serifHeadlines]);

  // ---- Lenis smooth scroll: only when motion is on (reduced-motion / mobile keep native scroll).
  // Lenis drives the REAL window scroll, so position:sticky (hero, flagship pin) + scroll-linked
  // effects (--hp/--enter/--p) keep working; it just lerps the wheel for an inertial feel.
  useEf(() => {
    if (!motionOn || !window.Lenis) return;
    const lenis = new window.Lenis({
      lerp: 0.1,
      wheelMultiplier: 1,
      smoothWheel: true,
      anchors: false,        // we handle anchors ourselves (offset for the fixed nav)
    });
    window.__lenis = lenis;   // shared so components (e.g. flagship rail goTo) scroll THROUGH Lenis
    let raf = requestAnimationFrame(function loop(t) { lenis.raf(t); raf = requestAnimationFrame(loop); });
    const navH = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--nav-h'), 10) || 64;
    const onClick = (e) => {
      if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
      const a = e.target.closest('a[href^="#"]');
      if (!a) return;
      const href = a.getAttribute('href');
      if (!href || href.length < 2) return;
      const el = document.querySelector(href);
      if (!el) return;
      e.preventDefault();
      lenis.scrollTo(el, { offset: -navH - 12 });
    };
    document.addEventListener('click', onClick);
    return () => { cancelAnimationFrame(raf); document.removeEventListener('click', onClick); lenis.destroy(); window.__lenis = null; };
  }, [motionOn]);

  const toggleLang = () => setTweak('lang', tw.lang === 'de' ? 'en' : 'de');

  return (
    <>
      <ScrollProgress />
      <Nav copy={copy} onToggleLang={toggleLang} lang={tw.lang} />
      <Hero copy={copy} motionOn={motionOn} />
      <Vision copy={copy} motionOn={motionOn} />
      <GodOSSection copy={copy} />
      <Proof copy={copy} motionOn={motionOn} />
      <Fleet copy={copy} />
      <Trevi copy={copy} motionOn={motionOn} />
      <CTA copy={copy} />
      <Footer copy={copy} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Language">
          <TweakRadio
            value={tw.lang}
            onChange={v => setTweak('lang', v)}
            options={[{ value: 'de', label: 'Deutsch' }, { value: 'en', label: 'English' }]}
          />
        </TweakSection>
        <TweakSection label="Density">
          <TweakRadio
            value={tw.density}
            onChange={v => setTweak('density', v)}
            options={[{ value: 'compact', label: 'Compact' }, { value: 'comfortable', label: 'Comfy' }, { value: 'spacious', label: 'Loose' }]}
          />
        </TweakSection>
        <TweakSection label="Typography">
          <TweakToggle label="Serif headlines" value={tw.serifHeadlines} onChange={v => setTweak('serifHeadlines', v)} />
        </TweakSection>
        <TweakSection label="Motion">
          <TweakToggle label="Animations on" value={tw.motion} onChange={v => setTweak('motion', v)} />
        </TweakSection>
        <TweakSection label="Debug">
          <TweakToggle label="Grid overlay" value={tw.gridOverlay} onChange={v => setTweak('gridOverlay', v)} />
        </TweakSection>
      </TweaksPanel>

      <style>{`
        body.grid-overlay::after {
          content: "";
          position: fixed; inset: 0;
          pointer-events: none;
          z-index: 99;
          background-image:
            linear-gradient(rgba(43,76,99,0.10) 1px, transparent 1px),
            linear-gradient(90deg, rgba(43,76,99,0.10) 1px, transparent 1px);
          background-size: 64px 64px;
        }
      `}</style>
    </>
  );
}

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