// chapters.jsx — scroll-driven story
// Each chapter is a full-viewport section observed by IntersectionObserver.
// Layout variations for the modules chapter are switchable.

const { useState, useEffect, useRef } = React;

// ===== Hook: in-view boolean =====
function useInView(threshold = 0.45){
  const ref = useRef(null);
  const [inView, setInView] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(([e]) => setInView(e.isIntersecting), { threshold });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [threshold]);
  return [ref, inView];
}

// ===========================================================
// CHAPTER 1 — "Você ainda usa N ferramentas separadas"
// ===========================================================
function ChapterOne(){
  const [ref, inView] = useInView(0.35);
  const tools = [
    { name: 'Omie / Conta Azul',        cat: 'Financeiro' },
    { name: 'RD Station / Mailchimp',   cat: 'Marketing' },
    { name: 'WhatsApp Web',             cat: 'Atendimento' },
    { name: 'ChatGPT',                  cat: 'IA de Apoio' },
    { name: 'Portais de Monitoramento', cat: 'Monitoramento de Energia' },
    { name: 'Aurora Solar',             cat: 'Desenho 3D Telhado' },
    { name: 'Pluga / Zapier / N8N',     cat: 'Automações' },
    { name: 'PowerBI',                  cat: 'Relatórios' },
    { name: 'DocuSign / ClickSign',     cat: 'Assinatura Digital' },
    { name: 'PipeDrive / Trello',       cat: 'Projetos' },
    { name: 'Gupy',                     cat: 'Gestão de RH' },
    { name: 'Planilhas Excel',          cat: 'Diversos' },
  ];

  return (
    <section ref={ref} className={"ch ch-one " + (inView ? "in" : "")} data-screen-label="01 · O integrador hoje">
      <div className="ch-shell">
        <div className="ch-eyebrow"><span className="bar"></span>Capítulo 01</div>
        <h2 className="ch-title">
          Você ainda roda sua empresa em <span className="hl">diversos sistemas espalhados</span>?
        </h2>
        <p className="ch-lede">CRM aqui, financeiro lá, RH numa planilha, atendimento no WhatsApp, MKT desconectado…<br />Cada um com sua própria senha, seu próprio mundo, seu próprio silêncio.</p>

        <div className="tool-field" aria-hidden>
          {tools.map((t, i) => (
            <div key={i} className="tool" style={{ '--i': i, '--total': tools.length }}>
              <span className="t-name">{t.name}</span>
              <span className="t-cat">{t.cat}</span>
            </div>
          ))}
        </div>

      </div>
    </section>
  );
}

// ===========================================================
// CHAPTER 2 — "E se tudo conversasse?"
// ===========================================================
function ChapterTwo(){
  const [ref, inView] = useInView(0.4);
  return (
    <section ref={ref} className={"ch ch-two " + (inView ? "in" : "")} data-screen-label="02 · Convergência">
      <div className="ch-shell narrow">
        <div className="ch-eyebrow"><span className="bar"></span>Capítulo 02</div>
        <h2 className="ch-title big">
          E se tudo<br />
          <span className="hl">conversasse</span> entre si?
        </h2>
        <p className="ch-lede">
          O CRM falando com o financeiro. O financeiro falando com o RH.<br />
          Agentes de IA atravessando todos eles, no ritmo da sua operação.
        </p>

        <ConstellationCanvas inView={inView} />
      </div>
    </section>
  );
}

function ConstellationCanvas({ inView }){
  const ref = useRef(null);
  useEffect(() => {
    const c = ref.current;
    if (!c) return;
    const ctx = c.getContext('2d');
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    function resize(){
      const w = c.clientWidth, h = c.clientHeight;
      c.width = w*dpr; c.height = h*dpr; ctx.setTransform(dpr,0,0,dpr,0,0);
    }
    resize();
    const ro = new ResizeObserver(resize); ro.observe(c);

    // nodes around a circle + center
    const w = () => c.clientWidth, h = () => c.clientHeight;
    const nodes = [];
    const N = 9;
    for (let i = 0; i < N; i++){
      const a = (i / N) * Math.PI * 2 - Math.PI/2;
      nodes.push({ a, r: 0.36, jitter: Math.random()*0.04, phase: Math.random()*Math.PI*2 });
    }

    let t = 0; let raf;
    function frame(){
      t += 0.012;
      ctx.clearRect(0,0,w(),h());
      const cx = w()*0.5, cy = h()*0.5;
      const rad = Math.min(w(), h()) * 0.36;

      // Lines from each node to center, fading on phase
      nodes.forEach((n, i) => {
        const x = cx + Math.cos(n.a) * rad * (1 + Math.sin(t + n.phase)*0.02);
        const y = cy + Math.sin(n.a) * rad * (1 + Math.sin(t + n.phase)*0.02);
        const alpha = inView ? (0.18 + Math.sin(t*1.4 + i)*0.10) : 0.04;
        const g = ctx.createLinearGradient(cx, cy, x, y);
        g.addColorStop(0, `rgba(78,179,196,${alpha*1.5})`);
        g.addColorStop(1, `rgba(78,179,196,0)`);
        ctx.strokeStyle = g; ctx.lineWidth = 1;
        ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo(x, y); ctx.stroke();

        // node dot
        ctx.beginPath();
        ctx.fillStyle = `rgba(196,230,236,${inView ? 0.85 : 0.2})`;
        ctx.arc(x, y, 3, 0, Math.PI*2); ctx.fill();
        // node glow
        const gg = ctx.createRadialGradient(x, y, 0, x, y, 18);
        gg.addColorStop(0, `rgba(78,179,196,${inView ? 0.45 : 0.1})`);
        gg.addColorStop(1, 'rgba(78,179,196,0)');
        ctx.fillStyle = gg; ctx.beginPath(); ctx.arc(x, y, 18, 0, Math.PI*2); ctx.fill();
      });

      // also connect adjacent nodes for "constellation" feel
      for (let i = 0; i < N; i++){
        const n1 = nodes[i], n2 = nodes[(i+1)%N];
        const x1 = cx + Math.cos(n1.a) * rad, y1 = cy + Math.sin(n1.a) * rad;
        const x2 = cx + Math.cos(n2.a) * rad, y2 = cy + Math.sin(n2.a) * rad;
        ctx.strokeStyle = `rgba(78,179,196,${inView ? 0.08 : 0.02})`;
        ctx.lineWidth = 1;
        ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke();
      }

      // Center logo glow
      const gC = ctx.createRadialGradient(cx, cy, 0, cx, cy, 60);
      gC.addColorStop(0, `rgba(26,142,162,${inView ? 0.45 : 0.05})`);
      gC.addColorStop(1, 'rgba(0,0,0,0)');
      ctx.fillStyle = gC; ctx.beginPath(); ctx.arc(cx, cy, 60, 0, Math.PI*2); ctx.fill();

      raf = requestAnimationFrame(frame);
    }
    frame();
    return () => { cancelAnimationFrame(raf); ro.disconnect(); };
  }, [inView]);

  return (
    <div className="constellation">
      <canvas ref={ref}></canvas>
      <div className="constellation-core">
        <img src="assets/logo-solarmarket-mark.png" alt="" />
      </div>
    </div>
  );
}

// ===========================================================
// CHAPTER 3 — Module reveal (3 layout variations)
// ===========================================================
const MODULES = [
  { id: 'ai',      name: 'Estúdio de IA',            desc: 'Agentes autônomos sob medida.',                                  icon: 'sparkles' },
  { id: 'mkt',     name: 'Marketing',                desc: 'Facebook Ads, Google Ads, automações.',                          icon: 'megaphone' },
  { id: 'fin',     name: 'Financeiro',               desc: 'Faturamento, contas, DRE, fluxo de caixa.',                      icon: 'wallet' },
  { id: 'kpi',     name: 'Relatórios & KPIs',        desc: 'Relatórios aprofundados de toda a operação.',                    icon: 'chart' },
  { id: 'crm',     name: 'CRM',                      desc: 'Pipelines, contatos e negócios.',                                icon: 'users' },
  { id: 'cad',     name: 'Cadências',                desc: 'Cadências de atividades para todas as operações.',               icon: 'repeat' },
  { id: 'sales',   name: 'Vendas',                   desc: 'Propostas e vendas, solares e genéricas.',                       icon: 'trending' },
  { id: 'monitor', name: 'Monitoramento de Energia', desc: 'Integração com portais de monitoramento e concessionárias de energia.', icon: 'activity' },
  { id: 'rh',      name: 'RH',                       desc: 'Time, contratos, férias.',                                       icon: 'briefcase' },
  { id: '3d',      name: 'Dimensionamento 3D e IA',  desc: 'Telhado, múltiplas superfícies, detecção automática.',           icon: 'cube' },
  { id: 'proj',    name: 'Projeto & Homologação',    desc: 'Serviços terceirizados por dentro da plataforma.',               icon: 'file' },
  { id: 'alfredo', name: 'Alfredo IA',               desc: 'Seu braço direito. Opera a plataforma por você.',                icon: 'bot' },
  { id: 'whats',   name: 'WhatsApp',                 desc: 'Atendimento integrado à plataforma MyFlows.',                    icon: 'message' },
  { id: 'integ',   name: 'Integrações',              desc: 'Slack, MyFlows, Google Calendar, API, entre outros.',            icon: 'link' },
];

function ModuleIcon({ name }){
  // Inline SVG strokes — lucide-style minimal
  const common = { width:24, height:24, viewBox:"0 0 24 24", fill:"none", stroke:"currentColor", strokeWidth:1.6, strokeLinecap:"round", strokeLinejoin:"round" };
  const paths = {
    users:    <><circle cx="9" cy="8" r="3"/><path d="M2 21v-2a5 5 0 0 1 5-5h4a5 5 0 0 1 5 5v2"/><circle cx="17" cy="6" r="2.5"/></>,
    sparkles: <><path d="M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5L18 18M6 18l2.5-2.5M15.5 8.5L18 6"/></>,
    cube:     <><path d="M12 3l9 5v8l-9 5-9-5V8z"/><path d="M3 8l9 5 9-5M12 13v10"/></>,
    activity: <><path d="M3 12h4l3-8 4 16 3-8h4"/></>,
    wallet:   <><rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18M17 14h.01"/></>,
    briefcase:<><rect x="3" y="7" width="18" height="13" rx="2"/><path d="M9 7V5a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2"/></>,
    cpu:      <><rect x="6" y="6" width="12" height="12" rx="2"/><path d="M9 9h6v6H9zM3 9h3M3 15h3M18 9h3M18 15h3M9 3v3M15 3v3M9 18v3M15 18v3"/></>,
    megaphone:<><path d="M3 11v2a2 2 0 0 0 2 2h3l8 4V5L8 9H5a2 2 0 0 0-2 2z"/><path d="M19 7a5 5 0 0 1 0 10"/></>,
    file:     <><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9zM14 3v6h6"/></>,
    shopping: <><path d="M3 4h2l2.5 13a2 2 0 0 0 2 1.6h8.5"/><circle cx="10" cy="20" r="1.5"/><circle cx="18" cy="20" r="1.5"/><path d="M7 8h14l-1.5 8H8.5"/></>,
    chart:    <><path d="M3 3v18h18"/><rect x="7" y="11" width="3" height="6"/><rect x="12" y="7" width="3" height="10"/><rect x="17" y="13" width="3" height="4"/></>,
    repeat:   <><path d="M17 2l4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="M7 22l-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></>,
    trending: <><path d="M3 17l6-6 4 4 8-8"/><path d="M17 7h4v4"/></>,
    bot:      <><rect x="4" y="8" width="16" height="12" rx="2"/><path d="M12 4v4M9 14h.01M15 14h.01M2 13v2M22 13v2"/></>,
    message:  <><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></>,
    link:     <><path d="M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1"/><path d="M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1"/></>,
  };
  return <svg {...common}>{paths[name]}</svg>;
}

function ChapterThree({ layout }){
  const [ref, inView] = useInView(0.25);
  return (
    <section ref={ref} className={"ch ch-three " + (inView ? "in" : "")} data-screen-label="03 · O ecossistema">
      <div className="ch-shell">
        <div className="ch-eyebrow"><span className="bar"></span>Capítulo 03 · O ecossistema</div>
        <h2 className="ch-title">
          Uma só plataforma.<br/>
          <span className="hl">Um ecossistema vivo e integrado.</span> <span className="muted-strong">Conversando entre si.</span>
        </h2>

        {layout === 'orbital' && <ModulesOrbital inView={inView} />}
        {layout === 'cards'   && <ModulesCards   inView={inView} />}
        {layout === 'stream'  && <ModulesStream  inView={inView} />}
      </div>
    </section>
  );
}

// ----- Layout A: orbital -----
function ModulesOrbital({ inView }){
  const [hover, setHover] = useState(null);
  const N = MODULES.length;
  return (
    <div className={"orbital " + (inView ? "in" : "")}>
      <div className="orbital-core" aria-hidden>
        <img src="assets/logo-solarmarket-mark.png" alt="" />
        <span className="core-label">SolarMarket OS</span>
      </div>
      <div className="orbital-ring r1"></div>
      <div className="orbital-ring r2"></div>
      <div className="orbital-ring r3"></div>
      {MODULES.map((m, i) => {
        const angle = (i / N) * 360;
        return (
          <button
            key={m.id}
            className={"orbital-node " + (hover === m.id ? "hover" : "")}
            style={{
              '--angle': `${angle}deg`,
              '--delay': `${i * 120}ms`,
            }}
            onMouseEnter={() => setHover(m.id)}
            onMouseLeave={() => setHover(null)}
          >
            <span className="node-icon"><ModuleIcon name={m.icon}/></span>
            <span className="node-name">{m.name}</span>
          </button>
        );
      })}
      <div className="orbital-detail">
        {hover ? (
          <>
            <span className="d-name">{MODULES.find(m => m.id === hover).name}</span>
            <span className="d-desc">{MODULES.find(m => m.id === hover).desc}</span>
          </>
        ) : (
          <span className="d-hint">Passe o mouse pelos módulos →</span>
        )}
      </div>
    </div>
  );
}

// ----- Layout B: cards -----
function ModulesCards({ inView }){
  return (
    <div className={"mod-grid " + (inView ? "in" : "")}>
      {MODULES.map((m, i) => (
        <div key={m.id} className="mod-card" style={{ '--delay': `${i*70}ms` }}>
          <div className="mod-icon"><ModuleIcon name={m.icon} /></div>
          <div className="mod-meta">
            <div className="mod-name">{m.name}</div>
            <div className="mod-desc">{m.desc}</div>
          </div>
          <div className="mod-tag">App</div>
        </div>
      ))}
    </div>
  );
}

// ----- Layout C: terminal stream -----
function ModulesStream({ inView }){
  return (
    <div className={"mod-stream " + (inView ? "in" : "")}>
      <div className="stream-head">
        <span className="dot r"></span>
        <span className="dot y"></span>
        <span className="dot g"></span>
        <span className="stream-title">solarmarket@os · loading modules</span>
      </div>
      <div className="stream-body">
        {MODULES.map((m, i) => (
          <div key={m.id} className="stream-line" style={{ '--delay': `${i*180 + 200}ms` }}>
            <span className="ln-num">{String(i+1).padStart(2, '0')}</span>
            <span className="ln-arrow">→</span>
            <span className="ln-name">{m.name}</span>
            <span className="ln-desc">{m.desc}</span>
            <span className="ln-status">loaded</span>
          </div>
        ))}
        <div className="stream-line cursor" style={{ '--delay': `${MODULES.length*180 + 400}ms` }}>
          <span className="ln-num">··</span>
          <span className="ln-arrow">→</span>
          <span className="ln-name typing">aguardando seu uso<span className="cur">_</span></span>
        </div>
      </div>
    </div>
  );
}

// ===========================================================
// CHAPTER 4 — Spotlight scrubs (Dimensionamento, Monitor, IA, Financeiro)
// ===========================================================
function ChapterFour(){
  const [ref, inView] = useInView(0.3);
  const [active, setActive] = useState(0);
  const [paused, setPaused] = useState(false);
  const spots = [
    { tag: 'Engenharia', name: 'Dimensionamento 3D',                 body: 'Coloque módulos no telhado direto no satélite. Sombras, inclinação, FioB.' },
    { tag: 'Pós Venda',  name: 'Monitoramento de Energia',           body: 'Geração ao vivo dos inversores e histórico de faturas da concessionária, no mesmo lugar.' },
    { tag: 'IA',         name: 'Agentes nativos e customizados de IA', body: 'Você comanda. Os agentes operam a plataforma por você — propostas, follow-ups, atendimento.' },
    { tag: 'Gestão',     name: 'Financeiro',                         body: 'Fluxo de caixa, conciliação, faturamento — sem precisar exportar nada.' },
  ];

  useEffect(() => {
    if (!inView || paused) return;
    const id = setInterval(() => setActive(a => (a+1) % spots.length), 3800);
    return () => clearInterval(id);
  }, [inView, paused]);

  function pick(i){
    setActive(i);
    setPaused(true);   // any manual pick pauses the auto-rotation
  }

  return (
    <section ref={ref} className={"ch ch-four " + (inView ? "in" : "")} data-screen-label="04 · Destaques">
      <div className="ch-shell wide">
        <div className="ch-eyebrow"><span className="bar"></span>Capítulo 04 · Alguns destaques</div>
        <div className="spot-stage">
          <div className="spot-list">
            {spots.map((s, i) => (
              <button key={i} className={"spot-item " + (i === active ? "active" : "")} onClick={() => pick(i)}>
                <span className="spot-num">{String(i+1).padStart(2, '0')}</span>
                <span className="spot-meta">
                  <span className="spot-tag">{s.tag}</span>
                  <span className="spot-name">{s.name}</span>
                </span>
                <span className="spot-bar"></span>
              </button>
            ))}

            <div className="spot-more">
              <span className="more-plus">+</span>
              <span className="more-meta">
                <span className="more-title">Espere mais. Terá mais.</span>
                <span className="more-sub">Isto é só uma fração do que vem por aí.</span>
              </span>
            </div>

            <button
              className={"spot-pause " + (paused ? "paused" : "")}
              onClick={() => setPaused(p => !p)}
              aria-label={paused ? 'Retomar troca automática' : 'Pausar troca automática'}
            >
              {paused ? (
                <><svg viewBox="0 0 24 24" fill="currentColor" width="13" height="13"><path d="M8 5v14l11-7z"/></svg>Retomar troca automática</>
              ) : (
                <><svg viewBox="0 0 24 24" fill="currentColor" width="13" height="13"><path d="M7 5h3v14H7zM14 5h3v14h-3z"/></svg>Pausar troca automática</>
              )}
            </button>
          </div>
          <div className="spot-view">
            <SpotlightVisual which={active} />
            <div className="spot-caption">
              <span className="spot-cap-tag">{spots[active].tag}</span>
              <h3 className="spot-cap-title">{spots[active].name}</h3>
              <p className="spot-cap-body">{spots[active].body}</p>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function SpotlightVisual({ which }){
  if (which === 0) return <Spot3D/>;
  if (which === 1) return <SpotMonitor/>;
  if (which === 2) return <SpotAI/>;
  return <SpotFin/>;
}

function Spot3D(){
  return (
    <div className="spot-vis vis-3d">
      <div className="roof">
        {Array.from({length: 32}).map((_, i) => (
          <div key={i} className="panel" style={{ '--i': i, '--delay': `${i*40}ms` }}></div>
        ))}
      </div>
      <div className="iso-grid"></div>
      <div className="vis-label">
        <span className="lab">Telhado · 7,8 kWp</span>
        <span className="lab num">32 módulos · 4 strings</span>
      </div>
    </div>
  );
}

function SpotMonitor(){
  const bars = Array.from({length: 30}, (_, i) => 0.28 + Math.abs(Math.sin(i*0.42))*0.68);
  const faturas = [
    { my: '03/2026', kwh: '512' },
    { my: '02/2026', kwh: '478' },
    { my: '01/2026', kwh: '534' },
    { my: '12/2025', kwh: '491' },
  ];
  return (
    <div className="spot-vis vis-monitor">
      <div className="mon-head">
        <span className="mon-stat"><span className="num">8,42</span><span className="u">kWh hoje</span></span>
        <span className="mon-stat sub"><span className="num">+12%</span><span className="u">vs ontem</span></span>
        <span className="mon-src"><span className="src-dot"></span>HOYMILES</span>
      </div>
      <div className="mon-chart">
        {bars.map((v, i) => <div key={i} className="bar" style={{ '--v': v, '--i': i }}></div>)}
      </div>
      <div className="mon-foot">
        <span>06:00</span><span>12:00</span><span>18:00</span>
      </div>

      <div className="mon-bills">
        <div className="bills-head">
          <span className="bills-title">Histórico de faturas</span>
          <span className="bills-src">CEMIG</span>
        </div>
        <div className="bills-grid">
          {faturas.map((f, i) => (
            <div key={i} className="bill">
              <span className="bill-my">{f.my}</span>
              <span className="bill-kwh">{f.kwh}<span className="u">kWh</span></span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function SpotAI(){
  return (
    <div className="spot-vis vis-ai">
      <div className="ai-msg user">
        <span className="who">Você · Integrador</span>
        <span className="txt">Alfredo, gera a proposta do lead Santos e me manda o resumo no WhatsApp.</span>
      </div>
      <div className="ai-msg agent">
        <span className="who">Alfredo · IA</span>
        <span className="txt">
          Fechado. Dimensionei <b>3,5 kWp</b>, montei a proposta e já joguei no funil. Resumo a caminho.
          <span className="ai-think">operando a plataforma por você<span className="dots"><span></span><span></span><span></span></span></span>
        </span>
      </div>
      <div className="ai-msg agent small">
        <span className="who">Alfredo · IA</span>
        <span className="txt">Proposta #4821 · ROI 4,2 anos · enviada no WhatsApp do cliente ✓</span>
      </div>
      <div className="ai-chip"><span></span>agente operando por você</div>
    </div>
  );
}

function SpotFin(){
  return (
    <div className="spot-vis vis-fin">
      <div className="fin-card">
        <div className="fin-label">Receita do mês</div>
        <div className="fin-value">R$ <span className="num">284.910</span></div>
        <div className="fin-delta">▲ 18,4% vs. mês anterior</div>
      </div>
      <div className="fin-row">
        <div className="fin-mini"><span>A receber</span><b>R$ 92.300</b></div>
        <div className="fin-mini"><span>A pagar</span><b>R$ 41.870</b></div>
        <div className="fin-mini"><span>Caixa</span><b>R$ 187.120</b></div>
      </div>
      <div className="fin-list">
        <div className="fin-tx"><span className="t">Distribuidor A</span><span className="v out">- R$ 12.400</span></div>
        <div className="fin-tx"><span className="t">Cliente · Santos</span><span className="v in">+ R$ 24.800</span></div>
        <div className="fin-tx"><span className="t">Folha</span><span className="v out">- R$ 18.200</span></div>
      </div>
    </div>
  );
}

// ===== Máscara de telefone BR: (00) 00000-0000 =====
function maskPhone(value){
  const d = value.replace(/\D/g, '').slice(0, 11);
  if (d.length <= 2) return d.replace(/^(\d{0,2})/, '($1');
  if (d.length <= 6) return d.replace(/^(\d{2})(\d{0,4})/, '($1) $2');
  if (d.length <= 10) return d.replace(/^(\d{2})(\d{4})(\d{0,4})/, '($1) $2-$3');
  return d.replace(/^(\d{2})(\d{5})(\d{0,4})/, '($1) $2-$3');
}

// ===========================================================
// CHAPTER 5 — Abertura + "avise-me" (Estado 1 / teaser)
// Anuncia a DATA de abertura (sem contador) e captura e-mail + WhatsApp
// (ambos obrigatórios, formatados) para avisar quando as inscrições abrirem.
// Persiste via POST /api/leads (estado "teaser"); só mostra a confirmação se a
// gravação der certo. A data vem da query string (?abertura=YYYY-MM-DD),
// injetada pela página /.
// ===========================================================
function ChapterFive({ targetDate }){
  const [ref, inView] = useInView(0.4);
  const date = new Date(targetDate);
  const diaStr = date.toLocaleDateString('pt-BR', { day: '2-digit' });
  const mesStr = date.toLocaleDateString('pt-BR', { month: 'long' });

  const [form, setForm] = useState({ email: '', whats: '', hp: '' });
  const [state, setState] = useState('idle'); // idle | err | ok
  const [errors, setErrors] = useState({});
  const [submitting, setSubmitting] = useState(false);

  function setField(k, v){
    setForm(f => ({ ...f, [k]: k === 'whats' ? maskPhone(v) : v }));
    setState('idle');
    setErrors(e => ({ ...e, [k]: false }));
  }

  async function submit(e){
    e.preventDefault();
    if (submitting) return;
    const errs = {};
    if (!/.+@.+\..+/.test(form.email)) errs.email = true;
    if (form.whats.replace(/\D/g, '').length < 10) errs.whats = true;
    if (Object.keys(errs).length){ setErrors(errs); setState('err'); return; }

    setSubmitting(true);
    try {
      const res = await fetch('/api/leads', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          estado: 'teaser',
          email: form.email,
          whatsapp: form.whats,
          hp: form.hp || '',
        }),
      });
      if (!res.ok) throw new Error('fail');
      setState('ok');
      if (window.FX) window.FX.pulse({ x: window.innerWidth*0.5, y: window.innerHeight*0.5, duration: 1400, color: 'rgba(251,176,59,0.4)' });
    } catch (_) {
      setState('err');
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <section ref={ref} className={"ch ch-five " + (inView ? "in" : "")} data-screen-label="05 · Avise-me">
      <div className="ch-shell narrow center">
        <div className="ch-eyebrow accent"><span className="bar acc"></span>Acesso Antecipado</div>
        <h2 className="ch-title big">
          As inscrições abrem<br/>
          <span className="hl-accent">{diaStr} de {mesStr}</span>.
        </h2>
        <p className="ch-lede">
          As vagas serão limitadas e por tempo curto. Deixe seu contato e avisamos
          você no momento em que abrirem.
        </p>

        {state !== 'ok' ? (
          <form className="waitlist big" onSubmit={submit} noValidate>
            {/* Honeypot anti-bot: escondido de humanos; bots tendem a preencher. */}
            <input
              type="text"
              name="hp"
              value={form.hp}
              onChange={e => setField('hp', e.target.value)}
              tabIndex="-1"
              autoComplete="off"
              aria-hidden="true"
              style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }}
            />
            <div className="wl-grid">
              <label className={"wl-input " + (errors.email ? 'err' : '')}>
                <span className="wl-lbl">E-mail</span>
                <input
                  type="email"
                  value={form.email}
                  onChange={e => setField('email', e.target.value)}
                  placeholder="seu@email.com.br"
                  autoComplete="email"
                  inputMode="email"
                />
              </label>
              <label className={"wl-input " + (errors.whats ? 'err' : '')}>
                <span className="wl-lbl">WhatsApp</span>
                <input
                  type="tel"
                  value={form.whats}
                  onChange={e => setField('whats', e.target.value)}
                  placeholder="(00) 00000-0000"
                  autoComplete="tel"
                  inputMode="numeric"
                />
              </label>
            </div>

            <button type="submit" className="wl-submit" disabled={submitting}>
              {submitting ? 'Enviando…' : 'Avise-me quando abrir'}
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" width="16" height="16"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
            </button>
            <div className="wl-meta">
              {state === 'err'
                ? <span className="err-msg">Não foi possível enviar agora. Confira o e-mail e o WhatsApp e tente novamente.</span>
                : <span>E-mail e WhatsApp são obrigatórios.</span>}
            </div>
          </form>
        ) : (
          <div className="wl-ok">
            <div className="ok-mark">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" width="32" height="32"><path d="M20 6 9 17l-5-5"/></svg>
            </div>
            <h3>Avisaremos você.</h3>
            <p>Quando as inscrições abrirem em <b>{diaStr} de {mesStr}</b>, o aviso chega em <b>{form.email}</b> e no seu WhatsApp.</p>
          </div>
        )}

        <div className="six-foot">
          <span>SolarMarket 2.0</span>
          <span className="dot">·</span>
          <span>De integrador para integrador</span>
          <span className="dot">·</span>
          <span>2026</span>
        </div>
      </div>
    </section>
  );
}

// Export everything
Object.assign(window, {
  ChapterOne, ChapterTwo, ChapterThree, ChapterFour, ChapterFive,
});
