/* global React */
const { useState } = React;

/* ─────────────────────────────────────────────────────────────
   Waitlist signup → Loops.so

   SETUP (one-time): in your Loops account go to Forms → (your form) →
   Settings, copy the "Form Endpoint" URL, and paste it below. It looks
   like https://app.loops.so/api/newsletter-form/abc123… — this endpoint
   is public and safe to ship in the browser (no secret API key).
   The mailing list a signup lands in is configured on the Loops form
   itself, so we only need to send the email here.
   ───────────────────────────────────────────────────────────── */
const LOOPS_FORM_ENDPOINT = 'https://app.loops.so/api/newsletter-form/cmq8k9sbc023u0jw29b3rgyf0';

function Waitlist() {
  // status: 'idle' | 'submitting' | 'success' | 'error'
  const [status, setStatus] = useState('idle');
  const [error, setError] = useState('');

  const onSubmit = async (e) => {
    e.preventDefault();
    const email = new FormData(e.currentTarget).get('email');
    setStatus('submitting');
    setError('');
    try {
      const res = await fetch(LOOPS_FORM_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({ email, source: 'website-waitlist' }).toString(),
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data.success) {
        setStatus('success');
      } else if (res.status === 429) {
        setStatus('error');
        setError('Too many signups at once — give it a moment and try again.');
      } else {
        setStatus('error');
        setError(data.message || 'Something went wrong. Please try again.');
      }
    } catch (err) {
      setStatus('error');
      setError('Network error — check your connection and try again.');
    }
  };

  const submitting = status === 'submitting';

  return (
    <section className="sec sec-brick" id="waitlist">
      <div className="container-narrow" style={{ textAlign: 'center' }}>
        <div data-reveal style={{ marginBottom: 20 }}>
          <span className="eyebrow no-rule" style={{ justifyContent: 'center' }}>
            <span className="eyebrow-dot"/> Private beta · Launching late 2026
          </span>
        </div>
        <h2 data-reveal data-reveal-delay="1" className="display" style={{ fontSize: 'clamp(42px, 6.5vw, 88px)', marginBottom: 28, maxWidth: '18ch', marginLeft: 'auto', marginRight: 'auto' }}>
          Anticipation makes the <em>heart</em> grow fonder.
        </h2>
        <p data-reveal data-reveal-delay="2" className="subhead" style={{ margin: '0 auto 36px', textAlign: 'center' }}>
          Be the first to hear when the studio opens.
        </p>
        <form data-reveal data-reveal-delay="3" className="waitlist-form" style={{ marginLeft: 'auto', marginRight: 'auto' }} onSubmit={onSubmit}>
          {status !== 'success' ? (
            <>
              <input type="email" name="email" placeholder="you@email.com" required disabled={submitting}/>
              <button type="submit" className="btn btn-primary" disabled={submitting}>
                {submitting ? 'Signing up…' : 'Sign up'}
              </button>
            </>
          ) : (
            <div style={{
              flex: 1,
              padding: '14px 18px',
              borderRadius: 999,
              background: 'var(--success-soft)',
              color: '#1E6B3F',
              font: '500 14px/1 var(--font-sans)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            }}>
              ✓ You’re on the list. We’ll be in touch.
            </div>
          )}
        </form>
        {status === 'error' && (
          <p data-reveal role="alert" style={{
            marginTop: 14,
            font: '500 13px/1.5 var(--font-sans)',
            color: 'var(--spice-saffron)',
          }}>
            {error}
          </p>
        )}
        <p data-reveal data-reveal-delay="4" style={{
          marginTop: 20,
          font: '400 13px/1.5 var(--font-sans)',
          color: 'var(--ink-3)',
        }}>
          We don’t sell or share your contact info.
        </p>
      </div>
    </section>
  );
}

window.Waitlist = Waitlist;
