function Join() {
  const [email, setEmail] = React.useState('');
  const [location, setLocation] = React.useState('');
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);

  const locations = ['Ireland', 'UK', 'Somewhere else'];

  const onSubmit = async (e) => {
    e.preventDefault();
    if (!email || submitting) return;
    if (!location) { setError('Please select your location.'); return; }
    setSubmitting(true);
    setError(null);
    try {
      const res = await fetch('/api/waitlist', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, location }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.ok) {
        throw new Error(data.error || 'Something went wrong. Please try again.');
      }
      setSubmitted(true);
    } catch (err) {
      setError(err.message || 'Network error. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section id="join" className="section-pad" style={{ background: '#D9F1F1' }}>
      <style>{`
        .eivi-join-form { display: flex; flex-direction: column; gap: 12px; }
        .eivi-join-input-row { display: flex; gap: 10px; flex-direction: column; }
        @media (min-width: 600px) {
          .eivi-join-input-row { flex-direction: row; }
        }
        .eivi-location-radios { display: flex; gap: 24px; justify-content: center; flex-wrap: wrap; margin-bottom: 16px; }
        .eivi-location-label {
          display: flex; align-items: center; gap: 8px;
          font-size: var(--fs-body); font-weight: 500; color: #000; cursor: pointer;
        }
        .eivi-location-label input[type="radio"] {
          width: 20px; height: 20px; accent-color: var(--teal);
          cursor: pointer; flex-shrink: 0;
        }
      `}</style>
      <div style={{ maxWidth: 780, margin: '0 auto', textAlign: 'center' }}>
        <h2 className="t-h2" style={{ margin: 0, color: '#000' }}>Join the waitlist</h2>
        <p className="t-body" style={{
          color: '#000', marginTop: 'clamp(20px, 3vw, 32px)', marginBottom: 0,
          maxWidth: 580, marginLeft: 'auto', marginRight: 'auto',
        }}>
          Eivi is now accepting applications for the programme, to commence in 2026.
        </p>
        {submitted ? (
          <div style={{
            marginTop: 'clamp(36px, 5vw, 56px)',
            display: 'inline-flex', alignItems: 'center', gap: 12,
            padding: '18px 28px', borderRadius: 999, background: '#fff', color: '#0B6F8D',
            fontWeight: 500, fontSize: 20,
          }}>
            <span style={{ width: 10, height: 10, borderRadius: 999, background: '#1BBBBB', flexShrink: 0 }} />
            You're on the list. We'll be in touch from Cork.
          </div>
        ) : (
          <form
            onSubmit={onSubmit}
            className="eivi-join-form"
            style={{ marginTop: 'clamp(36px, 5vw, 56px)', maxWidth: 560, marginLeft: 'auto', marginRight: 'auto' }}
          >
            <div className="eivi-location-radios">
              {locations.map(l => (
                <label key={l} className="eivi-location-label">
                  <input
                    type="radio" name="location" value={l}
                    checked={location === l}
                    onChange={() => setLocation(l)}
                    required
                  />
                  {l}
                </label>
              ))}
            </div>
            <div className="eivi-join-input-row">
              <input
                type="email" required
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="you@example.com"
                disabled={submitting}
                style={{
                  flex: 1, padding: '18px 22px', borderRadius: 999,
                  border: '1px solid rgba(0,0,0,0.15)', background: '#fff',
                  color: '#000', fontSize: 'var(--fs-body)', fontFamily: 'inherit', outline: 'none', fontWeight: 500,
                  minWidth: 0,
                }} />
              <button
                type="submit"
                className="btn btn-primary btn-lg"
                disabled={submitting}
                style={{ cursor: submitting ? 'wait' : 'pointer', opacity: submitting ? 0.7 : 1 }}>
                {submitting ? 'Submitting…' : 'Apply'}
              </button>
            </div>
            {error && (
              <p style={{
                color: '#fff', fontSize: 'var(--fs-body)', fontWeight: 500,
                margin: '12px 0 0', padding: '10px 18px', borderRadius: 'var(--radius-md)',
                background: 'var(--red)',
              }}>
                {error}
              </p>
            )}
          </form>
        )}
      </div>
    </section>
  );
}
window.Join = Join;
