/* global React, Eyebrow, Icon, Button, SectionShell, GridBG */
/* ======================================================================
   SECCIÓN NEWSLETTER (landing)
   ----------------------------------------------------------------------
   Suscripción SOLO a la newsletter (sin Discord, sin agendar, sin recurso).
   Recoge nombre + correo + consentimiento y lo guarda en Supabase con la
   etiqueta `newsletter:landing` (tabla `leads`, columna newsletter=true), de
   modo que entra en los envíos "Todos" del panel y en la vista vw_newsletter.

   Depende de window.submitLead (leads.js) y del cliente Supabase
   (supabase-config.js + supabase-js). Si submitLead no estuviera disponible,
   nunca bloquea al usuario: igualmente muestra el éxito.
   ====================================================================== */

const { useState } = React;

const cdtNlInput = {
  background: 'var(--surface-2)', border: '1px solid var(--hairline)', borderRadius: 'var(--r-sm)',
  padding: '13px 14px', color: 'var(--fg-1)', fontFamily: 'var(--font-body)', fontSize: 15,
  outline: 'none', width: '100%', boxSizing: 'border-box', transition: 'all 150ms ease',
};

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

function NlField({ label, children }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      <span style={{ fontFamily: 'var(--font-head)', fontWeight: 600, fontSize: 12.5,
        letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--fg-2)' }}>{label}</span>
      {children}
    </label>
  );
}

function NlInput(props) {
  const [focus, setFocus] = useState(false);
  return (
    <input {...props} onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
      style={{ ...cdtNlInput, borderColor: focus ? 'var(--neon-magenta)' : 'var(--hairline)',
        boxShadow: focus ? 'var(--glow-magenta-sm)' : 'none' }} />
  );
}

// Tick grande de confirmación, con estética de marca (círculo cian + anillo que pulsa).
function NewsletterSuccess() {
  return (
    <div role="status" aria-live="polite" style={{ textAlign: 'center', padding: '14px 4px 6px', display: 'flex', flexDirection: 'column',
      alignItems: 'center', gap: 20, animation: 'cdtRise 360ms cubic-bezier(.2,.8,.2,1)' }}>
      <div style={{ position: 'relative', width: 104, height: 104, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {/* anillo que se expande en bucle */}
        <span aria-hidden style={{ position: 'absolute', inset: 0, borderRadius: '50%',
          border: '2px solid rgba(0,229,255,.55)', animation: 'cdtTickRing 1.8s ease-out infinite' }} />
        <div style={{ width: 96, height: 96, borderRadius: '50%', background: 'var(--cyan-soft)',
          border: '1px solid rgba(0,229,255,.45)', display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: 'var(--glow-cyan)', animation: 'cdtTickPop 460ms cubic-bezier(.2,.8,.2,1)' }}>
          <Icon name="check" size={52} color="var(--neon-cyan)" stroke={2.6} />
        </div>
      </div>
      <h3 style={{ fontFamily: 'var(--font-head)', fontWeight: 700, fontSize: 'clamp(22px,3vw,28px)',
        textTransform: 'uppercase', color: 'var(--fg-1)', margin: 0, lineHeight: 1.12 }}>
        ¡Ya estás suscrito!
      </h3>
      <p style={{ fontFamily: 'var(--font-body)', fontSize: 15.5, lineHeight: 1.6, color: 'var(--fg-2)', margin: 0, maxWidth: 380 }}>
        Ya formas parte. Pronto te llegará el primer mensaje: una idea para que te replantees algo. Atento a tu correo.
        <br /><span style={{ color: 'var(--fg-3)', fontSize: 13 }}>(Si no lo ves, revisa spam o promociones.)</span>
      </p>
    </div>
  );
}

function Newsletter() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [consent, setConsent] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  const [done, setDone] = useState(false);

  const submit = async (e) => {
    if (e) e.preventDefault();
    if (busy || done) return; // evita doble envío (Enter + clic) y leads duplicados
    setError('');
    if (!name.trim()) { setError('Pon tu nombre.'); return; }
    if (!EMAIL_RE.test(email.trim())) { setError('Pon un correo electrónico válido.'); return; }
    if (!consent) { setError('Marca la casilla para poder enviarte la newsletter.'); return; }

    setBusy(true);
    try {
      if (typeof window.submitLead === 'function') {
        await window.submitLead({
          slug: 'newsletter-landing',
          kind: 'newsletter',
          category: 'newsletter',
          tag: 'newsletter:landing',
          name: name.trim(),
          email: email.trim(),
          phone: null,
          newsletter: true,
          answers: {
            consentimiento: { q: 'Consentimiento de comunicaciones', a: 'Acepta apuntarse a la newsletter de la Cámara del Trader' },
            origen: { q: 'Origen de la suscripción', a: 'Landing — sección Newsletter' },
          },
        });
      }
    } catch (err) {
      // No bloqueamos al usuario: el respaldo local de leads.js ya cubre el fallo de red.
      console.warn('[CDT Newsletter] submitLead falló:', err);
    }
    setBusy(false);
    setDone(true);
  };

  return (
    <SectionShell id="newsletter" bg="var(--surface-2)">
      <GridBG opacity={0.05} style={{ maskImage: 'radial-gradient(circle at 50% 30%, #000 25%, transparent 80%)',
        WebkitMaskImage: 'radial-gradient(circle at 50% 30%, #000 25%, transparent 80%)' }} />

      <div style={{ maxWidth: 620, margin: '0 auto', textAlign: 'center', position: 'relative', zIndex: 1 }}>
        <Eyebrow style={{ display: 'inline-block' }}>Newsletter · Reflexión</Eyebrow>
        <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 'clamp(28px,3.6vw,46px)',
          lineHeight: 1.08, textTransform: 'uppercase', color: 'var(--fg-1)', margin: '16px 0 16px' }}>
          <span className="cdt-gradient-text">Mentalidad</span> antes<br />que mercado
        </h2>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 16.5, lineHeight: 1.65, color: 'var(--fg-2)',
          margin: '0 auto 30px', maxWidth: 500 }}>
          Es un mensaje personal que te llega cada cierto tiempo para que pares y te cuestiones: ¿estoy haciendo
          las cosas bien?, ¿es esta la mentalidad correcta? No solo en el trading, también en la vida. Más para
          pensar por ti mismo que para informarte.
        </p>

        <div style={{ background: 'var(--surface-3)', border: '1px solid var(--hairline)', borderRadius: 'var(--r-lg)',
          padding: 'clamp(24px,3.5vw,40px)', boxShadow: 'var(--shadow-card)', textAlign: 'left' }}>
          {done ? (
            <NewsletterSuccess />
          ) : (
            <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              <NlField label="Nombre">
                <NlInput type="text" value={name} onChange={(e) => setName(e.target.value)}
                  placeholder="Tu nombre" autoComplete="name" />
              </NlField>
              <NlField label="Correo electrónico">
                <NlInput type="email" value={email} onChange={(e) => setEmail(e.target.value)}
                  placeholder="tucorreo@gmail.com" autoComplete="email" />
              </NlField>

              <label style={{ display: 'flex', gap: 12, alignItems: 'flex-start', cursor: 'pointer',
                background: 'var(--surface-2)', border: `1px solid ${consent ? 'rgba(0,229,255,.4)' : 'var(--hairline)'}`,
                borderRadius: 'var(--r-sm)', padding: '14px 16px', transition: 'border-color 150ms ease' }}>
                <input type="checkbox" checked={consent} onChange={(e) => { setConsent(e.target.checked); setError(''); }}
                  style={{ marginTop: 2, accentColor: 'var(--neon-cyan)', width: 18, height: 18, flexShrink: 0 }} />
                <span style={{ fontFamily: 'var(--font-body)', fontSize: 13.5, lineHeight: 1.5, color: 'var(--fg-2)' }}>
                  Acepto y me apunto a la <strong style={{ color: 'var(--fg-1)', fontWeight: 600 }}>newsletter de la Cámara del Trader</strong>.
                </span>
              </label>

              {error && <p role="alert" style={{ color: 'var(--danger)', fontFamily: 'var(--font-body)', fontSize: 13.5, margin: 0 }}>{error}</p>}

              <Button type="submit" variant="primary" size="lg" icon="mail"
                style={{ width: '100%', justifyContent: 'center', opacity: busy ? 0.7 : 1, pointerEvents: busy ? 'none' : 'auto' }}>
                {busy ? 'Apuntando…' : 'Unirse a la newsletter'}
              </Button>
              <p style={{ fontFamily: 'var(--font-body)', fontSize: 11.5, lineHeight: 1.5, color: 'var(--fg-3)', margin: 0, textAlign: 'center' }}>
                Al suscribirte aceptas nuestra política de privacidad. Tus datos no se comparten con terceros.
              </p>
            </form>
          )}
        </div>
      </div>
    </SectionShell>
  );
}

window.Newsletter = Newsletter;
