/* ============================================================
   AUTH — Sign In · Sign Up · Reset · Magic Link
   Exports: AuthPage, AuthGate
   ============================================================ */

/* ── Shared field ─────────────────────────────────────────── */
function AuthField({ label, type = 'text', value, onChange, placeholder, autocomplete, required, hint, error, rightSlot }) {
  const [show, setShow] = React.useState(false);
  const isPass = type === 'password';
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <label style={{ fontSize: 11, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--ink-soft)', fontWeight: 500 }}>
          {label}{required && <span style={{ color: 'var(--blush)', marginLeft: 2 }}>*</span>}
        </label>
        {rightSlot}
      </div>
      <div style={{ position: 'relative' }}>
        <input
          className="input"
          type={isPass && show ? 'text' : type}
          value={value}
          onChange={onChange}
          placeholder={placeholder}
          autoComplete={autocomplete}
          style={{ paddingRight: isPass ? 44 : 16, borderColor: error ? 'var(--blush)' : undefined, boxShadow: error ? '0 0 0 4px rgba(192,123,74,.09)' : undefined }}
        />
        {isPass && (
          <button type="button" onClick={() => setShow(s => !s)}
            style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-faint)', background: 'none', border: 'none', cursor: 'pointer', padding: 4 }}
            aria-label={show ? 'Hide password' : 'Show password'}>
            {show
              ? <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"/><path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
              : <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>}
          </button>
        )}
      </div>
      {hint && !error && <p style={{ fontSize: 12, color: 'var(--ink-faint)', lineHeight: 1.5 }}>{hint}</p>}
      {error && <p style={{ fontSize: 12, color: 'var(--blush)', display: 'flex', alignItems: 'center', gap: 5 }}>
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="9"/><path d="M12 8v4M12 16h.01"/></svg>
        {error}
      </p>}
    </div>
  );
}

/* ── Password strength ────────────────────────────────────── */
function PasswordStrength({ password }) {
  const score = React.useMemo(() => {
    if (!password) return 0;
    let s = 0;
    if (password.length >= 8)  s++;
    if (/[A-Z]/.test(password)) s++;
    if (/[0-9]/.test(password)) s++;
    if (/[^A-Za-z0-9]/.test(password)) s++;
    return s;
  }, [password]);
  if (!password) return null;
  const labels = ['', 'Weak', 'Fair', 'Good', 'Strong'];
  const colors = ['', 'var(--blush)', '#E8A020', 'var(--sage)', 'var(--gold-deep)'];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
      <div style={{ display: 'flex', gap: 4 }}>
        {[1,2,3,4].map(i => (
          <div key={i} style={{ flex: 1, height: 3, borderRadius: 2, background: i <= score ? colors[score] : 'var(--line)', transition: 'background .3s' }} />
        ))}
      </div>
      <span style={{ fontSize: 11, color: colors[score], fontWeight: 500 }}>{labels[score]}</span>
    </div>
  );
}

/* ── Social / OAuth button ────────────────────────────────── */
function OAuthBtn({ icon, label, onClick }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button type="button" onClick={onClick}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, padding: '13px 20px', borderRadius: 'var(--r-sm)', border: '1.5px solid var(--line)', background: hover ? 'var(--cream-deep)' : 'var(--cream)', color: 'var(--ink)', fontSize: 14, fontWeight: 500, cursor: 'pointer', transition: 'background .2s, border-color .2s', borderColor: hover ? 'var(--ink-faint)' : 'var(--line)' }}>
      {icon}
      {label}
    </button>
  );
}

const GoogleIcon = () => (
  <svg width="18" height="18" viewBox="0 0 24 24">
    <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
    <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
    <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z"/>
    <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
  </svg>
);

/* ══════════════════════════════════════════════════════════
   AuthPage — main component
════════════════════════════════════════════════════════════ */
function AuthPage({ initialMode = 'signin', redirectTo }) {
  const { signIn, signUp, nav } = useStore();
  const [mode, setMode] = React.useState(initialMode); // signin | signup | reset | magic | sent
  const [loading, setLoading] = React.useState(false);

  // Sign in state
  const [siEmail, setSiEmail] = React.useState('');
  const [siPass,  setSiPass]  = React.useState('');
  const [siErr,   setSiErr]   = React.useState({});

  // Sign up state
  const [suFirst, setSuFirst] = React.useState('');
  const [suLast,  setSuLast]  = React.useState('');
  const [suEmail, setSuEmail] = React.useState('');
  const [suPass,  setSuPass]  = React.useState('');
  const [suConf,  setSuConf]  = React.useState('');
  const [suErr,   setSuErr]   = React.useState({});

  // Reset state
  const [rstEmail, setRstEmail] = React.useState('');
  const [rstErr,   setRstErr]   = React.useState('');

  // Magic link
  const [mgEmail, setMgEmail] = React.useState('');

  const fake = (ms = 1200) => new Promise(r => setTimeout(r, ms));

  /* ── Handlers ── */
  const handleSignIn = async (e) => {
    e.preventDefault();
    const errs = {};
    if (!siEmail.includes('@')) errs.email = 'Please enter a valid email address.';
    if (!siPass) errs.pass = 'Password is required.';
    if (Object.keys(errs).length) { setSiErr(errs); return; }
    setSiErr({}); setLoading(true);
    await fake();
    signIn({ email: siEmail, name: siEmail.split('@')[0] });
    setLoading(false);
    nav(redirectTo || 'account');
  };

  const handleSignUp = async (e) => {
    e.preventDefault();
    const errs = {};
    if (!suFirst.trim()) errs.first = 'First name is required.';
    if (!suEmail.includes('@')) errs.email = 'Please enter a valid email address.';
    if (suPass.length < 8) errs.pass = 'Password must be at least 8 characters.';
    if (suPass !== suConf) errs.conf = 'Passwords do not match.';
    if (Object.keys(errs).length) { setSuErr(errs); return; }
    setSuErr({}); setLoading(true);
    await fake();
    signUp({ firstName: suFirst, lastName: suLast, email: suEmail, name: `${suFirst} ${suLast}`.trim() });
    setLoading(false);
    nav(redirectTo || 'account');
  };

  const handleReset = async (e) => {
    e.preventDefault();
    if (!rstEmail.includes('@')) { setRstErr('Please enter a valid email address.'); return; }
    setRstErr(''); setLoading(true);
    await fake();
    setLoading(false);
    setMode('sent');
  };

  const handleMagic = async (e) => {
    e.preventDefault();
    if (!mgEmail.includes('@')) return;
    setLoading(true);
    await fake();
    setLoading(false);
    setMode('sent');
  };

  /* ── Layout shell ── */
  return (
    <div style={{ minHeight: '100vh', background: 'var(--cream)', display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
      {/* Left: decorative panel */}
      <div style={{ background: 'var(--ink)', position: 'relative', overflow: 'hidden', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', padding: 'clamp(40px,6vw,72px)' }}>
        <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(ellipse 80% 70% at 30% 60%, rgba(200,151,31,.28) 0%, transparent 65%), radial-gradient(ellipse 60% 50% at 70% 20%, rgba(192,123,74,.14) 0%, transparent 60%)', pointerEvents: 'none' }} />
        {/* Logo */}
        <button onClick={() => nav('home')} style={{ position: 'relative', zIndex: 1, textAlign: 'left', background: 'none', border: 'none', cursor: 'pointer' }}>
          <span style={{ fontFamily: 'var(--serif)', fontSize: 26, color: '#fff' }}>
            Your{' '}
            <em style={{ fontStyle: 'italic', background: 'linear-gradient(100deg,#E0B24A,#C07B4A)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>Brand</em>
          </span>
        </button>
        {/* Headline */}
        <div style={{ position: 'relative', zIndex: 1 }}>
          <h2 style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(32px,4.5vw,54px)', color: '#fff', lineHeight: .98, marginBottom: 18 }}>
            Every celebration<br/>
            <em style={{ fontStyle: 'italic', background: 'linear-gradient(135deg,#E0B24A,#C07B4A)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>made to order.</em>
          </h2>
          <p style={{ fontSize: 15, color: 'rgba(255,255,255,.58)', lineHeight: 1.75, maxWidth: 360 }}>
            Create an account to track your orders, save favourites, and check out faster.
          </p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 32 }}>
            {[
              ['Track every order', 'From received to delivered — always know where your pieces are.'],
              ['Save your wishlist', 'Curate your categories and revisit anytime.'],
              ['Faster checkout', 'Saved details mean less typing, more celebrating.'],
            ].map(([t, d]) => (
              <div key={t} style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                <div style={{ width: 20, height: 20, borderRadius: '50%', background: 'linear-gradient(135deg,var(--gold-deep),var(--gold))', display: 'grid', placeItems: 'center', flexShrink: 0, marginTop: 2 }}>
                  <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5"><path d="m5 13 4 4 10-11" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </div>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 500, color: '#fff', marginBottom: 2 }}>{t}</div>
                  <div style={{ fontSize: 13, color: 'rgba(255,255,255,.48)', lineHeight: 1.55 }}>{d}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
        {/* Footer */}
        <p style={{ fontSize: 12, color: 'rgba(255,255,255,.25)', position: 'relative', zIndex: 1 }}>© {new Date().getFullYear()} {BB.BRAND.name} · All rights reserved</p>
      </div>

      {/* Right: form panel */}
      <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: 'clamp(32px,5vw,64px) clamp(24px,5vw,72px)', overflowY: 'auto' }}>

        {/* ── SIGN IN ── */}
        {mode === 'signin' && (
          <form onSubmit={handleSignIn} style={{ maxWidth: 400, width: '100%', margin: '0 auto' }}>
            <p className="eyebrow" style={{ marginBottom: 8 }}>Welcome back</p>
            <h1 style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(32px,4vw,46px)', marginBottom: 6 }}>Sign <em style={{ fontStyle: 'italic' }}>in</em></h1>
            <p style={{ fontSize: 15, color: 'var(--ink-soft)', marginBottom: 28, lineHeight: 1.6 }}>
              New here?{' '}
              <button type="button" onClick={() => setMode('signup')} style={{ color: 'var(--gold-deep)', fontWeight: 500, background: 'none', border: 'none', cursor: 'pointer', fontSize: 15, textDecoration: 'underline' }}>Create an account</button>
            </p>

            {/* OAuth */}
            <OAuthBtn icon={<GoogleIcon />} label="Continue with Google" onClick={() => {}} />
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '20px 0' }}>
              <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
              <span style={{ fontSize: 11, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--ink-faint)' }}>or</span>
              <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <AuthField label="Email" type="email" value={siEmail} onChange={e => setSiEmail(e.target.value)} placeholder="you@email.com" autocomplete="email" required error={siErr.email} />
              <AuthField label="Password" type="password" value={siPass} onChange={e => setSiPass(e.target.value)} placeholder="••••••••" autocomplete="current-password" required error={siErr.pass}
                rightSlot={<button type="button" onClick={() => setMode('reset')} style={{ fontSize: 12, color: 'var(--gold-deep)', background: 'none', border: 'none', cursor: 'pointer' }}>Forgot password?</button>} />
            </div>

            <button type="submit" className="btn btn-primary" disabled={loading}
              style={{ width: '100%', justifyContent: 'center', marginTop: 24, opacity: loading ? .7 : 1 }}>
              {loading
                ? <><span style={{ width: 16, height: 16, borderRadius: '50%', border: '2px solid rgba(255,255,255,.4)', borderTopColor: '#fff', animation: 'spin .7s linear infinite', display: 'inline-block' }} /><span>Signing in…</span></>
                : <><span>Sign in</span><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6" strokeLinecap="round" strokeLinejoin="round"/></svg></>}
            </button>

            <button type="button" onClick={() => setMode('magic')}
              style={{ width: '100%', marginTop: 12, padding: '13px', borderRadius: 100, border: '1.5px solid var(--line)', background: 'none', fontSize: 13, color: 'var(--ink-soft)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, fontFamily: 'var(--sans)', transition: 'border-color .2s, color .2s' }}
              onMouseEnter={e => { e.currentTarget.style.borderColor='var(--ink)'; e.currentTarget.style.color='var(--ink)'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor='var(--line)'; e.currentTarget.style.color='var(--ink-soft)'; }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
              Email me a sign-in link instead
            </button>

            <p style={{ fontSize: 12, color: 'var(--ink-faint)', textAlign: 'center', marginTop: 20 }}>
              By signing in you agree to our{' '}
              <button type="button" style={{ color: 'var(--gold-deep)', background: 'none', border: 'none', cursor: 'pointer', fontSize: 12 }}>Terms</button>
              {' & '}
              <button type="button" style={{ color: 'var(--gold-deep)', background: 'none', border: 'none', cursor: 'pointer', fontSize: 12 }}>Privacy Policy</button>.
            </p>
          </form>
        )}

        {/* ── SIGN UP ── */}
        {mode === 'signup' && (
          <form onSubmit={handleSignUp} style={{ maxWidth: 400, width: '100%', margin: '0 auto' }}>
            <p className="eyebrow" style={{ marginBottom: 8 }}>Join us</p>
            <h1 style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(32px,4vw,46px)', marginBottom: 6 }}>Create an <em style={{ fontStyle: 'italic' }}>account</em></h1>
            <p style={{ fontSize: 15, color: 'var(--ink-soft)', marginBottom: 28 }}>
              Already have one?{' '}
              <button type="button" onClick={() => setMode('signin')} style={{ color: 'var(--gold-deep)', fontWeight: 500, background: 'none', border: 'none', cursor: 'pointer', fontSize: 15, textDecoration: 'underline' }}>Sign in</button>
            </p>

            <OAuthBtn icon={<GoogleIcon />} label="Sign up with Google" onClick={() => {}} />
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '20px 0' }}>
              <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
              <span style={{ fontSize: 11, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--ink-faint)' }}>or</span>
              <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 15 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <AuthField label="First name" value={suFirst} onChange={e => setSuFirst(e.target.value)} placeholder="Alex" autocomplete="given-name" required error={suErr.first} />
                <AuthField label="Last name" value={suLast} onChange={e => setSuLast(e.target.value)} placeholder="Morgan" autocomplete="family-name" />
              </div>
              <AuthField label="Email" type="email" value={suEmail} onChange={e => setSuEmail(e.target.value)} placeholder="you@email.com" autocomplete="email" required error={suErr.email} />
              <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
                <AuthField label="Password" type="password" value={suPass} onChange={e => setSuPass(e.target.value)} placeholder="8+ characters" autocomplete="new-password" required error={suErr.pass} />
                <PasswordStrength password={suPass} />
              </div>
              <AuthField label="Confirm password" type="password" value={suConf} onChange={e => setSuConf(e.target.value)} placeholder="Re-enter password" autocomplete="new-password" required error={suErr.conf} />
            </div>

            <button type="submit" className="btn btn-primary" disabled={loading}
              style={{ width: '100%', justifyContent: 'center', marginTop: 22, opacity: loading ? .7 : 1 }}>
              {loading
                ? <><span style={{ width: 16, height: 16, borderRadius: '50%', border: '2px solid rgba(255,255,255,.4)', borderTopColor: '#fff', animation: 'spin .7s linear infinite', display: 'inline-block' }} /><span>Creating account…</span></>
                : <><span>Create account</span><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6" strokeLinecap="round" strokeLinejoin="round"/></svg></>}
            </button>

            <p style={{ fontSize: 12, color: 'var(--ink-faint)', textAlign: 'center', marginTop: 16 }}>
              By creating an account you agree to our{' '}
              <button type="button" style={{ color: 'var(--gold-deep)', background: 'none', border: 'none', cursor: 'pointer', fontSize: 12 }}>Terms</button>
              {' & '}
              <button type="button" style={{ color: 'var(--gold-deep)', background: 'none', border: 'none', cursor: 'pointer', fontSize: 12 }}>Privacy Policy</button>.
            </p>
          </form>
        )}

        {/* ── RESET ── */}
        {mode === 'reset' && (
          <form onSubmit={handleReset} style={{ maxWidth: 400, width: '100%', margin: '0 auto' }}>
            <button type="button" onClick={() => setMode('signin')} style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 12, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--ink-soft)', background: 'none', border: 'none', cursor: 'pointer', marginBottom: 24 }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M19 12H5M12 5l-7 7 7 7" strokeLinecap="round" strokeLinejoin="round"/></svg>
              Back to sign in
            </button>
            <div style={{ width: 52, height: 52, borderRadius: '50%', background: 'var(--gold-soft)', display: 'grid', placeItems: 'center', color: 'var(--gold-deep)', marginBottom: 20 }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
            </div>
            <h2 style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(28px,3.5vw,40px)', marginBottom: 10 }}>Reset your <em style={{ fontStyle: 'italic' }}>password</em></h2>
            <p style={{ fontSize: 15, color: 'var(--ink-soft)', marginBottom: 24, lineHeight: 1.65 }}>Enter the email address associated with your account and we'll send a reset link.</p>
            <AuthField label="Email" type="email" value={rstEmail} onChange={e => setRstEmail(e.target.value)} placeholder="you@email.com" autocomplete="email" required error={rstErr} />
            <button type="submit" className="btn btn-primary" disabled={loading} style={{ width: '100%', justifyContent: 'center', marginTop: 20, opacity: loading ? .7 : 1 }}>
              {loading
                ? <><span style={{ width: 16, height: 16, borderRadius: '50%', border: '2px solid rgba(255,255,255,.4)', borderTopColor: '#fff', animation: 'spin .7s linear infinite', display: 'inline-block' }} /><span>Sending…</span></>
                : <span>Send reset link</span>}
            </button>
          </form>
        )}

        {/* ── MAGIC LINK ── */}
        {mode === 'magic' && (
          <form onSubmit={handleMagic} style={{ maxWidth: 400, width: '100%', margin: '0 auto' }}>
            <button type="button" onClick={() => setMode('signin')} style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 12, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--ink-soft)', background: 'none', border: 'none', cursor: 'pointer', marginBottom: 24 }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M19 12H5M12 5l-7 7 7 7" strokeLinecap="round" strokeLinejoin="round"/></svg>
              Back
            </button>
            <div style={{ width: 52, height: 52, borderRadius: '50%', background: 'var(--blush-soft)', display: 'grid', placeItems: 'center', color: 'var(--blush-deep)', marginBottom: 20 }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
            </div>
            <h2 style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(28px,3.5vw,40px)', marginBottom: 10 }}>Sign in with a <em style={{ fontStyle: 'italic' }}>magic link</em></h2>
            <p style={{ fontSize: 15, color: 'var(--ink-soft)', marginBottom: 24, lineHeight: 1.65 }}>No password needed. We'll email you a secure one-click sign-in link.</p>
            <AuthField label="Email" type="email" value={mgEmail} onChange={e => setMgEmail(e.target.value)} placeholder="you@email.com" autocomplete="email" required />
            <button type="submit" className="btn btn-primary" disabled={loading} style={{ width: '100%', justifyContent: 'center', marginTop: 20, opacity: loading ? .7 : 1 }}>
              {loading
                ? <><span style={{ width: 16, height: 16, borderRadius: '50%', border: '2px solid rgba(255,255,255,.4)', borderTopColor: '#fff', animation: 'spin .7s linear infinite', display: 'inline-block' }} /><span>Sending…</span></>
                : <span>Send magic link</span>}
            </button>
          </form>
        )}

        {/* ── EMAIL SENT ── */}
        {mode === 'sent' && (
          <div style={{ maxWidth: 400, width: '100%', margin: '0 auto', textAlign: 'center' }}>
            <div style={{ width: 72, height: 72, borderRadius: '50%', background: 'linear-gradient(135deg,var(--gold-deep),var(--gold))', display: 'grid', placeItems: 'center', color: '#fff', margin: '0 auto 22px', boxShadow: '0 8px 28px rgba(200,151,31,.28)' }}>
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
            </div>
            <p className="eyebrow" style={{ color: 'var(--gold-deep)', marginBottom: 10 }}>Check your inbox</p>
            <h2 style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(28px,4vw,42px)', marginBottom: 14 }}>Email <em style={{ fontStyle: 'italic' }}>sent!</em></h2>
            <p style={{ fontSize: 15, color: 'var(--ink-soft)', lineHeight: 1.75, marginBottom: 28 }}>
              We've sent a link to your inbox. It will expire in 10 minutes. Don't forget to check your spam folder.
            </p>
            <button type="button" className="btn btn-secondary" onClick={() => setMode('signin')} style={{ margin: '0 auto' }}>Back to sign in</button>
          </div>
        )}

      </div>

      {/* Responsive: stack on mobile */}
      <style>{`
        @media(max-width:720px){
          .auth-split { grid-template-columns: 1fr !important; }
          .auth-deco { display: none !important; }
        }
        @keyframes spin { to { transform: rotate(360deg); } }
      `}</style>
    </div>
  );
}

/* ── AuthGate ─────────────────────────────────────────────
   Wrap any page — if not signed in, show sign-in prompt
   ────────────────────────────────────────────────────────── */
function AuthGate({ children, redirectTo }) {
  const { user, nav } = useStore();
  if (user) return children;
  return (
    <div style={{ background: 'var(--cream)', minHeight: '70vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 'clamp(40px,7vw,80px) var(--gutter)' }}>
      <div style={{ maxWidth: 460, width: '100%', textAlign: 'center' }}>
        <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'var(--gold-soft)', display: 'grid', placeItems: 'center', color: 'var(--gold-deep)', margin: '0 auto 20px' }}>
          <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 4-6 8-6s8 2 8 6"/></svg>
        </div>
        <p className="eyebrow" style={{ marginBottom: 10 }}>Members only</p>
        <h2 style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(28px,4vw,42px)', marginBottom: 12 }}>Sign in to <em style={{ fontStyle: 'italic' }}>continue</em></h2>
        <p style={{ fontSize: 15, color: 'var(--ink-soft)', lineHeight: 1.7, marginBottom: 28 }}>Please sign in or create a free account to access this page.</p>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
          <button className="btn btn-primary" onClick={() => nav('auth', { mode: 'signin', redirectTo })}>
            <span>Sign in</span>
          </button>
          <button className="btn btn-secondary" onClick={() => nav('auth', { mode: 'signup', redirectTo })}>Create account</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AuthPage, AuthGate });
