// landing-form.jsx — waitlist form with empty / focus / loading / success / error states.

// ─────────────────────────────────────────────────────────────────────────
// Para conectar la lista de espera de verdad, pon aquí la URL de tu endpoint
// (Formspree, Mailchimp, un backend propio…). Si se deja vacío, el formulario
// solo simula el envío. El email se manda como POST JSON { email, source }.
// Ejemplos:  'https://formspree.io/f/xxxxxxx'  ·  'https://api.poteapp.com/waitlist'
const WAITLIST_ENDPOINT = '';
// ─────────────────────────────────────────────────────────────────────────

function WaitlistForm({ tone = 'light', idp = 'f' }) {
  const { t } = useT();
  const tf = t.form;
  const [email, setEmail] = React.useState('');
  const [status, setStatus] = React.useState('idle'); // idle | loading | success | error
  const [focused, setFocused] = React.useState(false);
  const valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());

  const submit = (e) => {
    e.preventDefault();
    if (status === 'loading' || status === 'success') return;
    if (!valid) { setStatus('error'); return; }
    setStatus('loading');
    if (!WAITLIST_ENDPOINT) {
      // sin backend configurado → demo
      setTimeout(() => setStatus('success'), 1300);
      return;
    }
    fetch(WAITLIST_ENDPOINT, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
      body: JSON.stringify({ email: email.trim(), source: idp }),
    })
      .then((r) => { if (!r.ok) throw new Error('bad response'); setStatus('success'); })
      .catch(() => setStatus('error'));
  };

  const dark = tone === 'dark';
  const fieldText = dark ? C.white : C.black;
  const fieldBg = dark ? 'rgba(255,255,255,0.08)' : C.white;
  const helperCol = dark ? 'rgba(255,255,255,0.6)' : C.textMuted;
  const errBorder = '#E5484D';
  const isError = status === 'error';

  if (status === 'success') {
    return (
      <div role="status" style={{
        display: 'flex', alignItems: 'center', gap: 14, padding: '16px 18px', borderRadius: 20,
        background: dark ? 'rgba(255,255,255,0.1)' : C.white,
        boxShadow: dark ? 'inset 0 0 0 1.5px rgba(255,255,255,0.18)' : '0 0 0 1.5px rgba(5,5,5,0.07), 0 12px 30px -14px rgba(5,5,5,0.25)',
        maxWidth: 560,
      }}>
        <span style={{ width: 42, height: 42, borderRadius: 21, background: C.lime, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, boxShadow: '0 3px 0 #7C9300' }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={C.black} strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12l5 5 9-11"/></svg>
        </span>
        <div>
          <div style={{ fontSize: 16, fontWeight: 800, letterSpacing: '-0.3px', color: fieldText }}>{tf.successT}</div>
          <div style={{ fontSize: 13, fontWeight: 600, color: helperCol, marginTop: 2 }}>{tf.successD}</div>
        </div>
      </div>
    );
  }

  const loading = status === 'loading';
  return (
    <form onSubmit={submit} noValidate style={{ maxWidth: 560, width: '100%' }}>
      <div className="wl-pill" style={{
        display: 'flex', gap: 8, alignItems: 'stretch', padding: 7,
        borderRadius: 999, background: fieldBg,
        boxShadow: isError
          ? `inset 0 0 0 2px ${errBorder}`
          : focused
            ? `inset 0 0 0 2px ${dark ? C.lime : C.black}`
            : (dark ? 'inset 0 0 0 1.5px rgba(255,255,255,0.16)' : '0 0 0 1.5px rgba(5,5,5,0.09), 0 10px 28px -16px rgba(5,5,5,0.3)'),
        transition: 'box-shadow 0.18s ease',
        flexWrap: 'wrap',
      }}>
        <input
          type="email" inputMode="email" placeholder={tf.placeholder}
          aria-label="Email"
          value={email}
          onChange={(e) => { setEmail(e.target.value); if (isError) setStatus('idle'); }}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          disabled={loading}
          className="wl-input"
          style={{
            flex: '1 1 220px', minWidth: 0, border: 'none', outline: 'none', background: 'transparent',
            padding: '0 16px 0 22px', fontSize: 17, fontWeight: 600, color: fieldText,
            fontFamily: 'inherit', height: 56,
          }}
        />
        <button type="submit" disabled={loading} className="wl-btn" style={{
          flex: '0 0 auto', height: 56, padding: '0 30px', borderRadius: 999, border: 'none',
          background: C.lime, color: C.black, fontSize: 15, fontWeight: 900, letterSpacing: '-0.2px',
          fontFamily: 'inherit', cursor: loading ? 'default' : 'pointer',
          boxShadow: '0 3px 0 #7C9300, inset 0 1px 0 rgba(255,255,255,0.4)',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8, whiteSpace: 'nowrap',
        }}>
          {loading && <span className="pote-spin" style={{ width: 16, height: 16, borderRadius: 8, border: '2.5px solid rgba(5,5,5,0.25)', borderTopColor: C.black, display: 'inline-block' }} />}
          {loading ? tf.loading : tf.cta}
        </button>
      </div>
      <div style={{ marginTop: 12, paddingLeft: 22, fontSize: 13, fontWeight: 600, color: isError ? errBorder : helperCol, display: 'flex', alignItems: 'center', gap: 7 }}>
        {isError && (
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke={errBorder} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 8v5M12 16.5v.01"/></svg>
        )}
        {isError ? tf.error : tf.helper}
      </div>
    </form>
  );
}

Object.assign(window, { WaitlistForm });
