// SubscribeForm.jsx — the conversion surface (wired to Buttondown via /api/subscribe)
function SubscribeForm({ variant = 'block' }) {
  const [email, setEmail] = React.useState('');
  const [hp, setHp] = React.useState('');           // honeypot — real users leave this empty
  const [state, setState] = React.useState('idle');  // idle | loading | done | error

  // Endpoint can be overridden globally (e.g. an absolute URL) via window.KD_SUBSCRIBE_ENDPOINT.
  const endpoint = (typeof window !== 'undefined' && window.KD_SUBSCRIBE_ENDPOINT) || '/api/subscribe';

  const t = {
    kicker:  'Subscribe — every other Sunday',
    heading: 'One issue. One quiet idea.',
    blurb:   "Drawn lines between things that don't usually sit next to each other. Around 7 minutes' read, twice a month.",
    cta:     'Subscribe',
    loading: 'Subscribing…',
    doneCta: 'Check inbox',
    doneMsg: 'One more step — check your inbox to confirm.',
    errMsg:  'Something went wrong. Please try again.',
    fine:    'No tracking. Unsubscribe in one click.',
    labelCase: { letterSpacing: '0.2em', textTransform: 'uppercase' },
    kickerCase: { letterSpacing: '0.22em', textTransform: 'uppercase' },
  };

  const submit = async (e) => {
    e.preventDefault();
    if (state === 'loading' || state === 'done') return;
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { setState('error'); return; }
    setState('loading');
    try {
      const res = await fetch(endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, website: hp }),
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok) { setState('done'); return; }
      // Show the backend error message if available
      setState('error');
      window.__subError = data;
    } catch (_) {
      setState('error');
    }
  };

  // Visually-hidden honeypot field
  const honeypot = (
    <input
      type="text" name="website" tabIndex={-1} autoComplete="off"
      value={hp} onChange={e => setHp(e.target.value)}
      aria-hidden="true"
      style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }}
    />
  );

  const busy = state === 'loading';
  const locked = busy || state === 'done';

  if (variant === 'inline') {
    return (
      <form onSubmit={submit} style={{ display: 'flex', gap: 8 }} noValidate>
        {honeypot}
        <input value={email} onChange={e => setEmail(e.target.value)} placeholder="you@somewhere.com"
          type="email" disabled={locked}
          style={{ flex: 1, fontFamily: 'var(--serif)', fontSize: 16, padding: '12px 14px', border: '1px solid var(--hairline)', background: 'var(--bone-card)', color: 'var(--ink)', borderRadius: 2, outline: 'none' }} />
        <button type="submit" disabled={locked} style={{
          fontFamily: 'var(--mono)', fontSize: 11, ...t.labelCase,
          padding: '12px 22px', background: 'var(--ink)', color: 'var(--bone)', border: 'none', borderRadius: 2, cursor: locked ? 'default' : 'pointer', opacity: busy ? 0.7 : 1,
        }}>{state === 'done' ? t.doneCta : busy ? t.loading : t.cta}</button>
      </form>
    );
  }

  return (
    <div style={{
      background: 'var(--bone-card)',
      border: '1px solid var(--hairline)',
      borderRadius: 4,
      padding: '40px',
      maxWidth: 560,
      margin: '0 auto',
    }}>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 11, ...t.kickerCase, color: 'var(--slate)' }}>
        {t.kicker}
      </div>
      <h3 style={{ fontFamily: 'var(--serif)', fontWeight: 400, fontSize: 30, letterSpacing: '-0.01em', color: 'var(--ink)', margin: '14px 0 8px 0', lineHeight: 1.2 }}>
        {t.heading}
      </h3>
      <p style={{ fontFamily: 'var(--serif)', fontSize: 16, lineHeight: 1.6, color: 'var(--slate)', margin: '0 0 24px 0' }}>
        {t.blurb}
      </p>
      {state === 'done' ? (
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '8px 0' }}>
          <Mark size="sm" />
          <div style={{ fontFamily: 'var(--serif)', fontSize: 17, color: 'var(--ink)' }}>
            {t.doneMsg}
          </div>
        </div>
      ) : (
        <form onSubmit={submit} style={{ display: 'flex', gap: 8 }} noValidate>
          {honeypot}
          <input value={email} onChange={e => setEmail(e.target.value)} placeholder="you@somewhere.com"
            type="email" disabled={busy}
            style={{ flex: 1, fontFamily: 'var(--serif)', fontSize: 16, padding: '12px 14px', border: '1px solid var(--hairline)', background: 'var(--bone)', color: 'var(--ink)', borderRadius: 2, outline: 'none' }}
            onFocus={e => e.target.style.borderColor = 'var(--ink)'}
            onBlur={e => e.target.style.borderColor = 'var(--hairline)'} />
          <button type="submit" disabled={busy} style={{
            fontFamily: 'var(--mono)', fontSize: 11, ...t.labelCase,
            padding: '12px 22px', background: 'var(--ink)', color: 'var(--bone)', border: 'none', borderRadius: 2, cursor: busy ? 'default' : 'pointer', opacity: busy ? 0.7 : 1,
          }}>{busy ? t.loading : t.cta}</button>
        </form>
      )}
      <div style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.04em', marginTop: 16, color: state === 'error' ? 'var(--blue)' : 'var(--slate)' }}>
        {state === 'error' ? t.errMsg : t.fine}
      </div>
    </div>
  );
}
window.SubscribeForm = SubscribeForm;
