/* global React, ReactDOM, Hero, Nav, Marquee, Benefits, Features, Personas, Problems, Demo, SocialProof, Pitch, Plans, Guarantee, FAQ, FinalCTA, Footer, DarkTail, useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakColor, TweakSelect, TweakToggle */

const { useState, useEffect, useRef } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroVariant": "A",
  "brandHue": "240",
  "showFloatingCards": true,
  "navStyle": "floating"
}/*EDITMODE-END*/;

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [navLight, setNavLight] = useState(false);

  // Update brand color when hue changes
  useEffect(() => {
    const hue = parseInt(tweaks.brandHue, 10);
    // Map hue to brand colors using HSL
    const root = document.documentElement;
    if (hue !== 240) {
      // Approximate the original #1F46E0 in HSL: 226, 75%, 50%
      // We allow user to shift the hue
      root.style.setProperty('--brand', `hsl(${hue}, 75%, 50%)`);
      root.style.setProperty('--brand-deep', `hsl(${hue}, 80%, 40%)`);
      root.style.setProperty('--brand-bright', `hsl(${hue}, 90%, 62%)`);
      root.style.setProperty('--brand-glow', `hsl(${hue}, 100%, 70%)`);
    } else {
      root.style.removeProperty('--brand');
      root.style.removeProperty('--brand-deep');
      root.style.removeProperty('--brand-bright');
      root.style.removeProperty('--brand-glow');
    }
  }, [tweaks.brandHue]);

  // Switch nav from dark to light when scrolling into light sections
  useEffect(() => {
    const handler = () => {
      const y = window.scrollY;
      const total = document.body.scrollHeight - window.innerHeight;
      const ratio = y / total;
      // Switch around 65% of the page (where light sections begin)
      setNavLight(ratio > 0.62);
    };
    handler();
    window.addEventListener('scroll', handler, { passive: true });
    return () => window.removeEventListener('scroll', handler);
  }, []);

  // Reveal on scroll
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add('in');
            obs.unobserve(e.target);
          }
        });
      },
      { threshold: 0.15 }
    );
    els.forEach((el) => obs.observe(el));
    return () => obs.disconnect();
  }, []);

  // Anchor scroll fix — React renderiza depois do load do browser,
  // então #demo / #planos / #faq não funcionam nativamente.
  useEffect(() => {
    // Anima scrollY → target em ~600ms com easing (mais confiável que scroll-behavior: smooth
    // que conflita com handlers de scroll listener)
    const smoothScrollTo = (targetY) => {
      const startY = window.scrollY;
      const distance = targetY - startY;
      const duration = 600;
      const startTime = performance.now();
      const easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);
      const step = (now) => {
        const elapsed = now - startTime;
        const t = Math.min(elapsed / duration, 1);
        window.scrollTo(0, startY + distance * easeOutCubic(t));
        if (t < 1) requestAnimationFrame(step);
      };
      requestAnimationFrame(step);
    };

    const scrollToHash = (hash) => {
      const id = hash.replace(/^#/, '');
      if (!id) return;
      const el = document.getElementById(id);
      if (!el) return;
      const scrollMargin = parseInt(getComputedStyle(el).scrollMarginTop) || 96;
      const top = el.getBoundingClientRect().top + window.scrollY - scrollMargin;
      smoothScrollTo(top);
    };

    // Initial: se chegou com #algo na URL, scroll após mount
    if (window.location.hash) {
      setTimeout(() => scrollToHash(window.location.hash), 150);
    }

    // Click handler global pra anchors internos
    const onClick = (e) => {
      const a = e.target.closest('a[href^="#"]');
      if (!a) return;
      const href = a.getAttribute('href');
      if (href.length <= 1) return;
      const el = document.getElementById(href.slice(1));
      if (!el) return;
      e.preventDefault();
      scrollToHash(href);
      history.replaceState(null, '', href);
    };
    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
  }, []);

  return (
    <React.Fragment>
      <div className="bg-stage" aria-hidden="true"></div>
      <div className="bg-noise" aria-hidden="true"></div>

      <Nav isLight={navLight} />

      <main>
        <Hero variant={tweaks.heroVariant} />
        <Marquee />
        <Benefits />
        <Features />
        <Personas />
        <Problems />
        <Demo />
        <SocialProof />
        <Pitch />
        <FAQ />
      </main>

      <DarkTail />

      <TweaksPanel title="Tweaks">
        <TweakSection title="Hero">
          <TweakRadio
            label="Variante do Hero"
            value={tweaks.heroVariant}
            options={[
              { value: 'A', label: 'A · ToDesktop' },
              { value: 'B', label: 'B · Paste' },
              { value: 'C', label: 'C · Split' },
            ]}
            onChange={(v) => setTweak('heroVariant', v)}
          />
          {tweaks.heroVariant === 'A' && (
            <TweakToggle
              label="Cards flutuantes (m² / margem)"
              value={tweaks.showFloatingCards}
              onChange={(v) => setTweak('showFloatingCards', v)}
            />
          )}
        </TweakSection>

        <TweakSection title="Cor da marca">
          <TweakSelect
            label="Hue do azul"
            value={String(tweaks.brandHue)}
            options={[
              { value: '226', label: '226° · Azul Limify (#1F46E0)' },
              { value: '240', label: '240° · Azul royal' },
              { value: '210', label: '210° · Azul céu' },
              { value: '260', label: '260° · Roxo' },
              { value: '195', label: '195° · Ciano' },
              { value: '170', label: '170° · Verde-azulado' },
            ]}
            onChange={(v) => setTweak('brandHue', v)}
          />
        </TweakSection>
      </TweaksPanel>

      {/* Toggle floating cards via class on body */}
      <FloatingCardsToggle show={tweaks.showFloatingCards} />
    </React.Fragment>
  );
}

function FloatingCardsToggle({ show }) {
  useEffect(() => {
    document.body.classList.toggle('hide-float-cards', !show);
  }, [show]);
  return null;
}

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