// sections.jsx — B2Boost Paid Media · rediseño
const { useState, useEffect, useRef, useMemo } = React;
const D = () => window.LP;

/* ===== Integraciones reales (trasplantado de la version de produccion) ===== */
const KLAVIYO_COMPANY_ID = 'Wpj6Tn';
const KLAVIYO_LIST_ID    = 'UwFEs6';
const KLAVIYO_API_REV    = '2024-10-15';
const WEB3FORMS_KEY      = '81b3314c-af34-45fa-9186-79be8de7d3be';
function getUtms(){
  try{
    const p = new URLSearchParams(location.search), u = {};
    ['utm_source','utm_medium','utm_campaign','utm_content','utm_term'].forEach(k=>{const val=p.get(k);if(val)u[k]=val});
    return u;
  }catch(e){ return {}; }
}
function toE164MX(raw){
  if(!raw) return '';
  const d = raw.replace(/\D/g,''); if(!d) return '';
  if(d.startsWith('52') && d.length>=12) return '+'+d;
  if(d.length===10) return '+52'+d;
  return '+'+d;
}

/* media query hook */
function useMQ(q){
  const [m, setM] = useState(() => typeof window === 'undefined' ? false : window.matchMedia(q).matches);
  useEffect(() => {
    const mq = window.matchMedia(q);
    const on = () => setM(mq.matches);
    mq.addEventListener ? mq.addEventListener('change', on) : mq.addListener(on);
    return () => { mq.removeEventListener ? mq.removeEventListener('change', on) : mq.removeListener(on); };
  }, [q]);
  return m;
}
const useMobile = () => useMQ('(max-width:880px)');

/* Count-up number that animates when scrolled into view.
   Robust against frozen/throttled timelines (snaps to final via setTimeout). */
function CountUp({ end, dur = 1500, prefix = '', suffix = '', className }){
  const ref = useRef(null);
  const [val, setVal] = useState(0);
  const started = useRef(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    let raf;
    const animate = () => {
      if (started.current) return; started.current = true;
      let t0 = null;
      const step = (ts) => {
        if (t0 == null) t0 = ts;
        const p = Math.min((ts - t0) / dur, 1);
        const eased = 1 - Math.pow(1 - p, 3);
        setVal(Math.round(eased * end));
        if (p < 1) raf = requestAnimationFrame(step);
      };
      raf = requestAnimationFrame(step);
      setTimeout(() => setVal(end), dur + 300); // frozen-timeline fallback
    };
    const check = () => {
      const r = el.getBoundingClientRect();
      const vh = window.innerHeight || document.documentElement.clientHeight;
      if (r.top < vh * 0.9 && r.bottom > 0) animate();
    };
    check();
    const iv = setInterval(() => { check(); if (started.current) clearInterval(iv); }, 250);
    window.addEventListener('scroll', check, { passive: true });
    return () => { clearInterval(iv); cancelAnimationFrame(raf); window.removeEventListener('scroll', check); };
  }, [end, dur]);
  return <span ref={ref} className={className}>{prefix}{val.toLocaleString('es-MX')}{suffix}</span>;
}
function parseStat(str){
  const m = String(str).match(/^([^\d]*)(\d[\d,]*)(.*)$/);
  if (!m) return { prefix: '', end: 0, suffix: str };
  return { prefix: m[1], end: parseInt(m[2].replace(/,/g, ''), 10), suffix: m[3] };
}

/* Reusable numbered station header */
function Station({ num, kicker, children, sub, dark }){
  return (
    <div className="station reveal">
      <span className="station-num">{num}</span>
      <div className="station-meta">
        <span className="station-kicker">{kicker}</span>
        <h2 className="station-h">{children}</h2>
        {sub && <p className="station-sub">{sub}</p>}
      </div>
    </div>
  );
}

/* ============================================================ NAV */
function Nav(){
  const [open, setOpen] = useState(false);
  const [solid, setSolid] = useState(false);
  const [active, setActive] = useState('');
  useEffect(() => {
    const ids = D().NAV.map(n => n.href.replace('#', ''));
    const on = () => {
      setSolid(window.scrollY > 24);
      const y = window.scrollY + 140;
      let cur = '';
      for (const id of ids){
        const el = document.getElementById(id);
        if (el && el.offsetTop <= y) cur = id;
      }
      setActive(cur);
    };
    on(); window.addEventListener('scroll', on, { passive:true });
    return () => window.removeEventListener('scroll', on);
  }, []);
  return (
    <header className={`nav ${solid ? 'solid' : ''}`}>
      <div className="nav-in">
        <a className="brand" href="#top" aria-label="Sindicato">
          <img src="assets/sindicato-blanco.svg" alt="Sindicato"/>
          <span className="brand-sub">A Peltier<br/>Group company</span>
        </a>
        <nav className={`nav-links ${open ? 'open' : ''}`}>
          {D().NAV.map(n => <a key={n.href} href={n.href} className={active === n.href.replace('#','') ? 'active' : ''} onClick={() => setOpen(false)}>{n.label}</a>)}
        </nav>
        <div className="nav-cta">
          <a className="btn btn-primary btn-sm nav-cta-btn" href="#demo">
            <span className="lbl lbl-full">Agenda una cita</span>
            <span className="lbl lbl-short">Demo</span>
            <span className="ar" aria-hidden="true">↗</span>
          </a>
          <button className="nav-toggle" onClick={() => setOpen(!open)} aria-label="Menú">{open ? '×' : '≡'}</button>
        </div>
      </div>
    </header>
  );
}

/* ============================================================ HERO */
function HeroVideo(){
  const H = D().HERO;
  const ref = useRef(null);
  useEffect(() => { const v = ref.current; if (v){ const p = v.play(); if (p && p.catch) p.catch(()=>{}); } }, []);
  if (!H.video) return null;
  return (
    <div className="hero-video" aria-hidden="true">
      <video ref={ref} autoPlay muted loop playsInline preload="metadata"><source src={H.video} type="video/mp4"/></video>
    </div>
  );
}
function Hero(){
  const H = D().HERO;
  const reduce = useMQ('(prefers-reduced-motion: reduce)');
  return (
    <section className="hero" id="top">
      {!reduce && <HeroVideo/>}
      <div className="hero-grid" aria-hidden="true"></div>
      <div className="hero-in wrap">
        <div className="hero-eyebrow reveal">
          <span className="dot" aria-hidden="true"></span>
          {H.eyebrow.map((e, i) => (
            <React.Fragment key={i}>
              <span>{e}</span>
              {i < H.eyebrow.length - 1 && <span className="sep" aria-hidden="true"></span>}
            </React.Fragment>
          ))}
        </div>
        <h1 className="reveal" style={{'--d':1}}>
          {H.headline.map((l, i) => (
            <span className={`ln ${i === H.headline.length-1 ? 'ln-accent' : ''}`} key={i}>{l}</span>
          ))}
        </h1>
        <p className="hero-sub reveal" style={{'--d':2}}>{H.sub}</p>
        <p className="hero-micro reveal" style={{'--d':2}}>{H.micro}</p>
        <div className="hero-ctas reveal" style={{'--d':3}}>
          <a className="btn btn-primary" href={H.ctaPrimary.href}><span className="lbl">{H.ctaPrimary.label}</span><span className="ar" aria-hidden="true">↗</span></a>
          <a className="btn btn-ghost-light" href={H.ctaSecondary.href}><span className="lbl">{H.ctaSecondary.label}</span></a>
        </div>
        {H.reassure && (
          <div className="hero-reassure reveal" style={{'--d':3}}>
            {H.reassure.map((r, i) => <span key={i}>{r}</span>)}
          </div>
        )}
        <div className="flow reveal" style={{'--d':4}} role="img" aria-label="Flujo: pauta, lead, CRM, seguimiento, decisión">
          {H.flow.map((n, i) => (
            <div className="flow-node" key={i} style={{'--i': i}}>
              <div className="flow-rail" aria-hidden="true"><div className="pulse"></div></div>
              <span className="flow-dot" aria-hidden="true"></span>
              <span className="flow-label">{n.l}</span>
              <span className="flow-sub">{n.sub}</span>
            </div>
          ))}
        </div>
        <div className="hero-claim reveal" style={{'--d':5}}>
          <span className="lbl">Claim</span>
          <span className="txt">{H.claim}</span>
        </div>
      </div>
    </section>
  );
}

/* ============================================================ TRUST STRIP (early social proof) */
function TrustStrip(){
  const items = D().TRUST.items.slice(0, 6);
  return (
    <section className="trust-strip" aria-label="Experiencia operando marcas">
      <div className="wrap trust-strip-in reveal">
        <span className="lab">Experiencia del grupo operando marcas como</span>
        <div className="logos">
          {items.map(l => <img key={l.nm} src={l.src} alt={l.nm} title={l.nm} loading="lazy"/>)}
        </div>
      </div>
    </section>
  );
}

/* ============================================================ PROBLEM */
const MARK = { ok:'✓', bad:'✕', unk:'?' };
const STLABEL = { ok:'OK', bad:'Se corta', unk:'Sin lectura' };
function Chain({ rows, conn }){
  return (
    <ul className="chain">
      {rows.map((r, i) => (
        <li className={r.st} key={i}>
          <span className={`node-mark ${r.st}`} aria-hidden="true">{conn ? '✓' : MARK[r.st]}</span>
          <span>{r.s}</span>
          {!conn && <span className="st">{STLABEL[r.st]}</span>}
          {conn && <span className="st">OK</span>}
        </li>
      ))}
    </ul>
  );
}
function Problem(){
  const P = D().PROBLEM;
  return (
    <section className="sec sec-paper" id="problema">
      <div className="wrap">
        <div className="prob-grid">
          <div>
            <Station num={P.station} kicker={P.kicker}>
              {P.headline}<br/><span className="it">{P.accent}</span>
            </Station>
            <p className="station-sub reveal" style={{'--d':1}}>{P.body}</p>
            <ul className="prob-bullets reveal" style={{'--d':2}}>
              {P.bullets.map((b, i) => (
                <li key={i}>
                  <span className="x" aria-hidden="true">
                    <svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round"><path d="M6 6l12 12M18 6 6 18"/></svg>
                  </span>
                  <span>{b}</span>
                </li>
              ))}
            </ul>
            <div className="prob-closer reveal" style={{'--d':3}}>{P.closer}</div>
          </div>
          <div className="compare reveal" style={{'--d':1}}>
            <div className="cmp">
              <span className="cmp-label">{P.brokenLabel}</span>
              <Chain rows={P.broken}/>
            </div>
            <div className="cmp conn">
              <span className="cmp-label">{P.connectedLabel}</span>
              <Chain rows={P.connected} conn/>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================ SYSTEM */
function SystemVideo(){
  const S = D().SYSTEM;
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches){ try{ el.pause(); }catch(e){} return; }
    const io = new IntersectionObserver(([e]) => {
      if (!e) return;
      e.isIntersecting ? (el.play && el.play().catch(()=>{})) : (el.pause && el.pause());
    }, { threshold:0.25 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <div className="sys-video">
      <video ref={ref} muted autoPlay loop playsInline preload="metadata" aria-label={S.videoLabel}><source src={S.video} type="video/mp4"/></video>
      <div className="sys-video-ov" aria-hidden="true"></div>
      <span className="vlabel">{S.videoLabel}</span>
    </div>
  );
}
function System(){
  const S = D().SYSTEM;
  return (
    <section className="sec sec-paper" id="sistema">
      <div className="wrap">
        <Station num={S.station} kicker={S.kicker} sub={S.sub}>{S.headline}</Station>
        <div className="sys-chips reveal" style={{'--d':1}}>
          {S.chips.map((c, i) => <span className="sys-chip" key={i}>{c}</span>)}
        </div>
        <div className="sys-stage reveal" style={{'--d':1, marginTop:24}}>
          <div className="sys-route">
            <span className="sys-route-label">Ruta del sistema</span>
            <ol className="route-list">
              {S.route.map((r, i) => (
                <li className="route-node" key={i}>
                  <span className="route-dot" aria-hidden="true"></span>
                  <span className="route-body">
                    <span className="route-t">{r.t}</span>
                    <span className="route-c">{r.c}</span>
                  </span>
                </li>
              ))}
            </ol>
          </div>
          <SystemVideo/>
        </div>
      </div>
    </section>
  );
}

/* ============================================================ AI */
function AILayer(){
  const A = D().AI;
  return (
    <section className="sec sec-dark" id="ia">
      <div className="wrap">
        <div className="ai-grid">
          <div className="ai-side">
            <Station num={A.station} kicker={A.kicker} sub={A.sub}>{A.headline}</Station>
            <div className="ai-closer reveal" style={{'--d':1}}>{A.closer}</div>
            <a className="ai-cta reveal" style={{'--d':2}} href={A.cta.href}>
              <span>{A.cta.label}</span><span className="ar" aria-hidden="true">↗</span>
            </a>
          </div>
          <div className="ai-cards reveal" style={{'--d':1}}>
            {A.cards.map((c, i) => (
              <div className="ai-card" key={c.n} style={{'--d': i}}>
                <span className="ai-num">{c.n}</span>
                <h3 className="ai-t">{c.t}</h3>
                <p className="ai-copy">{c.c}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================ RESULTS + PROOF */
function Results(){
  const R = D().RESULTS;
  const T = D().TRUST;
  const f = R.feature;
  return (
    <section className="sec sec-dark" id="resultados">
      <div className="wrap">
        <Station num={R.station} kicker={R.kicker}>{R.headline}</Station>
        <div className="res-feature reveal" style={{'--d':1}}>
          <div>
            <div className="res-bignum"><CountUp end={parseInt(f.v, 10)} dur={1700}/><span className="sfx">{f.suffix}</span></div>
            <div className="res-k">{f.k}</div>
          </div>
          <div className="res-read">
            <p className="res-copy">{f.copy}</p>
            <div className="res-decision">
              <span className="rd-l">La decisión</span>
              <p>{f.read}</p>
            </div>
          </div>
        </div>
        <div className="res-metrics reveal" style={{'--d':1}}>
          <span className="res-metrics-label">{R.metricsLabel}</span>
          <div className="res-metrics-grid">
            {R.metrics.map((m, i) => {
              const ps = parseStat(m.v);
              return (
                <div className="rmc" key={i} style={{'--d': i}}>
                  <div className="rmc-v"><CountUp end={ps.end} prefix={ps.prefix} suffix={ps.suffix} dur={1300}/></div>
                  <div className="rmc-k">{m.k}</div>
                  <div className="rmc-note">{m.note}</div>
                </div>
              );
            })}
          </div>
        </div>
        <p className="res-disclaimer reveal">{R.disclaimer}</p>

        <div className="proof">
          <div className="proof-head reveal">
            <h3>{T.headline}</h3>
            <p>{T.sub}</p>
          </div>
          <div className="proof-grid reveal" style={{'--d':1}}>
            {T.items.map(l => (
              <div className="proof-item" key={l.nm} title={l.nm}><img src={l.src} alt={l.nm} loading="lazy"/></div>
            ))}
          </div>
          <p className="proof-disclaimer reveal">{T.disclaimer}</p>
        </div>
      </div>
    </section>
  );
}

/* ============================================================ TESTIMONIALS (placeholder — replace with real quotes) */
function initials(name){
  return name.split(' ').filter(Boolean).slice(0, 2).map(w => w[0]).join('').toUpperCase();
}
function Testimonials(){
  const T = D().TESTIMONIALS;
  return (
    <section className="tst-sec sec-paper" id="testimonios">
      <div className="wrap">
        <div className="tst-head reveal">
          <span className="station-kicker">{T.kicker}</span>
          <h2 className="station-h" style={{marginTop:14}}>{T.headline}</h2>
          <p className="station-sub" style={{marginTop:8}}>{T.sub}</p>
        </div>
        <div className="tst-grid">
          {T.items.map((t, i) => (
            <figure className="tst-card reveal" key={i} style={{'--d': i}}>
              <span className="tst-quote-mark" aria-hidden="true">&#8220;</span>
              <blockquote className="tst-quote">{t.quote}</blockquote>
              <figcaption className="tst-by">
                <span className="tst-avatar" aria-hidden="true">{initials(t.name)}</span>
                <span className="tst-meta">
                  <span className="tst-name">{t.name}</span>
                  <span className="tst-role">{t.role} · {t.company}</span>
                </span>
              </figcaption>
            </figure>
          ))}
        </div>
        {T.placeholderNote && <p className="tst-note reveal">{T.placeholderNote}</p>}
      </div>
    </section>
  );
}

/* ============================================================ OFFER */
function Offer(){
  const O = D().OFFER;
  const C = O.custom;
  return (
    <section className="sec sec-paper" id="oferta">
      <div className="wrap">
        <Station num={O.station} kicker={O.kicker} sub={O.sub}>{O.headline}</Station>
        <div className="offer-cards reveal" style={{'--d':1}}>
          {O.tiers.map((p, i) => {
            const totalMin = p.hon + p.pmin, totalMax = p.hon + p.pmax;
            return (
              <div className={`pcard ${p.feat ? 'feat' : ''}`} key={p.key}>
                {p.feat && <span className="pcard-flag">{p.flag}</span>}
                <div className="pcard-top">
                  <span className="pcard-key">{p.key}</span>
                  <span className="pcard-sub">{p.sub}</span>
                </div>
                <div className="pcard-total">
                  <span className="tl">Inversión mensual estimada</span>
                  <span className="tv">{pesoFull(totalMin)} a {pesoFull(totalMax)}<small>MXN / mes · fee + pauta</small></span>
                </div>
                <ul className="pbreak">
                  <li><span className="pk">Fee de agencia</span><span className="pv">{pesoFull(p.hon)}/mes</span></li>
                  <li><span className="pk">Pauta sugerida</span><span className="pv">{pesoFull(p.pmin)}–{pesoFull(p.pmax)}</span></li>
                  <li><span className="pk">Setup inicial</span><span className="pv">desde {pesoFull(p.setup)}</span></li>
                </ul>
                <div className="pcard-channels">
                  <span className="ck">Canales iniciales</span>
                  <span className="cv">{p.channels}</span>
                </div>
                <div className="pcard-cta">
                  <a className={`btn ${p.feat ? 'btn-primary' : 'btn-ghost'}`} href="#demo"><span className="lbl">{p.cta}</span><span className="ar" aria-hidden="true">↗</span></a>
                </div>
              </div>
            );
          })}
        </div>
        <div className="offer-custom reveal" style={{'--d':1}}>
          <div className="oc-l">
            <span className="pcard-key">{C.key}</span>
            <p className="oc-copy">{C.copy}</p>
          </div>
          <ul className="pbreak">
            <li><span className="pk">Fee de agencia</span><span className="pv">{C.fee}</span></li>
            <li><span className="pk">Pauta sugerida</span><span className="pv">{C.pauta}</span></li>
            <li><span className="pk">Inversión mensual</span><span className="pv">{C.total}</span></li>
            <li><span className="pk">Setup inicial</span><span className="pv">{C.setup}</span></li>
          </ul>
          <div className="pcard-cta" style={{paddingTop:0}}>
            <a className="btn btn-primary" href="#demo"><span className="lbl">{C.cta}</span><span className="ar" aria-hidden="true">↗</span></a>
          </div>
        </div>
        <p className="offer-setup-note reveal">{O.setupNote}</p>
      </div>
    </section>
  );
}

/* ============================================================ SIMULATOR */
function simDecide(pauta){
  let cfg, fee;
  if (pauta <= 14000)      { cfg='Start';   fee=8000;  }
  else if (pauta <= 30000) { cfg='Signal';  fee=12000; }
  else if (pauta <= 70000) { cfg='Control'; fee=25000; }
  else                     { cfg='Custom';  fee=null;  }
  const controlAdv = (cfg === 'Control' && pauta > 50000);
  const lecturaKey = controlAdv ? 'ControlAdv' : cfg;
  let channels;
  if (cfg === 'Start')        channels = 'Meta o Google Search, según industria';
  else if (cfg === 'Signal')  channels = 'Meta + Google Search';
  else if (cfg === 'Control') channels = controlAdv ? 'Canal mix a definir en setup' : 'Meta + Google Search + canal selectivo';
  else                        channels = 'Se define en arquitectura';
  const total = (fee != null) ? fee + pauta : null;
  return { cfg, fee, total, channels, lecturaKey };
}
function Simulator(){
  const M = D().SIM;
  const [v, setV] = useState({ ...M.defaults });
  const upd = (k, val) => setV(s => ({ ...s, [k]: val }));
  const out = useMemo(() => {
    const d = simDecide(v.pauta);
    const pautaOpt = M.pautaOpts.find(o => o.v === v.pauta);
    const feeText   = d.fee != null ? pesoFull(d.fee) + '/mes' : 'Según alcance';
    const pautaText = d.cfg === 'Custom' ? ((pautaOpt ? pautaOpt.l : '$120K+') + '/mes') : (pesoFull(v.pauta) + '/mes');
    const totalText = d.total != null ? pesoFull(d.total) + '/mes' : 'Cotización';
    const base = M.lectura[d.lecturaKey] || M.lectura[d.cfg] || '';
    const lectura = (base + ' ' + (M.lecturaSeg[v.seguimiento] || '')).trim();
    return { ...d, feeText, pautaText, totalText, lectura };
  }, [v]);

  const Field = ({ label, micro, opts, k }) => (
    <div className="sim-field">
      <label>{label}</label>
      {micro && <span className="micro">{micro}</span>}
      <div className="seg">
        {opts.map(o => (
          <button key={o.v} type="button" className={`seg-opt ${v[k] === o.v ? 'on' : ''}`} onClick={() => upd(k, o.v)}>{o.l}</button>
        ))}
      </div>
    </div>
  );

  return (
    <section className="sec sec-paper" id="simulador">
      <div className="wrap">
        <Station num={M.station} kicker={M.kicker} sub={M.sub}>{M.headline}</Station>
        <div className="sim-shell reveal" style={{'--d':1}}>
          <div className="sim-inputs">
            <Field label={M.pautaLabel} opts={M.pautaOpts} k="pauta"/>
            <Field label={M.ticketLabel} micro={M.ticketMicro} opts={M.ticketOpts} k="ticket"/>
            <Field label={M.seguimientoLabel} opts={M.seguimientoOpts} k="seguimiento"/>
          </div>
          <div className="sim-output">
            <span className="sim-out-head">Configuración sugerida</span>
            <span className="sim-config" key={out.cfg}>{out.cfg}</span>
            <div className="sim-rows">
              <div className="sim-line"><span className="sk">Fee de agencia</span><span className="sv" key={'f'+out.feeText}>{out.feeText}</span></div>
              <div className="sim-line"><span className="sk">Pauta seleccionada</span><span className="sv" key={'p'+out.pautaText}>{out.pautaText}</span></div>
              <div className="sim-line"><span className="sk">Canales iniciales</span><span className="sv" style={{maxWidth:200,whiteSpace:'normal',fontSize:13}}>{out.channels}</span></div>
              <div className="sim-line total"><span className="sk">Inversión mensual estimada</span><span className="sv" key={'t'+out.totalText}>{out.totalText}</span></div>
            </div>
            <div className="sim-reading">
              <span className="rl">Lectura</span>
              <p>{out.lectura}</p>
            </div>
            <div className="sim-actions">
              <a className="btn btn-primary" href={M.cta.href}><span className="lbl">{M.cta.label}</span><span className="ar" aria-hidden="true">↗</span></a>
              <p className="sim-cta-micro">{M.ctaMicro}</p>
            </div>
          </div>
        </div>
        <p className="sim-disclaimer reveal">{M.disclaimer}</p>
      </div>
    </section>
  );
}

/* ============================================================ DEMO */
function DemoForm(){
  const DM = D().DEMO;
  const [f, setF] = useState({ nombre:'', empresa:'', correo:'', whatsapp:'', sitio:'', vende:'', resolver:'', consent:false });
  const [status, setStatus] = useState('idle');
  const [err, setErr] = useState('');
  const upd = (k, val) => setF(s => ({ ...s, [k]: val }));
  const submit = async (e) => {
    e.preventDefault();
    if (status === 'sending' || status === 'sent') return;
    const okMail = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(f.correo);
    if (!(f.nombre && f.empresa && okMail)){ setErr('Faltan datos: nombre, empresa y correo válido.'); setStatus('error'); return; }
    setErr(''); setStatus('sending');
    // Conversion (Pixel + GA4 + dataLayer)
    try { if (typeof fbq === 'function') fbq('track','Lead',{content_name:f.resolver||'paid_media',content_category:'B2Boost Paid Media',value:0,currency:'MXN'}); } catch(e){}
    try { if (typeof gtag === 'function') gtag('event','generate_lead',{method:'form',empresa:f.empresa,origen:'lp_sindicato_demo'}); } catch(e){}
    try { (window.dataLayer = window.dataLayer || []).push({event:'form_submit',form_name:'lp_sindicato_demo',empresa:f.empresa}); } catch(e){}
    // Envio REAL a Web3Forms (llega a hola@peltiermkt.com)
    const fd = new FormData();
    fd.append('access_key', WEB3FORMS_KEY);
    fd.append('subject', 'Lead Demo Guiada — B2Boost Paid Media');
    fd.append('from_name', 'B2Boost Paid Media — lp.sindicato.agency');
    fd.append('botcheck', '');
    fd.append('nombre', f.nombre);
    fd.append('empresa', f.empresa);
    fd.append('correo', f.correo);
    fd.append('whatsapp', f.whatsapp);
    fd.append('sitio_web', f.sitio);
    fd.append('como_vende_hoy', f.vende);
    fd.append('que_resolver_primero', f.resolver);
    fd.append('consentimiento_marketing', f.consent ? 'sí' : 'no');
    fd.append('origen', 'lp_sindicato_demo');
    fd.append('fecha_envio', new Date().toISOString());
    const utms = getUtms();
    Object.keys(utms).forEach(k => fd.append(k, utms[k]));
    let ok = false;
    try {
      const res = await fetch('https://api.web3forms.com/submit', {method:'POST',headers:{'Accept':'application/json'},body:fd});
      const j = await res.json();
      ok = res.status === 200 && j.success;
      if (!ok) console.warn('Web3Forms no-ok:', j);
    } catch(e){ console.warn('Web3Forms failed:', e); }
    // Suscripcion Klaviyo (email marketing)
    try {
      const body = {data:{type:'subscription',attributes:{
        custom_source:'B2Boost Paid Media · lp.sindicato.agency',
        profile:{data:{type:'profile',attributes:{
          email: f.correo,
          phone_number: toE164MX(f.whatsapp) || undefined,
          first_name: f.nombre,
          organization: f.empresa,
          properties: {
            b2boost_paid_sitio_web: f.sitio,
            b2boost_paid_como_vende: f.vende,
            b2boost_paid_resolver: f.resolver,
            b2boost_paid_consentimiento_marketing: f.consent ? 'si' : 'no',
            b2boost_paid_origen: 'lp_sindicato_landing',
            b2boost_paid_fecha_envio: new Date().toISOString(),
            ...utms,
          }
        }}}
      },relationships:{list:{data:{type:'list',id:KLAVIYO_LIST_ID}}}}};
      fetch('https://a.klaviyo.com/client/subscriptions/?company_id='+KLAVIYO_COMPANY_ID, {
        method:'POST',
        headers:{'Content-Type':'application/json','revision':KLAVIYO_API_REV},
        body: JSON.stringify(body)
      }).catch(e => console.warn('Klaviyo:', e));
    } catch(e){}
    setStatus('sent');
  };
  if (status === 'sent'){
    return (
      <div className="demo-confirm">
        <span className="ico" aria-hidden="true">✓</span>
        <h3>Listo.</h3>
        <p>{DM.success}</p>
        <span className="meta">{f.nombre} · {f.empresa} · {f.correo}</span>
      </div>
    );
  }
  const sending = status === 'sending';
  return (
    <form className="demo-form" onSubmit={submit} noValidate>
      <div className="demo-form-head"><h3>{DM.formTitle}</h3><p>{DM.formSub}</p></div>
      <div className="fgrid">
        <div className="lf"><label htmlFor="d_n">Nombre <span className="req">*</span></label><input id="d_n" type="text" value={f.nombre} onChange={e=>upd('nombre',e.target.value)}/></div>
        <div className="lf"><label htmlFor="d_e">Empresa <span className="req">*</span></label><input id="d_e" type="text" value={f.empresa} onChange={e=>upd('empresa',e.target.value)}/></div>
        <div className="lf"><label htmlFor="d_c">Email corporativo <span className="req">*</span></label><input id="d_c" type="email" value={f.correo} onChange={e=>upd('correo',e.target.value)}/></div>
        <div className="lf"><label htmlFor="d_w">Teléfono / WhatsApp</label><input id="d_w" type="tel" value={f.whatsapp} onChange={e=>upd('whatsapp',e.target.value)}/></div>
        <div className="lf"><label htmlFor="d_s">Sitio web</label><input id="d_s" type="text" inputMode="url" value={f.sitio} onChange={e=>upd('sitio',e.target.value)} placeholder="https://"/></div>
        <div className="lf"><label htmlFor="d_r">¿Qué resolver primero?</label>
          <select id="d_r" value={f.resolver} onChange={e=>upd('resolver',e.target.value)}>
            <option value="">Selecciona una opción</option>
            {DM.needOpts.map((o,i)=><option key={i} value={o}>{o}</option>)}
          </select>
        </div>
        <div className="lf full"><label htmlFor="d_v">¿Cómo vendes hoy?</label><textarea id="d_v" rows="3" value={f.vende} onChange={e=>upd('vende',e.target.value)} placeholder="Canal, equipo comercial, dónde llegan tus leads, cómo les das seguimiento."/></div>
      </div>
      <ul className="demo-reassure">
        {DM.reassure.map((r,i)=>(<li key={i}><span className="rk">{r.k}</span><span className="rv">{r.v}</span></li>))}
      </ul>
      <label className="demo-consent"><input type="checkbox" checked={f.consent} onChange={e=>upd('consent',e.target.checked)}/><span>Acepto recibir información comercial de Sindicato.</span></label>
      <div className="demo-submit">
        <button type="submit" className="btn btn-primary" disabled={sending}><span className="lbl">{sending ? 'Enviando…' : 'Agenda una cita'}</span><span className="ar" aria-hidden="true">↗</span></button>
        {status === 'error' && err && <span className="demo-err">{err}</span>}
      </div>
    </form>
  );
}
function Demo(){
  const DM = D().DEMO;
  return (
    <section className="sec sec-paper" id="demo">
      <div className="wrap">
        <div className="demo-grid">
          <div className="demo-side">
            <Station num={DM.station} kicker={DM.kicker} sub={DM.body}>{DM.headline}</Station>
            <ul className="demo-bullets reveal" style={{'--d':1}}>
              {DM.bullets.map((b,i)=>(<li key={i}><span className="d" aria-hidden="true"></span><span>{b}</span></li>))}
            </ul>
            <a className="demo-wa reveal" style={{'--d':2}} href={D().WA_URL} target="_blank" rel="noopener"><span>{DM.waSecondary}</span><span className="ar" aria-hidden="true">↗</span></a>
          </div>
          <div className="demo-card reveal" style={{'--d':1}}><DemoForm/></div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================ FAQ */
function FAQ(){
  const items = D().FAQ;
  const [open, setOpen] = useState(0);
  return (
    <section className="sec sec-paper" id="faq">
      <div className="wrap">
        <div className="faq-grid">
          <div className="reveal">
            <span className="station-kicker" style={{marginBottom:18, display:'inline-flex'}}>Dudas</span>
            <h2 className="station-h" style={{marginTop:14}}>Preguntas frecuentes.</h2>
            <p className="station-sub" style={{marginTop:20}}>Las dudas que llegan más seguido, respondidas con la misma claridad con la que opera el sistema.</p>
          </div>
          <div className="faq-items reveal" style={{'--d':1}}>
            {items.map((it, i) => (
              <div className={`faq-item ${open === i ? 'open' : ''}`} key={i}>
                <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)} aria-expanded={open === i}>
                  <span>{it.q}</span><span className="ic" aria-hidden="true"></span>
                </button>
                <div className="faq-a"><div><p>{it.a}</p></div></div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================ FOOTER */
function Footer(){
  const c = D().CONTACT;
  return (
    <footer>
      <div className="footer-word" aria-hidden="true">EL RESULTADO</div>
      <div className="wrap footer-in">
        <img className="footer-logo" src="assets/b2boost-blanco.svg" alt="B2Boost"/>
        <div className="footer-claim">El resultado es <span className="it">el que manda.</span></div>
        <div className="footer-actions">
          <a className="btn btn-primary" href="#demo"><span className="lbl">Agenda una cita</span><span className="ar" aria-hidden="true">↗</span></a>
          <a className="btn btn-ghost-light" href="#simulador"><span className="lbl">Simular mi inversión</span></a>
        </div>
        <div className="footer-eco">
          <span className="lab">B2Boost Paid Media by Sindicato · A Peltier Group company</span>
          <a href="https://peltiermkt.com/" target="_blank" rel="noopener"><span>Peltier Group</span><span className="ar" aria-hidden="true">↗</span></a>
        </div>
        <div className="footer-bottom">
          <span>© {new Date().getFullYear()} Sindicato · Peltier Group</span>
          <span>{c.addr} · <a href={`mailto:${c.mail}`}>{c.mail}</a></span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Nav, Hero, TrustStrip, Problem, System, AILayer, Results, Testimonials, Offer, Simulator, Demo, FAQ, Footer, CountUp });
