// ---- Mabel landing — keyboard-first beta signup form ----
// One source of truth, driven by `force` so the frames canvas can show
// each state. Live (force=null) it's fully keyboard-operable:
//  · logical Tab order through fields + disclosure
//  · Enter submits from any field
//  · disclosure toggles by keyboard, reveals 2nd field with height transition
const { useState, useRef, useEffect } = React;

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

// Web3Forms access key. Get one free at https://web3forms.com (tie it to jelgie@gmail.com).
// This key is intended to live in client-side code and is safe to expose publicly;
// spam is filtered on Web3Forms' side. Submissions are emailed to that address.
const WEB3FORMS_ACCESS_KEY = '105d7983-320b-45a2-a0d0-cb7d5c12a05f';

function SignupForm({ force = null }) {
  // force: 'default' | 'focus' | 'expanded' | 'error' | 'submitting' | 'success' | null(live)
  const [name, setName] = useState(force ? 'Sam Ortiz' : '');
  const [email, setEmail] = useState(
    force === 'error' ? 'sam@oops' : force && force !== 'default' && force !== 'focus' ? 'sam@ortiz.co' : ''
  );
  const [relOpen, setRelOpen] = useState(force === 'expanded' || force === 'error');
  const [relEmail, setRelEmail] = useState(force === 'error' ? 'mom@' : force === 'expanded' ? '' : '');
  const [status, setStatus] = useState(
    force === 'submitting' ? 'submitting' : force === 'success' ? 'success' : 'idle'
  );
  const [err, setErr] = useState(force === 'error' ? { email: true } : {});
  const [bot, setBot] = useState(''); // honeypot
  const nameRef = useRef(null);

  // demo focus for the "focus" frame
  useEffect(() => {
    if (force === 'focus' && nameRef.current) nameRef.current.focus();
  }, [force]);

  const validate = () => {
    const e = {};
    if (!name.trim()) e.name = true;
    if (!EMAIL_RE.test(email)) e.email = true;
    if (relOpen && relEmail.trim() && !EMAIL_RE.test(relEmail)) e.rel = true;
    return e;
  };

  const submit = async (ev) => {
    ev && ev.preventDefault();
    if (force) return; // frozen in canvas frames
    const e = validate();
    setErr(e);
    if (Object.keys(e).length) return;
    setStatus('submitting');
    try {
      const res = await fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          access_key: WEB3FORMS_ACCESS_KEY,
          subject: 'New Mabel beta signup',
          from_name: 'Mabel Landing',
          name: name,
          email: email,
          relative_email: relOpen ? relEmail : '',
          botcheck: bot, // honeypot — real users leave this empty
        }),
      });
      const data = await res.json();
      if (data && data.success) {
        setStatus('success');
      } else {
        setStatus('idle');
        setErr({ submit: true });
      }
    } catch (_) {
      setStatus('idle');
      setErr({ submit: true });
    }
  };

  if (status === 'success') {
    return (
      <div className="form-card">
        <div className="success">
          <div className="smark"><Icon name="check" /></div>
          <h3>You're on the list.</h3>
          <p>I'll be in touch soon — thank you. Or just like the post and I'll follow up there.</p>
        </div>
      </div>
    );
  }

  const submitting = status === 'submitting';

  return (
    <div className="form-card">
      <form onSubmit={submit} noValidate>
        {/* honeypot: hidden from humans, bots tend to fill it */}
        <input type="text" name="botcheck" tabIndex={-1} autoComplete="off"
          value={bot} onChange={(e) => setBot(e.target.value)}
          style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }}
          aria-hidden="true" />
        <div className="field">
          <label htmlFor="f-name">Name</label>
          <div className={`input ${force === 'focus' ? 'focus-demo' : ''}`} style={force === 'focus' ? { borderColor: 'var(--color-accent-strong)', boxShadow: '0 0 0 3px var(--ring)' } : undefined}>
            <Icon name="user" />
            <input id="f-name" ref={nameRef} type="text" placeholder="Your name" autoComplete="name"
              value={name} onChange={(e) => setName(e.target.value)} disabled={submitting} />
          </div>
        </div>

        <div className="field">
          <label htmlFor="f-email">Your email</label>
          <div className={`input ${err.email ? 'error' : ''}`}>
            <Icon name="mail" />
            <input id="f-email" type="email" inputMode="email" placeholder="you@gmail.com" autoComplete="email"
              value={email} onChange={(e) => setEmail(e.target.value)} disabled={submitting} />
          </div>
          {err.email && <span className="err-msg"><Icon name="alert-circle" />That doesn't look like an email address.</span>}
        </div>

        <label className="disclosure-row">
          <input type="checkbox" checked={relOpen} disabled={submitting}
            onChange={(e) => setRelOpen(e.target.checked)} />
          <span className={`ck ${relOpen ? 'on' : ''}`}><Icon name="check" /></span>
          <span className="dr-tx">I'd also like to use Mabel for a relative's inbox.
            <span className="dr-hint">This is exactly what started Mabel — helping my mom with hers.</span>
          </span>
        </label>

        <div className={`reveal ${relOpen ? 'open' : ''}`}>
          <div className="reveal-in">
            <div className="field">
              <label htmlFor="f-rel">A relative's email <span className="opt">(optional)</span></label>
              <div className={`input ${err.rel ? 'error' : ''}`}>
                <Icon name="mail" />
                <input id="f-rel" type="email" inputMode="email" placeholder="their@email.com"
                  value={relEmail} onChange={(e) => setRelEmail(e.target.value)} disabled={submitting}
                  tabIndex={relOpen ? 0 : -1} />
              </div>
              {err.rel && <span className="err-msg"><Icon name="alert-circle" />That doesn't look like an email address.</span>}
            </div>
          </div>
        </div>

        <div className="submit-block">
          <button type="submit" className="btn primary lg full" disabled={submitting}>
            {submitting ? <><span className="spin" />Counting you in…</> : <>Count me in <span className="kbd">⏎</span></>}
          </button>
          {err.submit && <span className="err-msg"><Icon name="alert-circle" />Something went wrong sending that. Please try again in a moment.</span>}
          <p className="privacy-line"><Icon name="lock" />Stored securely. Only Jamie sees this, and it's used only to contact you about the beta.</p>
        </div>
      </form>
    </div>
  );
}

function SignupSection({ formRef }) {
  return (
    <section className="signup" id="join" data-screen-label="Beta signup" ref={formRef}>
      <div className="wrap">
        <div className="inner">
          <div className="section-head">
            <div className="eyebrow">Join the beta</div>
            <h2 className="h-section">Want to help me test it?</h2>
            <p className="sub">I know there are other tools out there. I think I can do it better — I'd love for you to tell me if I'm right.</p>
          </div>
          <SignupForm />
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { SignupForm, SignupSection });
