/* ============================================================
   APIQO — Sections part 2 (Fleet, Stack, ROI, Process, FAQ, CTA, Footer)
   ============================================================ */

/* ---------- 03 · Fleet diagram ---------- */
const SectionFleet = ({ t }) => {
  const [pulse, setPulse] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setPulse(p => (p + 1) % 4), 1400);
    return () => clearInterval(id);
  }, []);

  return (
    <section className="sec-fleet">
      <div className="container">
        <div className="section-head">
          <div className="eyebrow" style={{ color: 'var(--brand-cyan)' }}>{t.fleet.eyebrow}</div>
          <h2>{t.fleet.h2}</h2>
          <p>{t.fleet.p}</p>
        </div>

        <div className="fleet-canvas">
          <FleetDiagram pulse={pulse} />
          <div className="fleet-legend">
            <div className="fleg"><span className="leg-d" style={{ background: 'var(--ink)' }}/>{t.fleet.legend.orch}</div>
            <div className="fleg"><span className="leg-d" style={{ background: 'var(--brand-magenta)' }}/>{t.fleet.legend.agent}</div>
            <div className="fleg"><span className="leg-d" style={{ background: 'var(--brand-cyan)' }}/>{t.fleet.legend.tool}</div>
            <div className="fleg"><span className="leg-d" style={{ background: 'var(--brand-blue)' }}/>{t.fleet.legend.human}</div>
          </div>
        </div>
      </div>
    </section>
  );
};

const FleetDiagram = ({ pulse }) => (
  <svg viewBox="0 0 1100 480" className="fleet-svg" preserveAspectRatio="xMidYMid meet">
    <defs>
      <linearGradient id="line-grad" x1="0" y1="0" x2="1" y2="0">
        <stop offset="0%" stopColor="#CD3266" stopOpacity="0.0"/>
        <stop offset="50%" stopColor="#CD3266" stopOpacity="0.7"/>
        <stop offset="100%" stopColor="#CD3266" stopOpacity="0.0"/>
      </linearGradient>
    </defs>

    {/* grid */}
    <g stroke="#EFF0F3" strokeWidth="1">
      {Array.from({length: 11}).map((_,i)=> <line key={'v'+i} x1={i*110} y1="0" x2={i*110} y2="480"/>)}
      {Array.from({length: 5}).map((_,i)=> <line key={'h'+i} x1="0" y1={i*120} x2="1100" y2={i*120}/>)}
    </g>

    {/* connections from orchestrator to agents */}
    {[180, 380, 580, 780, 920].map((x, i) => (
      <g key={'c'+i}>
        <path d={`M 550 140 Q ${(550+x)/2} 200 ${x} 260`} stroke="#D8DAE0" strokeWidth="1.2" fill="none"/>
        <circle r="4" fill="#CD3266" opacity={pulse === (i % 4) ? 1 : 0.15}>
          <animateMotion dur="2.4s" repeatCount="indefinite" path={`M 550 140 Q ${(550+x)/2} 200 ${x} 260`} />
        </circle>
      </g>
    ))}

    {/* agent → tool lines */}
    {[180,380,580,780,920].map((x,i)=>(
      <line key={'t'+i} x1={x} y1="320" x2={x} y2="400" stroke="#E6E7EB" strokeWidth="1"/>
    ))}

    {/* Orchestrator */}
    <g transform="translate(490,90)">
      <rect width="120" height="80" rx="14" fill="#0A0B0E"/>
      <rect width="120" height="80" rx="14" fill="none" stroke="#0A0B0E" strokeWidth="2"/>
      <text x="60" y="36" textAnchor="middle" fill="white" fontFamily="'JetBrains Mono', monospace" fontSize="10" letterSpacing="1.5">ORCHESTRATOR</text>
      <text x="60" y="60" textAnchor="middle" fill="white" fontFamily="'Nunito', sans-serif" fontWeight="800" fontSize="18">apiqo.core</text>
    </g>

    {/* 5 agent nodes */}
    {[
      { x: 180, c: '#CD3266', name: 'Sofía',  r: 'Prospectos' },
      { x: 380, c: '#CD3266', name: 'Diego',  r: 'Cobranza'   },
      { x: 580, c: '#0439D9', name: 'Mateo',  r: 'Soporte'    },
      { x: 780, c: '#54AFBC', name: 'Luna',   r: 'Reportes'   },
      { x: 920, c: '#CD3266', name: 'Ema',    r: 'RR.HH.'     },
    ].map((a, i) => (
      <g key={'a'+i} transform={`translate(${a.x-60},260)`}>
        <rect width="120" height="60" rx="12" fill="white" stroke="#E6E7EB"/>
        <circle cx="20" cy="30" r="8" fill={a.c}/>
        <text x="36" y="26" fill="#0A0B0E" fontFamily="'Nunito', sans-serif" fontWeight="800" fontSize="14">{a.name}</text>
        <text x="36" y="42" fill="#54575F" fontFamily="'JetBrains Mono', monospace" fontSize="9" letterSpacing="1">{a.r.toUpperCase()}</text>
      </g>
    ))}

    {/* tool nodes */}
    {[
      { x: 180, label: 'HubSpot' },
      { x: 380, label: 'monday'  },
      { x: 580, label: 'Zendesk' },
      { x: 780, label: 'Sheets'  },
      { x: 920, label: 'Workable'},
    ].map((tool, i) => (
      <g key={'tn'+i} transform={`translate(${tool.x-46},400)`}>
        <rect width="92" height="36" rx="8" fill="#ECF7F8" stroke="#54AFBC" strokeOpacity="0.3"/>
        <text x="46" y="22" textAnchor="middle" fill="#0A0B0E" fontFamily="'JetBrains Mono', monospace" fontSize="11">{tool.label}</text>
      </g>
    ))}

    {/* human in the loop */}
    <g transform="translate(40, 90)">
      <rect width="120" height="80" rx="14" fill="white" stroke="#0439D9" strokeWidth="1.6" strokeDasharray="4 3"/>
      <circle cx="60" cy="38" r="10" fill="#0439D9"/>
      <path d="M44 62 Q60 50 76 62" stroke="#0439D9" strokeWidth="2" fill="none"/>
      <text x="60" y="76" textAnchor="middle" fill="#0439D9" fontFamily="'JetBrains Mono', monospace" fontSize="9" letterSpacing="1">HUMAN.LOOP</text>
    </g>
    <path d="M 160 140 Q 320 120 490 130" stroke="#0439D9" strokeWidth="1.4" strokeDasharray="3 4" fill="none"/>
  </svg>
);

/* ---------- 04 · Stack + MCP ---------- */
const SectionStack = ({ t }) => (
  <section id="stack" className="sec-light">
    <div className="container">
      <div className="section-head">
        <div className="eyebrow" style={{ color: 'var(--brand-blue)' }}>{t.stack.eyebrow}</div>
        <h2>{t.stack.h2}</h2>
        <p>{t.stack.p}</p>
      </div>

      <div className="stack-grid">
        <div className="stack-col">
          <div className="stack-col-head mono">MODELS</div>
          <StackItem name="Claude" sub="Anthropic · Sonnet 4 / Opus" tag="primary" />
          <StackItem name="Gemini" sub="Google · 2.5 Pro" tag="secondary" />
          <StackItem name="GPT-4o" sub="OpenAI · backup" tag="secondary" />
          <StackItem name="Llama 3.3" sub="open-weight · privado" tag="optional" />
        </div>
        <div className="stack-col">
          <div className="stack-col-head mono">ORCHESTRATION</div>
          <StackItem name="n8n" sub="flujos visuales · self-hosted" tag="primary" />
          <StackItem name="Make" sub="conexiones rápidas" tag="primary" />
          <StackItem name="LangGraph" sub="estado de agente · grafos" tag="secondary" />
          <StackItem name="Apiqo Core" sub="orquestador propio" tag="primary" />
        </div>
        <div className="stack-col">
          <div className="stack-col-head mono">SYSTEMS · MCP</div>
          <StackItem name="monday.com" sub="boards · automations" tag="primary" />
          <StackItem name="WhatsApp BA" sub="canal de cliente" tag="primary" />
          <StackItem name="HubSpot · Zendesk" sub="CRM · soporte" tag="secondary" />
          <StackItem name="Sheets · Notion · Slack" sub="datos · conocimiento · señales" tag="secondary" />
        </div>
      </div>

      <div className="mcp-callout">
        <div className="mcp-tag mono">{t.stack.mcpTag}</div>
        <div className="mcp-grid">
          <div>
            <h3 className="display mcp-title">{t.stack.mcpTitle}</h3>
            <p className="mcp-p">{t.stack.mcpP}</p>
          </div>
          <McpDiagram />
        </div>
      </div>
    </div>
  </section>
);

const StackItem = ({ name, sub, tag }) => (
  <div className="stack-item">
    <div className="stack-item-l">
      <div className="stack-item-name display">{name}</div>
      <div className="stack-item-sub mono">{sub}</div>
    </div>
    <div className={`stack-item-tag tag-${tag}`}>{tag}</div>
  </div>
);

const McpDiagram = () => (
  <svg viewBox="0 0 480 280" className="mcp-svg">
    <defs>
      <pattern id="dotgrid" width="14" height="14" patternUnits="userSpaceOnUse">
        <circle cx="1" cy="1" r="1" fill="#E6E7EB"/>
      </pattern>
    </defs>
    <rect width="480" height="280" fill="url(#dotgrid)"/>

    {/* model bubble */}
    <g transform="translate(20, 100)">
      <rect width="140" height="80" rx="12" fill="#0A0B0E"/>
      <text x="70" y="32" textAnchor="middle" fill="white" fontFamily="'JetBrains Mono', monospace" fontSize="9" letterSpacing="1.5">MODEL</text>
      <text x="70" y="56" textAnchor="middle" fill="white" fontFamily="'Nunito', sans-serif" fontWeight="800" fontSize="18">claude</text>
    </g>

    {/* MCP gateway */}
    <g transform="translate(190, 80)">
      <rect width="100" height="120" rx="12" fill="white" stroke="#0439D9" strokeWidth="2"/>
      <text x="50" y="28" textAnchor="middle" fill="#0439D9" fontFamily="'JetBrains Mono', monospace" fontSize="10" letterSpacing="1.5">MCP</text>
      <line x1="14" y1="42" x2="86" y2="42" stroke="#EFF0F3"/>
      <text x="50" y="62" textAnchor="middle" fill="#0A0B0E" fontFamily="'JetBrains Mono', monospace" fontSize="9">read-customer</text>
      <text x="50" y="80" textAnchor="middle" fill="#0A0B0E" fontFamily="'JetBrains Mono', monospace" fontSize="9">create-invoice</text>
      <text x="50" y="98" textAnchor="middle" fill="#0A0B0E" fontFamily="'JetBrains Mono', monospace" fontSize="9">move-card</text>
    </g>

    {/* systems */}
    {['monday','HubSpot','Sheets'].map((s,i)=>(
      <g key={s} transform={`translate(330, ${50 + i*70})`}>
        <rect width="110" height="48" rx="10" fill="#ECF7F8" stroke="#54AFBC" strokeOpacity=".3"/>
        <text x="55" y="29" textAnchor="middle" fill="#0A0B0E" fontFamily="'JetBrains Mono', monospace" fontSize="11">{s}</text>
      </g>
    ))}

    {/* arrows */}
    <line x1="160" y1="140" x2="190" y2="140" stroke="#0A0B0E" strokeWidth="1.4"/>
    {[74, 144, 214].map((y,i)=>(
      <line key={i} x1="290" y1="140" x2="330" y2={y} stroke="#54AFBC" strokeWidth="1.4"/>
    ))}
  </svg>
);

/* ---------- 05 · ROI calculator ---------- */
const SectionROI = ({ t }) => {
  const [fte, setFte] = React.useState(8);
  const [hrs, setHrs] = React.useState(20);
  const [auto, setAuto] = React.useState(60);
  const [cost, setCost] = React.useState(28);

  const monthlyHours = fte * hrs * 4 * (auto / 100);
  const monthlyMoney = monthlyHours * cost;
  const setup = 18000;
  const monthly = 3500;
  const payback = monthlyMoney > monthly ? Math.max(2, Math.ceil((setup) / ((monthlyMoney - monthly) / 4))) : 99;

  return (
    <section id="roi" className="sec-soft">
      <div className="container">
        <div className="section-head">
          <div className="eyebrow" style={{ color: 'var(--brand-magenta)' }}>{t.roi.eyebrow}</div>
          <h2>{t.roi.h2}</h2>
          <p>{t.roi.p}</p>
        </div>

        <div className="roi-grid">
          <div className="roi-controls">
            <RoiSlider label={t.roi.lFte} v={fte} set={setFte} min={1} max={50} fmt={v=>v} />
            <RoiSlider label={t.roi.lHrs} v={hrs} set={setHrs} min={1} max={40} fmt={v=>`${v} h`} />
            <RoiSlider label={t.roi.lAuto} v={auto} set={setAuto} min={10} max={90} fmt={v=>`${v}%`} />
            <RoiSlider label={t.roi.lCost} v={cost} set={setCost} min={8} max={120} fmt={v=>`USD ${v}`} />
          </div>

          <div className="roi-out">
            <div className="roi-eyebrow mono">{t.roi.out}</div>
            <div className="roi-big display tab-num">
              {Math.round(monthlyMoney).toLocaleString()}<span className="roi-curr">USD</span>
            </div>
            <div className="roi-sub">{t.roi.money}</div>

            <div className="roi-pair">
              <div>
                <div className="roi-num display tab-num">{Math.round(monthlyHours).toLocaleString()}</div>
                <div className="roi-num-l">{t.roi.hours}</div>
              </div>
              <div>
                <div className="roi-num display tab-num">{payback}</div>
                <div className="roi-num-l">{t.roi.payback}</div>
              </div>
            </div>

            <div className="roi-bar">
              <div className="roi-bar-fill" style={{ width: `${Math.min(100, (monthlyMoney/30000)*100)}%` }}/>
            </div>
            <div className="roi-note mono">{t.roi.note}</div>
          </div>
        </div>
      </div>
    </section>
  );
};

const RoiSlider = ({ label, v, set, min, max, fmt }) => (
  <div className="roi-slider">
    <div className="roi-slider-row">
      <span className="roi-slider-l">{label}</span>
      <span className="roi-slider-v mono tab-num">{fmt(v)}</span>
    </div>
    <input type="range" min={min} max={max} value={v} onChange={e=>set(+e.target.value)}/>
  </div>
);

/* ---------- 06 · Process ---------- */
const SectionProcess = ({ t }) => (
  <section id="process" className="sec-light">
    <div className="container">
      <div className="section-head">
        <div className="eyebrow" style={{ color: 'var(--brand-blue)' }}>{t.process.eyebrow}</div>
        <h2>{t.process.h2}</h2>
      </div>
      <div className="proc-grid">
        {t.process.steps.map((s, i) => (
          <div className="proc-card" key={i}>
            <div className="proc-n display">{s.n}</div>
            <h3 className="proc-t display">{s.t}</h3>
            <p className="proc-d">{s.d}</p>
          </div>
        ))}
      </div>
    </div>
  </section>
);

/* ---------- 07 · FAQ ---------- */
const SectionFAQ = ({ t }) => {
  const [open, setOpen] = React.useState(0);
  return (
    <section className="sec-soft">
      <div className="container">
        <div className="section-head">
          <div className="eyebrow" style={{ color: 'var(--brand-cyan)' }}>{t.faq.eyebrow}</div>
          <h2>{t.faq.h2}</h2>
        </div>
        <div className="faq">
          {t.faq.items.map((it, i) => (
            <div key={i} className={`faq-item ${open === i ? 'open' : ''}`} onClick={() => setOpen(open === i ? -1 : i)}>
              <div className="faq-q">
                <span className="mono faq-n">{String(i+1).padStart(2,'0')}</span>
                <span className="display faq-qt">{it.q}</span>
                <span className="faq-toggle">{open===i ? '−' : '+'}</span>
              </div>
              <div className="faq-a">{it.a}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

/* ---------- Quoter Widget ---------- */
const QuoterWidget = ({ onComplete, onRequestForm }) => {
  const [activeTab, setActiveTab] = React.useState('web');
  const [step, setStep] = React.useState(0);
  const [selections, setSelections] = React.useState({});
  const [done, setDone] = React.useState(false);

  const webQuestions = [
    {
      q: '¿Qué tipo de sitio necesitas?',
      options: [
        { label: 'Landing page', price: 800 },
        { label: 'Sitio corporativo', price: 1800 },
        { label: 'E-commerce', price: 3000 },
        { label: 'Portal / App web', price: 5000 }
      ]
    },
    {
      q: '¿Necesitas diseño?',
      options: [
        { label: 'Tengo mockups o Figma', price: 0 },
        { label: 'Necesito guía de estilo', price: 400 },
        { label: 'Diseño desde cero', price: 800 }
      ]
    },
    {
      q: '¿Qué integraciones necesitas?',
      options: [
        { label: 'Ninguna por ahora', price: 0 },
        { label: 'CRM o WhatsApp', price: 400 },
        { label: 'Pagos online', price: 600 },
        { label: 'Varias integraciones', price: 1000 }
      ]
    },
    {
      q: '¿Cuál es tu plazo?',
      options: [
        { label: 'Flexible (4+ semanas)', price: 0, multiplier: 1.0 },
        { label: '3 semanas', price: 0, multiplier: 1.15 },
        { label: '2 semanas o menos', price: 0, multiplier: 1.25 }
      ]
    }
  ];

  const n8nQuestions = [
    {
      q: '¿Qué proceso quieres automatizar?',
      options: [
        { label: 'Generación de leads', price: 600 },
        { label: 'Cobranza y pagos', price: 700 },
        { label: 'Soporte al cliente (L1)', price: 800 },
        { label: 'Reportes y análisis', price: 500 },
        { label: 'RR.HH. o Compras', price: 650 }
      ]
    },
    {
      q: '¿Cuántos sistemas conectarás?',
      options: [
        { label: '1-2 sistemas', price: 0, multiplier: 1.0 },
        { label: '3-4 sistemas', price: 0, multiplier: 1.3 },
        { label: '5 o más sistemas', price: 0, multiplier: 1.6 }
      ]
    },
    {
      q: '¿Necesitas IA incluida?',
      options: [
        { label: 'Solo automatización', price: 0 },
        { label: 'Con agente de IA', price: 800 },
        { label: 'No sé, necesito asesoría', price: 0 }
      ]
    },
    {
      q: '¿Volumen mensual estimado?',
      options: [
        { label: 'Menos de 500 ejecuciones', price: 0 },
        { label: '500 a 5,000 ejecuciones', price: 200 },
        { label: 'Más de 5,000 ejecuciones', price: 400 }
      ]
    },
    {
      q: '¿Qué documentación tienes?',
      options: [
        { label: 'Bien documentado', price: 0 },
        { label: 'Parcialmente documentado', price: 150 },
        { label: 'Sin documentación', price: 300 }
      ]
    }
  ];

  const questions = activeTab === 'web' ? webQuestions : n8nQuestions;
  const currentQ = questions[step];
  const selectedIdx = selections[step] !== undefined ? selections[step] : -1;

  const calcPrice = (qs, sels) => {
    let base = 0, mult = 1.0;
    Object.keys(sels).forEach(qi => {
      const q = qs[parseInt(qi)];
      const opt = q && q.options[sels[qi]];
      if (opt) {
        base += opt.price || 0;
        if (opt.multiplier) mult = opt.multiplier;
      }
    });
    const total = Math.round(base * mult);
    return { total, min: Math.round(total * 0.9), max: Math.round(total * 1.2) };
  };

  const livePrice = calcPrice(questions, selections);
  const hasPrice = livePrice.total > 0;

  const getOptionTag = (opt) => {
    if (opt.multiplier && opt.multiplier !== 1.0) return '×' + opt.multiplier;
    if (opt.price > 0) return '+$' + opt.price.toLocaleString();
    return 'Incluido';
  };

  const handleSelect = (i) => {
    setSelections(Object.assign({}, selections, { [step]: i }));
  };

  const handleNext = () => {
    if (step < questions.length - 1) {
      setStep(step + 1);
    } else {
      const price = calcPrice(questions, selections);
      const summary = questions.map((q, i) => {
        const oi = selections[i];
        return oi !== undefined ? q.options[oi].label : null;
      }).filter(Boolean).join(' · ');
      onComplete({ summary, minPrice: price.min, maxPrice: price.max });
      setDone(true);
    }
  };

  const handleReset = () => {
    setStep(0);
    setSelections({});
    setDone(false);
  };

  return React.createElement('div', { className: 'quoter' },
    React.createElement('div', { className: 'quoter-tabs' },
      React.createElement('button', {
        className: 'quoter-tab' + (activeTab === 'web' ? ' on' : ''),
        onClick: () => { setActiveTab('web'); setStep(0); setSelections({}); setDone(false); }
      }, 'Página Web'),
      React.createElement('button', {
        className: 'quoter-tab' + (activeTab === 'n8n' ? ' on' : ''),
        onClick: () => { setActiveTab('n8n'); setStep(0); setSelections({}); setDone(false); }
      }, 'Flujo IA n8n')
    ),

    !done ? React.createElement(React.Fragment, null,
      React.createElement('div', { className: 'quoter-progress' },
        Array.from({ length: questions.length }).map((_, i) =>
          React.createElement('div', {
            key: i,
            className: 'q-dot' + (i < step ? ' done' : i === step ? ' on' : '')
          })
        ),
        React.createElement('span', { style: { fontSize: '12px', color: 'var(--ink-3)', marginLeft: '12px' } },
          'Paso ' + (step + 1) + ' de ' + questions.length
        )
      ),

      React.createElement('div', { className: 'quoter-question' }, currentQ.q),

      React.createElement('div', { className: 'quoter-options' },
        currentQ.options.map((opt, i) =>
          React.createElement('button', {
            key: i,
            className: 'q-option' + (selectedIdx === i ? ' on' : ''),
            onClick: () => handleSelect(i)
          },
            React.createElement('div', { className: 'q-option-label' }, opt.label),
            React.createElement('div', {
              className: 'q-option-price',
              style: (!opt.multiplier && opt.price === 0) ? { color: 'var(--ink-4)', fontWeight: '400' } : {}
            }, getOptionTag(opt))
          )
        )
      ),

      hasPrice && React.createElement('div', { className: 'quoter-liveprice' },
        React.createElement('div', { style: { fontSize: '11px', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' } }, 'Acumulado hasta aquí'),
        React.createElement('div', { className: 'quoter-liveprice-val' },
          '$' + livePrice.total.toLocaleString() + ' USD'
        )
      ),

      React.createElement('div', { className: 'quoter-controls' },
        React.createElement('button', {
          className: 'quoter-btn',
          onClick: () => setStep(s => s - 1),
          disabled: step === 0,
          style: { opacity: step === 0 ? 0.35 : 1 }
        }, '← Anterior'),
        React.createElement('button', {
          className: 'quoter-btn quoter-btn-primary',
          onClick: handleNext,
          disabled: selectedIdx === -1
        }, step === questions.length - 1 ? 'Ver mi precio →' : 'Siguiente →')
      )
    ) :
    React.createElement('div', { className: 'quoter-result' },
      React.createElement('div', { style: { fontSize: '11px', color: 'var(--brand-cyan)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: '700', marginBottom: '10px' } }, '✓ Tu estimación base'),
      React.createElement('div', { className: 'quoter-result-price' },
        '$' + livePrice.min.toLocaleString() + ' – $' + livePrice.max.toLocaleString() + ' USD'
      ),
      React.createElement('div', { className: 'quoter-disclaimer' },
        '* Precio base estimado. El costo real se define en el diagnóstico de tu proyecto.'
      ),
      React.createElement('div', { style: { display: 'flex', gap: '12px', marginTop: '20px', flexWrap: 'wrap' } },
        React.createElement('button', {
          className: 'btn btn-primary',
          style: { flex: 1, minWidth: '180px', padding: '12px 20px', fontSize: '14px' },
          onClick: () => { onRequestForm && onRequestForm(); }
        }, 'Solicitar diagnóstico gratuito →'),
        React.createElement('button', {
          style: { background: 'none', border: '1px solid var(--ink-5)', borderRadius: '8px', color: 'var(--ink-3)', padding: '10px 16px', cursor: 'pointer', fontSize: '13px', whiteSpace: 'nowrap' },
          onClick: handleReset
        }, 'Recalcular')
      )
    )
  );
};

/* ---------- CTA ---------- */
const SectionCTA = ({ t }) => {
  const [mainTab, setMainTab] = React.useState('quoter');
  const [form, setForm] = React.useState({ nombre:'', empresa:'', email:'', cargo:'', telefono:'', mensaje:'' });
  const [honeypot, setHoneypot] = React.useState('');
  const [captcha, setCaptcha] = React.useState({ question:'', answer:0 });
  const [captchaInput, setCaptchaInput] = React.useState('');
  const [status, setStatus] = React.useState('idle');
  const [errors, setErrors] = React.useState({});
  const [touched, setTouched] = React.useState({});
  const [attempts, setAttempts] = React.useState(0);
  const [focusField, setFocusField] = React.useState(null);
  const startTime = React.useRef(Date.now());

  React.useEffect(() => {
    const a = Math.floor(Math.random() * 15) + 1;
    const b = Math.floor(Math.random() * 10) + 1;
    const ops = [
      { q: a + ' + ' + b + ' = ?', ans: a + b },
      { q: (a + b) + ' - ' + b + ' = ?', ans: a },
      { q: a + ' x ' + b + ' = ?', ans: a * b }
    ];
    const op = ops[Math.floor(Math.random() * ops.length)];
    setCaptcha({ question: op.q, answer: op.ans });
  }, []);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setForm(Object.assign({}, form, { [name]: value }));
  };

  const handleBlur = (e) => {
    const { name } = e.target;
    setTouched(Object.assign({}, touched, { [name]: true }));
  };

  const validateField = (name, value) => {
    if (!value && ['nombre', 'empresa', 'email', 'mensaje'].includes(name)) return 'Campo requerido';
    if (name === 'email' && value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return 'Email invalido';
    return '';
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (honeypot) return;
    if (Date.now() - startTime.current < 3000) {
      setStatus('error');
      setErrors({ form: 'Espera un poco...' });
      return;
    }
    if (attempts >= 5) {
      setStatus('error');
      setErrors({ form: 'Demasiados intentos.' });
      return;
    }
    if (parseInt(captchaInput) !== captcha.answer) {
      setErrors({ captcha: 'Respuesta incorrecta' });
      return;
    }
    const newErrors = {};
    ['nombre', 'empresa', 'email', 'mensaje'].forEach(f => {
      const err = validateField(f, form[f]);
      if (err) newErrors[f] = err;
    });
    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }
    setStatus('loading');
    setAttempts(attempts + 1);
    try {
      const res = await fetch('https://hook.us1.make.com/ywmulespifg9mnokrz80tqxb3559c0rv', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(Object.assign({}, form, { fuente: 'Landing Apiqo', timestamp: new Date().toISOString() }))
      });
      if (!res.ok) throw new Error('Error');
      setStatus('success');
      setForm({ nombre:'', empresa:'', email:'', cargo:'', telefono:'', mensaje:'' });
      setCaptchaInput('');
      setTouched({});
      window.trackEvent('Lead', { content_name: 'solicitar_diagnostico_cta' });
    } catch {
      setStatus('error');
      setErrors({ form: 'Error al enviar. Intenta de nuevo.' });
    }
  };

  const renderField = (name, label, type, required) => {
    const value = form[name];
    const error = touched[name] ? validateField(name, value) : '';
    const isActive = focusField === name || value;
    const isMultiline = name === 'mensaje';

    return React.createElement('div', { key: name, style: { marginBottom: '20px', position: 'relative' } },
      React.createElement('label', { style: { display: 'block', fontSize: '13px', fontWeight: '500', color: 'rgba(255,255,255,0.65)', marginBottom: '8px', textTransform: 'capitalize' } },
        label + (required ? ' *' : '')
      ),
      React.createElement(isMultiline ? 'textarea' : 'input', {
        type: type || 'text',
        name: name,
        value: value,
        onChange: handleChange,
        onFocus: () => setFocusField(name),
        onBlur: handleBlur,
        required: required,
        placeholder: 'Escribe aquí...',
        style: {
          width: '100%',
          padding: isMultiline ? '14px 16px' : '13px 16px',
          border: '1.5px solid ' + (error ? '#ef4444' : isActive ? 'var(--brand-cyan)' : 'var(--ink-5)'),
          background: isActive ? 'rgba(84, 175, 188, 0.03)' : 'var(--ink-8)',
          borderRadius: '8px',
          color: '#fff',
          fontSize: '14px',
          transition: 'all 0.2s ease',
          outline: 'none',
          boxShadow: isActive ? '0 0 0 3px rgba(84, 175, 188, 0.08)' : 'none',
          fontFamily: 'var(--font-body)',
          minHeight: isMultiline ? '120px' : 'auto',
          resize: isMultiline ? 'vertical' : 'none'
        }
      }),
      error ? React.createElement('div', { style: { color: '#ef4444', fontSize: '12px', marginTop: '6px', fontWeight: '500' } }, '✕ ' + error) : null
    );
  };

  const filledFields = Object.values(form).filter(v => v).length;
  const totalFields = 6;
  const progress = Math.round((filledFields / totalFields) * 100);

  const handleQuoteComplete = ({ summary, minPrice, maxPrice }) => {
    const formattedPrice = '$' + minPrice.toLocaleString() + ' - $' + maxPrice.toLocaleString() + ' USD';
    const msgContent = 'Cotización estimada: ' + formattedPrice + '\n\n' + summary + '\n\nMe gustaría agendar un diagnóstico para afinar el alcance.';
    setForm(Object.assign({}, form, { mensaje: msgContent }));
  };

  return React.createElement('section', { id: 'contact', className: 'sec-cta' },
    React.createElement('div', { className: 'container' },
      React.createElement('div', { className: 'cta-card' },
        React.createElement('div', { className: 'cta-grid-bg' }),
        React.createElement('div', { className: 'cta-content' },
          React.createElement('div', { className: 'eyebrow', style: { color: 'var(--brand-cyan)' } }, t.cta.eyebrow),
          React.createElement('h2', { className: 'display cta-h2' }, t.cta.h2),
          React.createElement('p', { className: 'cta-p' }, t.cta.p),
          React.createElement('div', { className: 'cta-main-tabs' },
            React.createElement('button', {
              className: 'cta-main-tab' + (mainTab === 'quoter' ? ' on' : ''),
              onClick: () => setMainTab('quoter')
            }, '💰 Cotizador rápido'),
            React.createElement('button', {
              className: 'cta-main-tab' + (mainTab === 'form' ? ' on' : ''),
              onClick: () => setMainTab('form')
            }, '✍️ Tengo otra necesidad')
          ),
          React.createElement('div', { style: { display: mainTab === 'quoter' ? 'block' : 'none' } },
            React.createElement(QuoterWidget, {
              onComplete: handleQuoteComplete,
              onRequestForm: () => {
                setMainTab('form');
                setTimeout(() => document.getElementById('form-anchor') && document.getElementById('form-anchor').scrollIntoView({ behavior: 'smooth' }), 150);
              }
            })
          ),
          React.createElement('div', { id: 'form-anchor', style: { display: mainTab === 'form' ? 'block' : 'none' } },
            status === 'success' ?
              React.createElement('div', { style: { padding: '24px', background: 'linear-gradient(135deg, rgba(10, 79, 47, 0.2), rgba(74, 222, 128, 0.1))', borderRadius: '8px', border: '1px solid #22c55e', color: '#4ade80', textAlign: 'center' } },
                React.createElement('div', { style: { fontSize: '20px', marginBottom: '8px' } }, '✓'),
                React.createElement('div', { style: { fontSize: '16px', fontWeight: '600' } }, 'Solicitud enviada'),
                React.createElement('div', { style: { fontSize: '14px', marginTop: '8px', opacity: 0.8 } }, 'Te contactaremos en breve para agendar tu diagnostico.')
              )
            :
              React.createElement('form', { className: 'cta-form', onSubmit: handleSubmit },
              React.createElement('div', { style: { marginBottom: '20px' } },
                React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', marginBottom: '8px', fontSize: '12px', color: '#666' } },
                  React.createElement('span', {}, 'Progreso'),
                  React.createElement('span', {}, progress + '%')
                ),
                React.createElement('div', { style: { height: '4px', background: '#333', borderRadius: '2px', overflow: 'hidden' } },
                  React.createElement('div', { style: { height: '100%', background: 'linear-gradient(90deg, var(--brand-cyan), var(--brand-magenta))', width: progress + '%', transition: 'width 0.3s ease' } })
                )
              ),
              renderField('nombre', 'Nombre', 'text', true),
              renderField('empresa', 'Empresa', 'text', true),
              renderField('email', 'Email', 'email', true),
              renderField('cargo', 'Cargo / Rol', 'text', false),
              renderField('telefono', 'Telefono', 'tel', false),
              renderField('mensaje', 'Que necesitas?', 'textarea', true),
              React.createElement('div', { style: { padding: '18px', background: 'linear-gradient(135deg, rgba(84, 175, 188, 0.05), rgba(205, 50, 102, 0.03))', borderRadius: '8px', border: '1.5px solid var(--ink-5)', marginBottom: '20px' } },
                React.createElement('div', { style: { fontSize: '12px', color: 'var(--ink-3)', marginBottom: '10px', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: '600' } }, '🔒 Verifica que eres humano'),
                React.createElement('div', { style: { display: 'flex', gap: '12px', alignItems: 'flex-end' } },
                  React.createElement('div', { style: { flex: 1 } },
                    React.createElement('div', { style: { fontSize: '16px', fontWeight: '700', color: 'var(--brand-cyan)', marginBottom: '8px', fontFamily: 'var(--font-display)' } }, captcha.question),
                    React.createElement('input', {
                      type: 'number',
                      value: captchaInput,
                      onChange: (e) => setCaptchaInput(e.target.value),
                      placeholder: 'Tu respuesta',
                      style: {
                        width: '100%',
                        padding: '11px 14px',
                        border: '1.5px solid ' + (errors.captcha ? '#ef4444' : 'var(--ink-5)'),
                        background: 'var(--ink-8)',
                        borderRadius: '6px',
                        color: '#fff',
                        fontSize: '14px',
                        outline: 'none',
                        transition: 'all 0.2s ease'
                      }
                    })
                  )
                ),
                errors.captcha ? React.createElement('div', { style: { color: '#ef4444', fontSize: '12px', marginTop: '8px', fontWeight: '500' } }, '✕ ' + errors.captcha) : null
              ),
              React.createElement('input', { type: 'text', name: 'honeypot', value: honeypot, onChange: (e) => setHoneypot(e.target.value), style: { display: 'none' } }),
              errors.form ? React.createElement('div', { style: { color: '#ef4444', fontSize: '13px', marginBottom: '16px', padding: '12px 14px', background: 'rgba(239, 68, 68, 0.08)', borderRadius: '6px', border: '1.5px solid rgba(239, 68, 68, 0.3)', fontWeight: '500' } }, '⚠ ' + errors.form) : null,
              React.createElement('button', { type: 'submit', disabled: status === 'loading', style: { width: '100%', padding: '13px 20px', marginTop: '8px', background: 'linear-gradient(135deg, var(--brand-cyan), var(--brand-magenta))', color: '#000', border: 'none', borderRadius: '8px', fontSize: '14px', fontWeight: '600', cursor: status === 'loading' ? 'not-allowed' : 'pointer', transition: 'all 0.2s ease', opacity: status === 'loading' ? 0.7 : 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px' } },
                React.createElement('span', {}, status === 'loading' ? '⏳ Enviando...' : t.cta.btn),
                status !== 'loading' && React.createElement('svg', { width: '14', height: '14', viewBox: '0 0 14 14', fill: 'none' },
                  React.createElement('path', { d: 'M3 7h8m0 0L7.5 3.5M11 7l-3.5 3.5', stroke: 'currentColor', strokeWidth: '1.5', strokeLinecap: 'round', strokeLinejoin: 'round' })
                )
              )
              )
            )
          )
        )
      )
  );
};

/* ---------- Footer ---------- */
const Footer = ({ t }) => (
  <footer className="footer">
    <div className="container footer-inner">
      <div className="footer-brand">
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <ApiqoMark size={28} />
          <span className="display" style={{ fontSize: 22, fontWeight: 900 }}>APIQO</span>
        </div>
        <p className="footer-tag">{t.footer.tagline}</p>
      </div>
      <div className="footer-cols">
        <div>
          <div className="mono footer-h">{t.footer.cols.product}</div>
          {t.footer.product.map(x => <a key={x}>{x}</a>)}
        </div>
        <div>
          <div className="mono footer-h">{t.footer.cols.company}</div>
          {t.footer.company.map(x => <a key={x}>{x}</a>)}
        </div>
        <div>
          <div className="mono footer-h">{t.footer.cols.legal}</div>
          {t.footer.legal.map(x => <a key={x}>{x}</a>)}
        </div>
      </div>
    </div>
    <div className="container footer-foot">
      <span className="mono">{t.footer.copy}</span>
      <span className="mono" style={{ color: 'var(--ink-4)' }}>v3.0 · 2026</span>
    </div>
  </footer>
);

window.SectionFleet = SectionFleet;
window.SectionStack = SectionStack;
window.SectionROI = SectionROI;
window.SectionProcess = SectionProcess;
window.SectionFAQ = SectionFAQ;
window.QuoterWidget = QuoterWidget;
window.SectionCTA = SectionCTA;
window.Footer = Footer;
