// App entrypoint + Tweaks integration

const HEADLINES = {
  vendas: 'Transforme o WhatsApp da sua empresa em uma máquina de atendimento e vendas',
  ritmo:  'O ritmo do seu atendimento, agora em escala',
  unico:  'Um painel para todo o WhatsApp do seu time',
};

const SIGNUP_URL = 'https://app.talkpulse.com.br/signup';

const SUBHEAD = 'A TalkPulse centraliza todos os seus canais do WhatsApp em um único painel, com automação inteligente, chatbots e relatórios em tempo real — para equipes que não podem perder nenhuma oportunidade.';

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "headlineVariant": "vendas",
  "accentHue": 285,
  "gradientAngle": 90,
  "waNumber": "5561996090025",
  "showFloatingChips": true
}/*EDITMODE-END*/;

function applyAccent(hue) {
  // map hue onto our gradient endpoints — keep saturation & lightness fixed
  const stop1 = `oklch(0.58 0.24 ${hue})`;
  const stop2 = `oklch(0.74 0.18 ${(hue + 25) % 360})`;
  const root  = document.documentElement;
  root.style.setProperty('--brand-1', stop1);
  root.style.setProperty('--brand-2', stop2);
}

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Apply gradient angle live via a style tag override
  React.useEffect(() => {
    let el = document.getElementById('__brand-grad');
    if (!el) { el = document.createElement('style'); el.id = '__brand-grad'; document.head.appendChild(el); }
    el.textContent = `
      .bg-brand-gradient { background-image: linear-gradient(${tweaks.gradientAngle}deg, #9d35f0 0%, #c471ed 100%) !important; }
    `;
  }, [tweaks.gradientAngle]);

  React.useEffect(() => {
    if (!tweaks.showFloatingChips) {
      document.body.classList.add('hide-chips');
    } else {
      document.body.classList.remove('hide-chips');
    }
  }, [tweaks.showFloatingChips]);

  // Scroll reveal
  // Scroll reveal — with robust failsafes so content can never stay hidden
  // (IntersectionObserver can be unreliable in embedded/iframe contexts).
  React.useEffect(() => {
    const els = Array.from(document.querySelectorAll('.reveal'));

    const revealIfInView = () => {
      const vh = window.innerHeight || document.documentElement.clientHeight;
      els.forEach(el => {
        const r = el.getBoundingClientRect();
        if (r.top < vh * 0.92 && r.bottom > 0) el.classList.add('in');
      });
    };

    let io;
    try {
      io = new IntersectionObserver((entries) => {
        entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); } });
      }, { threshold: 0.12, rootMargin: '0px 0px -40px 0px' });
      els.forEach(el => io.observe(el));
    } catch (_) { /* no IO support */ }

    // Reveal anything already in view right away, and re-check on scroll.
    revealIfInView();
    window.addEventListener('scroll', revealIfInView, { passive: true });
    window.addEventListener('resize', revealIfInView, { passive: true });

    // Absolute failsafe: never leave content invisible.
    const failsafe = setTimeout(() => els.forEach(el => el.classList.add('in')), 1500);

    return () => {
      if (io) io.disconnect();
      window.removeEventListener('scroll', revealIfInView);
      window.removeEventListener('resize', revealIfInView);
      clearTimeout(failsafe);
    };
  }, []);

  const waLink = `https://wa.me/${tweaks.waNumber}`;
  const headline = HEADLINES[tweaks.headlineVariant] || HEADLINES.vendas;

  return (
    <React.Fragment>
      <Navbar />
      <main>
        <Hero headline={headline} subheadline={SUBHEAD} waLink={waLink} />
        <Features />
        <HowItWorks waLink={waLink} />
        <Integrations />
        <Pricing signupUrl={SIGNUP_URL} waLink={waLink} />
        <ContactCTA waLink={waLink} />
      </main>
      <Footer waLink={waLink} />

      <TweaksPanel>
        <TweakSection label="Headline" />
        <TweakRadio
          label="Variante"
          value={tweaks.headlineVariant}
          options={['vendas', 'ritmo', 'unico']}
          onChange={(v) => setTweak('headlineVariant', v)}
        />

        <TweakSection label="Marca" />
        <TweakSlider
          label="Ângulo do gradiente"
          min={0} max={360} step={5}
          value={tweaks.gradientAngle}
          onChange={(v) => setTweak('gradientAngle', v)}
          unit="°"
        />

        <TweakSection label="Hero" />
        <TweakToggle
          label="Cards flutuantes"
          value={tweaks.showFloatingChips}
          onChange={(v) => setTweak('showFloatingChips', v)}
        />

        <TweakSection label="WhatsApp" />
        <TweakText
          label="Número"
          value={tweaks.waNumber}
          onChange={(v) => setTweak('waNumber', v)}
          placeholder="5561996090025"
        />
      </TweaksPanel>

      <style>{`
        .hide-chips .md\\:flex.absolute { display: none !important; }
      `}</style>
    </React.Fragment>
  );
}

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

// Reveal once the mounted markup has been laid out with Tailwind's styles applied.
requestAnimationFrame(() => {
  requestAnimationFrame(() => document.body.classList.add('app-ready'));
});
