// ===== Header / Navigation =====
function Header({ route, navigate, onLogin }) {
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const [scrolled, setScrolled] = React.useState(false);

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener('scroll', onScroll);
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  React.useEffect(() => { setMobileOpen(false); }, [route]);

  return (
    <header className="site-header" style={{
      boxShadow: scrolled ? '0 2px 20px rgba(31,15,61,0.06)' : 'none',
    }}>
      <div className="container nav-row">
        <button onClick={() => navigate('home')} className="brand-btn" aria-label="Vision Generation home">
          <VGWordmark/>
        </button>

        <nav className="primary-nav" aria-label="Primary">
          {NAV_ITEMS.map(item => (
            <button
              key={item.id}
              onClick={() => navigate(item.id)}
              className={`nav-link ${route === item.id ? 'is-active' : ''}`}
            >
              {item.label}
            </button>
          ))}
        </nav>

        <div className="nav-actions">
          <button onClick={onLogin} className="login-btn" aria-label="Members login">
            <Icon name="lock" size={16}/>
            <span>Members</span>
          </button>
          <button
            onClick={() => navigate('visit')}
            className="btn btn-primary btn-sm visit-cta"
          >
            Plan Your Visit
          </button>

          <button
            className="hamburger"
            aria-label={mobileOpen ? 'Close menu' : 'Open menu'}
            onClick={() => setMobileOpen(v => !v)}
          >
            <Icon name={mobileOpen ? 'close' : 'menu'} size={24}/>
          </button>
        </div>
      </div>

      {/* Mobile drawer */}
      <div className={`mobile-drawer ${mobileOpen ? 'is-open' : ''}`}>
        <div className="mobile-drawer-inner">
          {NAV_ITEMS.map(item => (
            <button
              key={item.id}
              onClick={() => navigate(item.id)}
              className={`mobile-link ${route === item.id ? 'is-active' : ''}`}
            >
              <span>{item.label}</span>
              <Icon name="arrow" size={18}/>
            </button>
          ))}
          <div className="mobile-actions">
            <button onClick={() => { onLogin(); setMobileOpen(false); }} className="btn btn-outline" style={{flex:1, justifyContent:'center'}}>
              <Icon name="lock" size={16}/> Members Login
            </button>
            <button onClick={() => navigate('visit')} className="btn btn-primary" style={{flex:1, justifyContent:'center'}}>
              Plan Your Visit
            </button>
          </div>
        </div>
      </div>

      <style>{`
        .nav-row {
          display: flex;
          align-items: center;
          gap: 32px;
          height: 84px;
        }
        .brand-btn { padding: 0; flex-shrink: 0; }
        .primary-nav {
          display: flex;
          align-items: center;
          gap: 4px;
          margin-left: 8px;
          margin-right: auto;
        }
        .nav-link {
          padding: 10px 14px;
          border-radius: 999px;
          font-size: 14px;
          font-weight: 600;
          color: var(--vg-ink-soft);
          transition: color .2s ease, background .2s ease;
          position: relative;
          white-space: nowrap;
        }
        .nav-link:hover { color: var(--vg-purple-700); background: var(--vg-purple-50); }
        .nav-link.is-active {
          color: var(--vg-purple-700);
        }
        .nav-link.is-active::after {
          content: "";
          position: absolute;
          bottom: 4px;
          left: 50%;
          transform: translateX(-50%);
          width: 18px;
          height: 2px;
          background: var(--vg-gold-600);
          border-radius: 2px;
        }
        .nav-actions { display: flex; align-items: center; gap: 10px; }
        .login-btn {
          display: inline-flex;
          align-items: center;
          gap: 6px;
          padding: 8px 14px;
          border-radius: 999px;
          border: 1.5px solid var(--vg-line);
          background: #fff;
          font-size: 13px;
          font-weight: 700;
          color: var(--vg-purple-700);
          transition: all .2s ease;
        }
        .login-btn:hover {
          border-color: var(--vg-purple-700);
          background: var(--vg-purple-50);
        }
        .hamburger {
          display: none;
          padding: 10px;
          border-radius: 12px;
          color: var(--vg-purple-700);
        }
        .mobile-drawer {
          max-height: 0;
          overflow: hidden;
          transition: max-height .35s ease;
          background: var(--vg-cream);
          border-top: 1px solid var(--vg-line);
        }
        .mobile-drawer.is-open { max-height: 700px; }
        .mobile-drawer-inner { padding: 16px 24px 24px; display: flex; flex-direction: column; gap: 4px; }
        .mobile-link {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 16px 8px;
          border-bottom: 1px solid var(--vg-line);
          font-size: 17px;
          font-weight: 600;
          color: var(--vg-ink);
          font-family: var(--font-display);
        }
        .mobile-link.is-active { color: var(--vg-purple-700); }
        .mobile-link.is-active span::after {
          content: " ●";
          color: var(--vg-gold-600);
        }
        .mobile-actions { display: flex; gap: 12px; margin-top: 20px; }

        @media (max-width: 1100px) {
          .primary-nav { display: none; }
          .visit-cta { display: none; }
          .login-btn { display: none; }
          .hamburger { display: flex; }
          .nav-row { height: 72px; }
        }
      `}</style>
    </header>
  );
}

// ===== Footer =====
function Footer({ navigate, onLogin }) {
  return (
    <footer className="site-footer">
      <div className="container">
        <div className="footer-grid">
          <div className="footer-brand">
            <VGWordmark variant="light"/>
            <p style={{marginTop: 20, color: '#D9CCEF', maxWidth: 320}}>
              A non-denominational, full-gospel family of churches across the UAE and the Philippines — believing we are blessed to bless.
            </p>
            <div className="social-row">
              <a href="#" aria-label="Facebook" className="social-btn"><Icon name="fb" size={16}/></a>
              <a href="#" aria-label="Instagram" className="social-btn"><Icon name="ig" size={16}/></a>
              <a href="#" aria-label="YouTube" className="social-btn"><Icon name="yt" size={16}/></a>
            </div>
          </div>

          <div>
            <h5 className="footer-h">Visit</h5>
            <ul className="footer-list">
              <li><button onClick={() => navigate('visit')}>Plan Your Visit</button></li>
              <li><button onClick={() => navigate('locations')}>Locations</button></li>
              <li><button onClick={() => navigate('events')}>Events</button></li>
              <li><button onClick={() => navigate('contact')}>Contact</button></li>
            </ul>
          </div>

          <div>
            <h5 className="footer-h">Grow</h5>
            <ul className="footer-list">
              <li><button onClick={() => navigate('about')}>About Us</button></li>
              <li><button onClick={() => navigate('sermons')}>Sermons</button></li>
              <li><button onClick={() => navigate('ministries')}>Ministries</button></li>
              <li><button onClick={onLogin}>Members Login</button></li>
            </ul>
          </div>

          <div>
            <h5 className="footer-h">Get in touch</h5>
            <ul className="footer-list">
              <li><a href="mailto:stephen.bala@visiongeneration.org">stephen.bala@<wbr/>visiongeneration.org</a></li>
              <li>+971 (0) 50 000 0000</li>
              <li>Sundays · 4 cities</li>
            </ul>
            <button onClick={onLogin} className="btn btn-outline-gold btn-sm" style={{marginTop: 16}}>
              <Icon name="lock" size={14}/> Members Login
            </button>
          </div>
        </div>

        <div className="footer-bottom">
          <div>© 2025 Vision Generation Church. All rights reserved.</div>
          <div className="footer-bottom-right">
            <span style={{color:'var(--vg-gold-500)', fontFamily:'var(--font-display)', fontStyle:'italic'}}>"Blessed to Bless"</span>
            <span style={{opacity:0.4}}>·</span>
            <span>Abu Dhabi · Dubai · Imus · Trece Martires</span>
          </div>
        </div>
      </div>

      <style>{`
        .site-footer {
          background: linear-gradient(180deg, #1F0F3D 0%, #15082B 100%);
          color: #D9CCEF;
          padding: 80px 0 32px;
          position: relative;
          overflow: hidden;
        }
        .site-footer::before {
          content: "";
          position: absolute;
          top: 0; left: 0; right: 0;
          height: 1px;
          background: linear-gradient(90deg, transparent, var(--vg-gold-600), transparent);
        }
        .footer-grid {
          display: grid;
          grid-template-columns: 2fr 1fr 1fr 1.4fr;
          gap: 48px;
        }
        .footer-h {
          font-family: var(--font-display);
          font-size: 18px;
          font-weight: 500;
          color: #fff;
          margin: 0 0 18px;
        }
        .footer-list { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 10px; }
        .footer-list a, .footer-list button {
          color: #D9CCEF;
          font-size: 14px;
          padding: 0;
          text-align: left;
          transition: color .2s ease;
        }
        .footer-list a:hover, .footer-list button:hover { color: var(--vg-gold-500); }
        .social-row { display: flex; gap: 10px; margin-top: 24px; }
        .social-btn {
          width: 36px; height: 36px;
          border-radius: 50%;
          border: 1px solid rgba(217,204,239,0.2);
          display: flex; align-items: center; justify-content: center;
          color: #D9CCEF;
          transition: all .2s ease;
        }
        .social-btn:hover {
          background: var(--vg-gold-600);
          color: var(--vg-purple-900);
          border-color: var(--vg-gold-600);
          transform: translateY(-2px);
        }
        .footer-bottom {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding-top: 32px;
          margin-top: 56px;
          border-top: 1px solid rgba(217,204,239,0.12);
          font-size: 13px;
          color: #B7A6D6;
          gap: 16px;
          flex-wrap: wrap;
        }
        .footer-bottom-right { display: flex; align-items: center; gap: 12px; }

        @media (max-width: 900px) {
          .footer-grid { grid-template-columns: 1fr 1fr; gap: 40px; }
        }
        @media (max-width: 560px) {
          .footer-grid { grid-template-columns: 1fr; }
          .footer-bottom { flex-direction: column; align-items: flex-start; }
        }
      `}</style>
    </footer>
  );
}

// ===== Compact Login Modal =====
//
// Two-step email OTP flow:
//   1. Visitor enters email → POST /api/auth/magic-link → Supabase
//      sends an email containing a 6-digit code (and a magic link,
//      but we drive the flow through the code).
//   2. Visitor types the 6-digit code → POST /api/auth/verify-otp →
//      Supabase verifies + sets session cookies → redirect to
//      /home (the personal landing page).
//
// Closes on backdrop click, Escape key, or the × button. While in
// step 2, "Use a different email" returns to step 1.
// Inline-style for the OTP <-> Password mode toggle link inside the
// modal. Hard-coded purple matches the marketing brand and stays
// stable when the surrounding `<p className="muted">` swaps tone.
const modeLinkStyle = {
  background: 'transparent',
  border: 0,
  padding: 0,
  color: 'var(--vg-purple-700)',
  fontWeight: 600,
  cursor: 'pointer',
  font: 'inherit',
  textDecoration: 'underline',
};

function LoginModal({ open, onClose }) {
  const [email, setEmail] = React.useState('');
  const [code, setCode] = React.useState('');
  // 'idle' | 'sending' | 'codeSent' | 'verifying' | 'error'
  const [status, setStatus] = React.useState({ kind: 'idle' });
  // 'otp' (default — magic-link / one-time code) or 'password' —
  // toggled by the link under the primary CTA. OTP stays the
  // default because it's the no-password path visitors expect
  // out of the box.
  const [mode, setMode] = React.useState('otp');
  const [password, setPassword] = React.useState('');
  const emailInputRef = React.useRef(null);
  const codeInputRef = React.useRef(null);
  const passwordInputRef = React.useRef(null);

  React.useEffect(() => {
    if (open) {
      setEmail('');
      setCode('');
      setPassword('');
      setMode('otp');
      setStatus({ kind: 'idle' });
      requestAnimationFrame(
        () => emailInputRef.current && emailInputRef.current.focus()
      );
    }
  }, [open]);

  // When the visitor toggles to the password mode, slide focus
  // into the password input so they can type immediately.
  React.useEffect(() => {
    if (!open) return;
    if (mode === 'password' && passwordInputRef.current) {
      passwordInputRef.current.focus();
    }
  }, [mode, open]);

  // When step 2 mounts, focus the code input.
  React.useEffect(() => {
    if (status.kind === 'codeSent' && codeInputRef.current) {
      codeInputRef.current.focus();
    }
  }, [status.kind]);

  // Escape-key dismiss while open.
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  // ── Password sign-in (single step). ─────────────────────────
  // POSTs to /api/auth/password-signin, which calls
  // supabase.auth.signInWithPassword server-side and writes the
  // session cookies via @supabase/ssr. On success the user is
  // dropped at /home; the middleware will redirect to
  // /change-password if their profile flag is set.
  const signInWithPasswordFlow = async (e) => {
    e.preventDefault();
    const trimmed = email.trim();
    if (!trimmed || !password) return;
    setStatus({ kind: 'sending' });
    try {
      const res = await fetch('/api/auth/password-signin', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ email: trimmed, password }),
      });
      const json = await res.json().catch(() => ({}));
      if (!res.ok || !json.ok) {
        setStatus({
          kind: 'error',
          step: 'send',
          message:
            json.error ||
            "That email + password didn't work. Try again or use a one-time code.",
        });
        return;
      }
      window.location.href = '/home';
    } catch {
      setStatus({
        kind: 'error',
        step: 'send',
        message: 'Network error. Try again.',
      });
    }
  };

  // ── Step 1: request the OTP code ───────────────────────────────
  const sendCode = async (e) => {
    e.preventDefault();
    const trimmed = email.trim();
    if (!trimmed) return;
    setStatus({ kind: 'sending' });
    try {
      const res = await fetch('/api/auth/magic-link', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ email: trimmed }),
      });
      const json = await res.json().catch(() => ({}));
      if (!res.ok || !json.ok) {
        setStatus({
          kind: 'error',
          step: 'send',
          message: json.error || 'Could not send the code. Try again.',
        });
        return;
      }
      setStatus({ kind: 'codeSent', email: trimmed });
    } catch {
      setStatus({
        kind: 'error',
        step: 'send',
        message: 'Network error. Try again.',
      });
    }
  };

  // ── Step 2: submit the OTP code ───────────────────────────────
  const verifyCode = async (e) => {
    e.preventDefault();
    // Strip non-digits so a paste of "123 456" or "123-456" still works.
    // Supabase's OTP length is configurable (6–10 digits) — we accept
    // any length in that range so a future dashboard change doesn't
    // silently truncate.
    const cleaned = code.replace(/\D/g, '');
    if (cleaned.length < 6) return;
    setStatus({ kind: 'verifying', email });
    try {
      const res = await fetch('/api/auth/verify-otp', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ email, token: cleaned }),
      });
      const json = await res.json().catch(() => ({}));
      if (!res.ok || !json.ok) {
        setStatus({
          kind: 'error',
          step: 'verify',
          email,
          message:
            json.error ||
            'That code didn’t work. Try again or request a new one.',
        });
        // Clear the bad code so retyping is unambiguous.
        setCode('');
        return;
      }
      // Session cookies are now set. Send the visitor to the
      // signed-in landing.
      window.location.href = '/home';
    } catch {
      setStatus({
        kind: 'error',
        step: 'verify',
        email,
        message: 'Network error. Try again.',
      });
    }
  };

  const inStep2 =
    status.kind === 'codeSent' ||
    status.kind === 'verifying' ||
    (status.kind === 'error' && status.step === 'verify');

  const errorMessage =
    status.kind === 'error' ? status.message : null;

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div
        className="modal-card-sm"
        role="dialog"
        aria-label="Members sign in"
        onClick={(e) => e.stopPropagation()}
      >
        <button
          className="modal-close"
          onClick={onClose}
          aria-label="Close"
        >
          <Icon name="close" size={20} />
        </button>

        <div className="modal-form-sm">
          <div className="eyebrow" style={{ marginBottom: 8 }}>
            <span className="dot" />
            Members Sign In
          </div>

          {/* ── Step 1: ask for email (+ password if password mode) ── */}
          {!inStep2 && (
            <>
              <h2 style={{ fontSize: 24, margin: '0 0 8px' }}>
                Welcome{' '}
                <em
                  style={{
                    background:
                      'linear-gradient(135deg, var(--vg-gold-700), var(--vg-gold-500))',
                    WebkitBackgroundClip: 'text',
                    backgroundClip: 'text',
                    color: 'transparent',
                    fontStyle: 'italic',
                  }}
                >
                  back
                </em>
              </h2>
              <p
                className="muted"
                style={{ margin: '0 0 20px', fontSize: 14 }}
              >
                {mode === 'password'
                  ? "Enter your email and password."
                  : "Enter your email and we'll send you a one-time code."}
              </p>

              <form
                onSubmit={
                  mode === 'password'
                    ? signInWithPasswordFlow
                    : sendCode
                }
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  gap: 12,
                }}
              >
                <div className="field">
                  <label htmlFor="vg-login-email">Email address</label>
                  <input
                    ref={emailInputRef}
                    id="vg-login-email"
                    type="email"
                    autoComplete="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder="you@example.com"
                    required
                    disabled={status.kind === 'sending'}
                  />
                </div>

                {/* Password field only renders in password mode.
                    Sliding it in conditionally keeps the OTP-default
                    surface visually identical to before for visitors
                    who don't have a password set. */}
                {mode === 'password' && (
                  <div className="field">
                    <label htmlFor="vg-login-password">Password</label>
                    <input
                      ref={passwordInputRef}
                      id="vg-login-password"
                      type="password"
                      autoComplete="current-password"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      required
                      disabled={status.kind === 'sending'}
                    />
                  </div>
                )}

                {errorMessage && (
                  <div
                    style={{
                      fontSize: 13,
                      color: '#9c2222',
                      background: '#fdecec',
                      border: '1px solid #f4c4c4',
                      padding: '8px 12px',
                      borderRadius: 8,
                    }}
                  >
                    {errorMessage}
                  </div>
                )}

                <button
                  type="submit"
                  className="btn btn-primary"
                  disabled={
                    status.kind === 'sending' ||
                    !email.trim() ||
                    (mode === 'password' && !password)
                  }
                  style={{
                    width: '100%',
                    justifyContent: 'center',
                    opacity:
                      status.kind === 'sending' ||
                      !email.trim() ||
                      (mode === 'password' && !password)
                        ? 0.6
                        : 1,
                    cursor:
                      status.kind === 'sending' ? 'wait' : 'pointer',
                  }}
                >
                  <Icon name="lock" size={16} />
                  {status.kind === 'sending'
                    ? mode === 'password'
                      ? 'Signing in…'
                      : 'Sending…'
                    : mode === 'password'
                    ? 'Sign in'
                    : 'Send code'}
                </button>
              </form>

              {/* Mode toggle — subtle link under the primary CTA.
                  OTP stays the default for visitors who came in
                  via a magic-link invitation; admins enrolled
                  with a password use this to switch modes. */}
              <p
                className="muted"
                style={{
                  marginTop: 14,
                  fontSize: 13,
                  textAlign: 'center',
                }}
              >
                {mode === 'password' ? (
                  <>
                    Prefer a one-time code?{' '}
                    <button
                      type="button"
                      onClick={() => {
                        setMode('otp');
                        setPassword('');
                        setStatus({ kind: 'idle' });
                      }}
                      style={modeLinkStyle}
                    >
                      Sign in with code
                    </button>
                  </>
                ) : (
                  <>
                    Have a password?{' '}
                    <button
                      type="button"
                      onClick={() => {
                        setMode('password');
                        setStatus({ kind: 'idle' });
                      }}
                      style={modeLinkStyle}
                    >
                      Sign in with password
                    </button>
                  </>
                )}
              </p>

              <p
                className="muted"
                style={{
                  fontSize: 12,
                  marginTop: 16,
                  lineHeight: 1.55,
                }}
              >
                Member accounts are created after joining a Sunday
                service. If you don&apos;t have one yet,{' '}
                <a
                  href="#visit"
                  onClick={onClose}
                  style={{
                    color: 'var(--vg-purple-700)',
                    fontWeight: 600,
                  }}
                >
                  plan a visit
                </a>{' '}
                first.
              </p>
            </>
          )}

          {/* ── Step 2: enter the code ─────────────────────────── */}
          {inStep2 && (
            <>
              <h2 style={{ fontSize: 24, margin: '0 0 8px' }}>
                Enter the{' '}
                <em
                  style={{
                    background:
                      'linear-gradient(135deg, var(--vg-gold-700), var(--vg-gold-500))',
                    WebkitBackgroundClip: 'text',
                    backgroundClip: 'text',
                    color: 'transparent',
                    fontStyle: 'italic',
                  }}
                >
                  6-digit code
                </em>
              </h2>
              <p
                className="muted"
                style={{ margin: '0 0 20px', fontSize: 14 }}
              >
                We sent it to <b>{status.email || email}</b>. The code
                expires in a few minutes.
              </p>

              <form
                onSubmit={verifyCode}
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  gap: 12,
                }}
              >
                <div className="field">
                  <label htmlFor="vg-login-code">One-time code</label>
                  <input
                    ref={codeInputRef}
                    id="vg-login-code"
                    type="text"
                    inputMode="numeric"
                    autoComplete="one-time-code"
                    /* Accept 6–10 digits to match Supabase's OTP-length
                       range; the actual configured length comes from
                       the dashboard setting. */
                    pattern="[0-9]{6,10}"
                    maxLength={10}
                    value={code}
                    onChange={(e) =>
                      setCode(e.target.value.replace(/\D/g, '').slice(0, 10))
                    }
                    placeholder="123456"
                    required
                    disabled={status.kind === 'verifying'}
                    style={{
                      letterSpacing: '0.4em',
                      fontFamily: 'var(--font-mono, ui-monospace, monospace)',
                      fontSize: 18,
                      textAlign: 'center',
                    }}
                  />
                </div>

                {errorMessage && (
                  <div
                    style={{
                      fontSize: 13,
                      color: '#9c2222',
                      background: '#fdecec',
                      border: '1px solid #f4c4c4',
                      padding: '8px 12px',
                      borderRadius: 8,
                    }}
                  >
                    {errorMessage}
                  </div>
                )}

                <button
                  type="submit"
                  className="btn btn-primary"
                  disabled={
                    status.kind === 'verifying' ||
                    code.replace(/\D/g, '').length < 6
                  }
                  style={{
                    width: '100%',
                    justifyContent: 'center',
                    opacity:
                      status.kind === 'verifying' ||
                      code.replace(/\D/g, '').length < 6
                        ? 0.6
                        : 1,
                    cursor:
                      status.kind === 'verifying' ? 'wait' : 'pointer',
                  }}
                >
                  <Icon name="lock" size={16} />
                  {status.kind === 'verifying'
                    ? 'Verifying…'
                    : 'Verify and sign in'}
                </button>
              </form>

              <div
                style={{
                  display: 'flex',
                  gap: 12,
                  justifyContent: 'center',
                  marginTop: 16,
                  fontSize: 12,
                }}
              >
                <button
                  type="button"
                  onClick={async () => {
                    // Re-issue a fresh code for the same email.
                    setStatus({ kind: 'sending' });
                    setCode('');
                    try {
                      const res = await fetch('/api/auth/magic-link', {
                        method: 'POST',
                        headers: { 'content-type': 'application/json' },
                        body: JSON.stringify({ email: email.trim() }),
                      });
                      const json = await res.json().catch(() => ({}));
                      if (!res.ok || !json.ok) {
                        setStatus({
                          kind: 'error',
                          step: 'verify',
                          email,
                          message:
                            json.error ||
                            'Could not resend. Try again later.',
                        });
                      } else {
                        setStatus({ kind: 'codeSent', email });
                      }
                    } catch {
                      setStatus({
                        kind: 'error',
                        step: 'verify',
                        email,
                        message: 'Network error. Try again.',
                      });
                    }
                  }}
                  style={{
                    background: 'transparent',
                    border: 0,
                    color: 'var(--vg-purple-700)',
                    fontWeight: 600,
                    cursor: 'pointer',
                  }}
                >
                  Resend code
                </button>
                <span style={{ color: 'var(--vg-mute)' }}>·</span>
                <button
                  type="button"
                  onClick={() => {
                    setStatus({ kind: 'idle' });
                    setCode('');
                  }}
                  style={{
                    background: 'transparent',
                    border: 0,
                    color: 'var(--vg-ink-soft)',
                    cursor: 'pointer',
                  }}
                >
                  Use a different email
                </button>
              </div>
            </>
          )}
        </div>
      </div>

      <style>{`
        .modal-backdrop {
          position: fixed; inset: 0;
          background: rgba(31,15,61,0.55);
          backdrop-filter: blur(6px);
          z-index: 200;
          display: flex; align-items: center; justify-content: center;
          padding: 24px;
          animation: fadeIn .25s ease;
        }
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        .modal-card-sm {
          background: #fff;
          border-radius: 20px;
          width: 100%;
          max-width: 420px;
          overflow: hidden;
          box-shadow: var(--shadow-lg);
          position: relative;
          animation: fadeUp .35s ease;
        }
        .modal-close {
          position: absolute; top: 12px; right: 12px;
          width: 32px; height: 32px;
          border-radius: 50%;
          background: rgba(255,255,255,0.9);
          color: var(--vg-ink);
          z-index: 3;
          display: flex; align-items: center; justify-content: center;
          transition: all .2s ease;
        }
        .modal-close:hover { background: var(--vg-purple-700); color: #fff; }
        .modal-form-sm { padding: 36px 32px 32px; }

        @media (max-width: 480px) {
          .modal-form-sm { padding: 28px 22px 24px; }
        }
      `}</style>
    </div>
  );
}

Object.assign(window, { Header, Footer, LoginModal });
