// PÁGINA: Solicitar Diagnóstico Cognitivo
const DiagHero = () => (
  <section style={{ background: '#FFFFFF', paddingTop: 72, paddingBottom: 48, borderBottom: '1px solid #E4EBF3', position: 'relative', overflow: 'hidden' }}>
    <div style={{
      position: 'absolute', inset: 0,
      backgroundImage: 'linear-gradient(#E4EBF3 1px, transparent 1px), linear-gradient(90deg, #E4EBF3 1px, transparent 1px)',
      backgroundSize: '80px 80px', opacity: 0.4, pointerEvents: 'none',
      maskImage: 'radial-gradient(ellipse at 100% 0%, #000 0%, transparent 55%)',
      WebkitMaskImage: 'radial-gradient(ellipse at 100% 0%, #000 0%, transparent 55%)',
    }}/>
    <Container>
      <div style={{ position: 'relative', maxWidth: 900 }}>
        <Reveal><Eyebrow color="#F4024C">SOLICITAR DIAGNÓSTICO COGNITIVO</Eyebrow><Rule width={56}/></Reveal>
        <Reveal delay={80}>
          <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 72, lineHeight: 0.98, letterSpacing: '-0.03em', margin: '0 0 20px', color: '#000' }}>
            Empieza por la <span style={{ color: '#F4024C' }}>operación</span>. No por la demo.
          </h1>
        </Reveal>
        <Reveal delay={140}>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 19, lineHeight: 1.5, color: '#52557A', maxWidth: 640, margin: 0 }}>
            Comparte el proceso, decisión o restricción que quieres resolver. OMNIX evaluará si existe
            un caso viable para convertir datos, reglas y sistemas existentes en una capacidad cognitiva operable.
          </p>
        </Reveal>
      </div>
    </Container>
  </section>
);

const HCAPTCHA_SITEKEY = '50b2fe65-b00b-4b9e-ad62-3ba471098be2'; // site key público de Web3Forms (plan free)
const DiagForm = () => {
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState(null);
  const captchaRef = React.useRef(null);
  React.useEffect(() => {
    const renderCaptcha = () => {
      if (window.hcaptcha && captchaRef.current && captchaRef.current.dataset.rendered !== '1') {
        window.hcaptcha.render(captchaRef.current, { sitekey: HCAPTCHA_SITEKEY });
        captchaRef.current.dataset.rendered = '1';
      }
    };
    if (window.hcaptcha) { renderCaptcha(); return; }
    window.__omnixHcaptchaOnLoad = renderCaptcha;
    if (!document.getElementById('hcaptcha-api')) {
      const s = document.createElement('script');
      s.id = 'hcaptcha-api';
      s.src = 'https://js.hcaptcha.com/1/api.js?render=explicit&onload=__omnixHcaptchaOnLoad';
      s.async = true; s.defer = true;
      document.head.appendChild(s);
    }
  }, []);
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (sending) return;
    const captcha = e.target.querySelector('textarea[name="h-captcha-response"]');
    if (!captcha || !captcha.value) {
      setError('Por favor completa el captcha antes de enviar.');
      return;
    }
    setError(null);
    setSending(true);
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify(Object.fromEntries(new FormData(e.target))),
      });
      const data = await res.json();
      if (data.success) setSent(true);
      else setError(data.message || 'No se pudo enviar. Intenta de nuevo o escríbenos a contact@omnixcorp.com.');
    } catch (err) {
      setError('Error de conexión. Revisa tu red o escríbenos a contact@omnixcorp.com.');
    }
    setSending(false);
  };
  return (
    <section style={{ background: '#FAFBFD', paddingTop: 80, paddingBottom: 128, borderBottom: '1.5px solid #E4EBF3' }}>
      <Container>
        <div style={{ display: 'grid', gridTemplateColumns: '1.15fr 0.85fr', gap: 64, alignItems: 'start' }}>
          {/* Form */}
          <Reveal>
            <form onSubmit={handleSubmit} style={{
              background: '#FFF', border: '1.5px solid #1E1F26', padding: 40,
            }}>
              {sent ? (
                <div style={{ minHeight: 500, display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 20 }}>
                  <div style={{ width: 56, height: 56, border: '1.5px solid #F4024C', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#F4024C" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
                  </div>
                  <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 32, letterSpacing: '-0.02em', margin: 0, color: '#000' }}>
                    Recibido.
                  </h3>
                  <p style={{ fontFamily: 'var(--font-body)', fontSize: 16, color: '#52557A', margin: 0, lineHeight: 1.55, maxWidth: 480 }}>
                    Un experto en cognición operacional te contactará en menos de 24 horas hábiles con una propuesta
                    de agenda. Revisará tu contexto antes de la reunión.
                  </p>
                  <div style={{ marginTop: 12, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                    <Badge tone="outline">Sin propuesta pre-armada</Badge>
                    <Badge tone="outline">NDA disponible upfront</Badge>
                    <Badge tone="outline">Español / English</Badge>
                  </div>
                </div>
              ) : (
                <>
                  <input type="checkbox" name="botcheck" tabIndex={-1} autoComplete="off" style={{ display: 'none' }}/>
                  <div style={{ marginBottom: 24 }}>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em', color: '#F4024C', textTransform: 'uppercase', marginBottom: 8 }}>
                      Formulario · 4 min
                    </div>
                    <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 26, letterSpacing: '-0.015em', color: '#000', margin: 0 }}>
                      Cuéntanos qué está frenando tu operación.
                    </h3>
                  </div>

                  <FormField label="Nombre completo" required>
                    <input type="text" name="Nombre" required placeholder="Ej: Nombre Apellido" style={inputStyle}/>
                  </FormField>
                  <FormRow>
                    <FormField label="Cargo" required><input type="text" name="Cargo" required placeholder="Ej: COO / CIO" style={inputStyle}/></FormField>
                    <FormField label="Email corporativo" required><input type="email" name="Email" required placeholder="nombre@empresa.com" style={inputStyle}/></FormField>
                  </FormRow>
                  <FormField label="Empresa" required>
                    <input type="text" name="Empresa" required placeholder="Nombre legal" style={inputStyle}/>
                  </FormField>
                  <FormRow>
                    <FormField label="Industria" required>
                      <select name="Industria" required style={inputStyle} defaultValue="">
                        <option value="" disabled>Seleccionar</option>
                        {['Banca', 'Telecomunicaciones', 'Retail', 'Logística', 'Manufactura', 'Minería', 'Energía', 'Gobierno', 'Otra'].map(o => <option key={o}>{o}</option>)}
                      </select>
                    </FormField>
                    <FormField label="Tamaño" required>
                      <select name="Tamaño" required style={inputStyle} defaultValue="">
                        <option value="" disabled>Seleccionar</option>
                        {['< 500', '500 – 2.000', '2.000 – 10.000', '10.000 – 50.000', '> 50.000'].map(o => <option key={o}>{o} empleados</option>)}
                      </select>
                    </FormField>
                  </FormRow>
                  <FormField label="Timing esperado">
                    <select name="Timing esperado" style={inputStyle} defaultValue="">
                      <option value="" disabled>Seleccionar</option>
                      {['Ya, hay urgencia', 'Próximo trimestre', 'Este año', 'Explorando · sin fecha'].map(o => <option key={o}>{o}</option>)}
                    </select>
                  </FormField>
                  <FormField label="¿Qué proceso te está frenando hoy?" hint="Sé específico. Máximo 400 caracteres.">
                    <textarea name="Proceso que frena" maxLength={400} placeholder="Ej: cada disrupción en supply-chain nos cuesta 3 días de respuesta manual y coordinación entre 4 equipos..." style={{ ...inputStyle, minHeight: 100, resize: 'vertical', fontFamily: 'var(--font-body)' }}/>
                  </FormField>

                  <div ref={captchaRef} style={{ marginTop: 28 }}></div>
                  <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginTop: 20 }}>
                    <Button variant="primary" style={{ flex: 1, justifyContent: 'center', opacity: sending ? 0.7 : 1, pointerEvents: sending ? 'none' : 'auto' }}>
                      {sending ? 'Enviando…' : 'Evaluar un caso de uso'}
                    </Button>
                  </div>
                  {error && (
                    <div style={{ marginTop: 16, padding: '10px 14px', background: '#FFE5EC', border: '1px solid #F4024C', borderRadius: 2, fontFamily: 'var(--font-body)', fontSize: 13, color: '#B00238' }}>
                      {error}
                    </div>
                  )}
                  <div style={{ marginTop: 16, fontFamily: 'var(--font-mono)', fontSize: 10, color: '#96A3B5', letterSpacing: '0.04em', textAlign: 'center' }}>
                    Al enviar, aceptas nuestra política de privacidad. NDA disponible upfront si lo prefieres.
                  </div>
                </>
              )}
            </form>
          </Reveal>

          {/* Sidebar: qué pasa después */}
          <Reveal delay={120}>
            <div style={{ position: 'sticky', top: 100 }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em', color: '#F4024C', textTransform: 'uppercase', marginBottom: 24 }}>
                Qué pasa después
              </div>
              <ol style={{ listStyle: 'none', padding: 0, margin: '0 0 48px', display: 'flex', flexDirection: 'column', gap: 4 }}>
                {[
                  { n: '01', t: 'Contacto en < 24h',    d: 'Un socio de OMNIX (no un SDR) revisa tu contexto y responde con propuesta de agenda.' },
                  { n: '02', t: '30 minutos · sin slides', d: 'Conversación directa. Escuchamos primero. Preguntamos operación, decisiones críticas, sistemas.' },
                  { n: '03', t: 'Diagnóstico concreto',    d: 'Salimos con qué se puede automatizar, qué ROI esperar y en cuántas semanas puede correr. Sin propuesta de 40 páginas.' },
                ].map((s, i) => (
                  <li key={s.n} style={{
                    padding: '20px 0', borderBottom: '1px solid #E4EBF3',
                    display: 'grid', gridTemplateColumns: '48px 1fr', gap: 20,
                  }}>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.18em', color: '#F4024C', paddingTop: 4 }}>
                      {s.n}
                    </div>
                    <div>
                      <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 17, letterSpacing: '-0.01em', color: '#000', marginBottom: 6 }}>
                        {s.t}
                      </div>
                      <p style={{ fontFamily: 'var(--font-body)', fontSize: 14, lineHeight: 1.5, color: '#52557A', margin: 0 }}>
                        {s.d}
                      </p>
                    </div>
                  </li>
                ))}
              </ol>

              <div style={{ padding: 24, background: '#000', color: '#FFF', border: '1.5px solid #000' }}>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', color: '#96A3B5', marginBottom: 12 }}>
                  ALTERNATIVAS
                </div>
                <a href="mailto:contact@omnixcorp.com" style={{ display: 'flex', gap: 10, alignItems: 'center', color: '#FFF', textDecoration: 'none', marginBottom: 12, fontFamily: 'var(--font-body)', fontSize: 15 }}>
                  <i data-lucide="mail" width="16" height="16" style={{ strokeWidth: 1.5 }}/>
                  contact@omnixcorp.com
                </a>
                <a href="https://www.linkedin.com/company/omnixcorp/" target="_blank" rel="noopener noreferrer" style={{ display: 'flex', gap: 10, alignItems: 'center', color: '#FFF', textDecoration: 'none', fontFamily: 'var(--font-body)', fontSize: 15 }}>
                  <i data-lucide="linkedin" width="16" height="16" style={{ strokeWidth: 1.5 }}/>
                  LinkedIn · OMNIX
                </a>
              </div>

              <div style={{ marginTop: 24, fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.14em', color: '#96A3B5', textTransform: 'uppercase' }}>
                SOC 2 Type II · ISO 27001 · GDPR · LGPD
              </div>
            </div>
          </Reveal>
        </div>
      </Container>
    </section>
  );
};

// Form helpers
const inputStyle = {
  width: '100%', padding: '12px 14px', background: '#FFF', border: '1.5px solid #C7CFDA',
  borderRadius: 2, fontFamily: 'var(--font-body)', fontSize: 15, color: '#1E1F26',
  boxSizing: 'border-box', outline: 'none', transition: 'border-color 160ms',
};
const FormField = ({ label, required, hint, children }) => (
  <div style={{ marginBottom: 18 }}>
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
      <label style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: '#1E1F26', fontWeight: 500 }}>
        {label}{required && <span style={{ color: '#F4024C', marginLeft: 4 }}>*</span>}
      </label>
      {hint && <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: '#96A3B5', letterSpacing: '0.06em' }}>{hint}</span>}
    </div>
    {children}
  </div>
);
const FormRow = ({ children }) => (
  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>{children}</div>
);

Object.assign(window, { DiagHero, DiagForm });
