// Auth modal — magic-link sign in / sign up.
//
// Two states:
//   1. Email entry → user types email, hits Send link.
//   2. Sent state  → "We've sent a link to {email}. Click it to come back here signed in."
//
// We also pick up the audience from the welcome modal if it ran first, so
// we can write it into user_profiles.metadata for downstream marketing.

const { useEffect: _ae, useState: _as, useRef: _ar } = React;

function AuthModal({ open, onClose, audience, onSignedIn }) {
  const [email, setEmail] = _as('');
  const [busy, setBusy] = _as(false);
  const [err, setErr] = _as('');
  const [sent, setSent] = _as(false);
  const [marketingOptIn, setMarketingOptIn] = _as(true);
  const inputRef = _ar(null);

  _ae(() => {
    if (open) {
      setEmail(''); setBusy(false); setErr(''); setSent(false);
      setTimeout(() => inputRef.current && inputRef.current.focus(), 80);
    }
  }, [open]);

  // When the user comes back signed in (after clicking the magic link),
  // close ourselves and let parent know.
  _ae(() => {
    if (!open || !window.MR || !window.MR.user) return;
    const unsub = window.MR.user.subscribe((state) => {
      if (state.isSignedIn) {
        if (typeof onSignedIn === 'function') onSignedIn(state);
        if (typeof onClose === 'function') onClose();
      }
    });
    return unsub;
  }, [open, onSignedIn, onClose]);

  if (!open) return null;

  const submit = async (e) => {
    e.preventDefault();
    if (!email.trim()) return;
    setErr('');
    setBusy(true);
    try {
      const res = await window.MR.user.signInWithMagicLink(email.trim(), {
        metadata: {
          audience: audience || null,
          marketing_opt_in: !!marketingOptIn,
        },
      });
      if (!res.ok) {
        const msg = res.error?.message || 'We couldn\'t send the link. Try again in a minute?';
        if (/rate limit/i.test(msg)) {
          setErr('Too many requests just now — wait 60 seconds and try again.');
        } else {
          setErr(msg);
        }
      } else {
        setSent(true);
      }
    } catch (e) {
      setErr(e.message || 'Network problem — try again?');
    } finally {
      setBusy(false);
    }
  };

  return (
    <>
      <div className="auth-scrim" onClick={onClose} />
      <div className="auth-modal" role="dialog" aria-modal="true" aria-label="Sign in to MagicRascals">
        <button
          type="button"
          className="auth-close"
          aria-label="Close"
          onClick={onClose}
        >
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M6 18L18 6"/></svg>
        </button>
        {!sent ? (
          <form onSubmit={submit} className="auth-form">
            <div className="auth-eyebrow">Welcome to MagicRascals</div>
            <h2 className="auth-h">
              Create your account or <em><Whimsy text="sign in" /></em>
            </h2>
            <p className="auth-sub">
              Save your lists, share registries with family, and pick up where you left off
              on any device. We use a magic link — no passwords to remember.
            </p>

            <label className="auth-field">
              <span className="auth-lbl">Email</span>
              <input
                ref={inputRef}
                type="email"
                inputMode="email"
                autoComplete="email"
                required
                className="auth-input"
                placeholder="you@email.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              />
            </label>

            <label className="auth-checkrow">
              <input
                type="checkbox"
                checked={marketingOptIn}
                onChange={(e) => setMarketingOptIn(e.target.checked)}
              />
              <span>Send me the occasional curated email — new picks, seasonal essentials, no spam.</span>
            </label>

            <button
              type="submit"
              className="btn"
              disabled={!email.trim() || busy}
              style={{ width: '100%', marginTop: 8 }}
            >
              <span className="btn-row">{busy ? 'Sending link…' : 'Send me a magic link'}</span>
              <span className="arrow">→</span>
            </button>

            {err && <div className="auth-err">{err}</div>}

            <p className="auth-tos">
              By creating an account you agree to receive transactional emails about your account.
              Marketing emails are opt-in and you can unsubscribe at any time.
            </p>
          </form>
        ) : (
          <div className="auth-sent">
            <div className="auth-sent-icon" aria-hidden="true">
              <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3" y="5" width="18" height="14" rx="2"/>
                <path d="M3 7 l9 7 l9 -7"/>
              </svg>
            </div>
            <h2 className="auth-h">Check your inbox</h2>
            <p className="auth-sub">
              We've sent a magic link to <strong>{email}</strong>. Open it on this device and you'll come back here signed in.
            </p>
            <p className="auth-tos">
              Didn't get it? Check spam, or <button type="button" className="auth-resend" onClick={() => setSent(false)}>try a different email</button>.
            </p>
          </div>
        )}
      </div>
    </>
  );
}

window.AuthModal = AuthModal;
