// admin-login.jsx — Magic-link only.
//
// As of 2026-05-18, password sign-in is removed for the admin portal.
// Joe's reasoning: the admin dashboard is the most sensitive surface on
// the site, so we don't want a guessable / leakable password living
// anywhere. Magic-link forces ownership of the inbox at every login.
//
// Two paths render in this component:
//   1. Already-signed-in user → we check if their email is on the admin
//      allow-list and auto-call onLogin(). Same behaviour as before.
//   2. Not signed in → we show ONE input (email) and ONE button
//      ("Send login link"). Supabase emails a magic link; clicking it
//      lands them back here signed in, which triggers path (1).

const AdminLogin = ({ onLogin, onBack }) => {
  const auth = window.useAuth();
  const [email, setEmail] = React.useState(auth.user?.email || '');
  const [error, setError] = React.useState('');
  const [busy, setBusy]   = React.useState(false);
  const [sent, setSent]   = React.useState(false);
  const captcha = window.useCaptcha ? window.useCaptcha() : { token: null, widget: null, required: false };

  // Already signed in? Check the allow-list and jump straight in. (Magic
  // link landing also lands here — auth.user fills in, this effect fires,
  // and we route through to the dashboard if they're an admin.)
  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      if (!auth.user) return;
      const { data } = await window.supa
        .from('admin_users')
        .select('email')
        .eq('email', (auth.user.email || '').toLowerCase())
        .maybeSingle();
      if (cancelled) return;
      if (data) {
        onLogin();
      } else {
        // Signed in but not on the admin list — surface a clear error
        // instead of silently doing nothing. The user can sign out and
        // try a different email, or contact whoever runs admin_users.
        setError("That account is signed in, but isn't on the admin allow-list. Contact your administrator.");
      }
    })();
    return () => { cancelled = true; };
  }, [auth.user?.id]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (captcha.required) { setError('Please complete the captcha.'); return; }
    setError(''); setBusy(true);
    try {
      // sendMagicLink uses signInWithOtp with shouldCreateUser:false so
      // it errors if the email isn't already in auth.users — matches the
      // existing student/instructor login flows.
      const { error } = await window.AUTH.sendMagicLink({ email: email.trim().toLowerCase(), captchaToken: captcha.token });
      captcha.reset && captcha.reset();
      if (error) {
        setError(error.message || "Couldn't send login link.");
        return;
      }
      setSent(true);
    } catch (e2) {
      setError(e2.message || 'Sign-in failed.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{
      minHeight: '100vh',
      background: 'oklch(98.5% 0.007 60)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: "'Plus Jakarta Sans', sans-serif",
      position: 'relative',
    }}>
      {/* X close — matches the other auth flows. */}
      <button onClick={onBack} aria-label="Close" title="Back to site"
        style={{ position:'absolute', top:18, right:18, width:38, height:38, borderRadius:'50%', background:'oklch(95% 0.005 60)', border:'1px solid oklch(90% 0.01 265)', cursor:'pointer', fontSize:18, lineHeight:1, color:'oklch(40% 0.04 265)', fontFamily:"'Plus Jakarta Sans', sans-serif", display:'flex', alignItems:'center', justifyContent:'center', zIndex:10 }}>
        ×
      </button>

      <div style={{ width: 420, textAlign: 'center' }}>
        {/* Logo */}
        <div style={{ fontFamily: "'Plus Jakarta Sans', sans-serif", fontSize: 22, fontWeight: 800, letterSpacing: '0.06em', color: 'oklch(22% 0.06 265)', marginBottom: 6, textTransform: 'uppercase' }}>Mastery</div>
        <div style={{ fontSize: 13, color: 'oklch(55% 0.03 265)', marginBottom: 44, letterSpacing: '0.04em' }}>Admin Access</div>

        <div style={{ background: '#fff', borderRadius: 18, padding: '40px 40px 36px', border: '1px solid oklch(90% 0.01 265)', boxShadow: '0 4px 32px oklch(18% 0.06 265 / 0.09)' }}>
          {sent ? (
            <>
              <div style={{ width:48, height:48, borderRadius:12, background:'oklch(22% 0.06 265)', display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto 16px', flexShrink:0 }}>
                <svg width="22" height="22" viewBox="0 0 22 22" fill="none"><rect x="1" y="4" width="20" height="14" rx="3" stroke="#fff" strokeWidth="1.6"/><path d="M1 7l10 7 10-7" stroke="#fff" strokeWidth="1.6" strokeLinejoin="round"/></svg>
              </div>
              <div style={{ fontWeight: 700, fontSize: 16, color: 'oklch(18% 0.03 265)', marginBottom: 8 }}>Check your email</div>
              <div style={{ fontSize: 14, color: 'oklch(52% 0.03 265)', lineHeight: 1.6, marginBottom: 18 }}>
                We sent a one-tap login link to <strong>{email}</strong>. Click it to access the admin dashboard. The tab will reload automatically.
              </div>
              <button
                type="button"
                onClick={() => { setSent(false); setError(''); }}
                style={{ background: 'oklch(95% 0.01 265)', border: '1px solid oklch(88% 0.02 265)', borderRadius: 10, padding: '10px 18px', fontWeight: 600, fontSize: 13, cursor: 'pointer', fontFamily: "'Plus Jakarta Sans', sans-serif", color: 'oklch(36% 0.04 265)' }}
              >
                Use a different email
              </button>
            </>
          ) : (
            <form onSubmit={handleSubmit}>
              <div style={{ marginBottom: 20, textAlign: 'left' }}>
                <label style={{ display: 'block', fontSize: 11, fontWeight: 700, color: 'oklch(42% 0.04 265)', letterSpacing: '0.07em', textTransform: 'uppercase', marginBottom: 7 }}>Email</label>
                <input
                  type="email" value={email} onChange={e => setEmail(e.target.value)}
                  placeholder="hello@coachingforall.co" required autoFocus
                  style={{ width: '100%', padding: '11px 14px', borderRadius: 10, border: '1.5px solid oklch(87% 0.02 265)', fontSize: 14, color: 'oklch(22% 0.06 265)', outline: 'none', background: 'oklch(98.5% 0.005 60)', fontFamily: "'Plus Jakarta Sans', sans-serif", boxSizing: 'border-box' }}
                />
              </div>
              <div style={{ fontSize: 12, color: 'oklch(58% 0.03 265)', textAlign: 'left', lineHeight: 1.55, marginBottom: 20 }}>
                We'll email you a one-tap login link. No password needed — and the link expires after a few minutes.
              </div>
              {captcha.widget}
              {error && (
                <div style={{ color: 'oklch(50% 0.19 25)', fontSize: 13, marginBottom: 16, textAlign: 'left', padding: '10px 12px', background: 'oklch(96% 0.06 25)', borderRadius: 8 }}>{error}</div>
              )}
              <button
                type="submit" disabled={busy || !email.includes('@') || captcha.required}
                style={{ width: '100%', background: 'oklch(22% 0.06 265)', color: '#fff', border: 'none', borderRadius: 10, padding: '13px 0', fontWeight: 600, fontSize: 14, cursor: busy ? 'wait' : 'pointer', fontFamily: "'Plus Jakarta Sans', sans-serif", opacity: busy ? 0.72 : 1, transition: 'opacity 0.15s' }}
              >
                {busy ? 'Sending…' : 'Send login link'}
              </button>
            </form>
          )}
          {/* Admin signup UI removed: admins are added by manually inserting
              a row into public.admin_users. */}
        </div>

        <div style={{ marginTop: 28, fontSize: 12, color: 'oklch(65% 0.03 265)' }}>
          Admin access only.&nbsp;
          <button onClick={onBack} style={{ background: 'none', border: 'none', color: 'oklch(44% 0.08 265)', cursor: 'pointer', fontSize: 12, textDecoration: 'underline', fontFamily: "'Plus Jakarta Sans', sans-serif" }}>Return to site</button>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { AdminLogin });
