// Main app — assembles all sections + Tweaks panel + scroll reveal

const { useState, useEffect, useRef } = React;

// IntersectionObserver for reveal animations
const useReveal = () => {
  useEffect(() => {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) e.target.classList.add('in');
      });
    }, { threshold: 0.1, rootMargin: '0px 0px -10% 0px' });
    document.querySelectorAll('.reveal').forEach(el => obs.observe(el));
    return () => obs.disconnect();
  }, []);
};

// Scroll to URL hash target after React has rendered the page.
// Needed because sections are React-rendered: the anchor element does not
// exist when the browser tries to apply the hash on initial navigation.
const useHashScroll = () => {
  useEffect(() => {
    const scrollToHash = () => {
      const id = window.location.hash.replace('#', '');
      if (!id) return;
      let attempts = 0;
      const tryScroll = () => {
        const el = document.getElementById(id);
        if (el) {
          el.scrollIntoView({ behavior: 'smooth', block: 'start' });
        } else if (attempts < 30) {
          attempts++;
          requestAnimationFrame(tryScroll);
        }
      };
      tryScroll();
    };
    scrollToHash();
    window.addEventListener('hashchange', scrollToHash);
    return () => window.removeEventListener('hashchange', scrollToHash);
  }, []);
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "headline": "A",
  "density": "comfortable",
  "sectionOrder": "default",
  "pricingHighlight": "annual",
  "painVariant": "timeline"
}/*EDITMODE-END*/;

const SECTION_ORDERS = {
  default: ['hero','social','pain','pillars','features','migration','grid','testimonials','ogarom','pionero','built','faq','cta'],
  conversion: ['hero','social','migration','pain','pillars','features','grid','testimonials','ogarom','pionero','built','faq','cta'],
  story: ['hero','social','pain','pillars','testimonials','features','built','migration','grid','ogarom','pionero','faq','cta'],
};

const App = () => {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useReveal();
  useHashScroll();

  useEffect(() => {
    document.documentElement.setAttribute('data-density', tweaks.density === 'compact' ? 'compact' : 'comfortable');
  }, [tweaks.density]);

  const sections = {
    hero: <Hero variant={tweaks.headline} />,
    social: <SocialBar />,
    pain: <PainSection variant={tweaks.painVariant} />,
    pillars: <PillarsSection />,
    features: <FeaturesSection />,
    migration: <MigrationSection />,
    grid: <FeaturesGrid />,
    latam: <LatamSection />,
    compare: <CompareTable />,
    testimonials: <Testimonials />,
    ogarom: <OgaromSection />,
    pionero: <PlanPionero />,
    built: <BuiltWith />,
    pricing: <PricingSection />,
    faq: <FAQSection />,
    cta: <FinalCTA />,
  };

  const order = SECTION_ORDERS[tweaks.sectionOrder] || SECTION_ORDERS.default;

  return (
    <>
      <Nav />
      <main>
        {order.map((key, i) => <React.Fragment key={key + i}>{sections[key]}</React.Fragment>)}
      </main>
      <Footer />
      <WhatsAppButton />

      <TweaksPanel title="Tweaks" defaultOpen={false}>
        <TweakSection title="Hero · Variantes de headline">
          <TweakRadio
            label="Variante"
            value={tweaks.headline}
            onChange={v => setTweak('headline', v)}
            options={[
              { value: 'A', label: 'A · Storytelling' },
              { value: 'B', label: 'B · Autoridad' },
              { value: 'C', label: 'C · Dolor' },
              { value: 'D', label: 'D · Resultado' },
            ]}
          />
        </TweakSection>
        <TweakSection title="Sección Dolor — '¿Tu día a día se ve así?'">
          <TweakRadio
            label="Variante"
            value={tweaks.painVariant}
            onChange={v => setTweak('painVariant', v)}
            options={[
              { value: 'timeline', label: 'Timeline · Scroll-driven' },
              { value: 'editorial', label: 'Editorial · Checklist' },
              { value: 'conversation', label: 'Conversación · Citas' },
            ]}
          />
        </TweakSection>
        <TweakSection title="Layout">
          <TweakRadio
            label="Densidad"
            value={tweaks.density}
            onChange={v => setTweak('density', v)}
            options={[
              { value: 'comfortable', label: 'Aéré' },
              { value: 'compact', label: 'Compact' },
            ]}
          />
          <TweakSelect
            label="Orden de secciones"
            value={tweaks.sectionOrder}
            onChange={v => setTweak('sectionOrder', v)}
            options={[
              { value: 'default', label: 'Por defecto (estándar CRO)' },
              { value: 'conversion', label: 'Conversión máxima (migración arriba)' },
              { value: 'story', label: 'Storytelling (testimonios temprano)' },
            ]}
          />
        </TweakSection>
        <TweakSection title="Pricing · Card destacada">
          <TweakRadio
            label="Plan resaltado"
            value={tweaks.pricingHighlight}
            onChange={v => setTweak('pricingHighlight', v)}
            options={[
              { value: 'annual', label: 'Anual (recomendado)' },
              { value: 'monthly', label: 'Mensual' },
            ]}
          />
        </TweakSection>
      </TweaksPanel>
    </>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(
  <CountryProvider country={typeof window !== 'undefined' ? window.__CB_COUNTRY__ : undefined}>
    <App />
  </CountryProvider>
);
