// Admin Login Gate — same visual language as CodeGate but amber accent.
// Handles three states:
//   1. login        — email + password (+ optional TOTP) form
//   2. enroll-show  — show TOTP QR code after first login attempt
//   3. enroll-done  — confirm TOTP enrollment then back to login

const AdminGate = ({ onSuccess, onBack }) => {
  const [step, setStep] = React.useState('login');         // login | enroll-show | enroll-done
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [totp, setTotp] = React.useState('');
  const [error, setError] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);
  const [rateLimited, setRateLimited] = React.useState(false);
  const [qrData, setQrData] = React.useState(null);        // { secret, keyUri, qrDataUrl }
  const emailRef = React.useRef(null);

  React.useEffect(() => { emailRef.current?.focus(); }, []);

  const submit = async () => {
    if (submitting || rateLimited) return;
    setError('');
    if (!email.includes('@') || password.length < 8) {
      setError('Enter a valid email and password (min 8 chars).');
      return;
    }
    setSubmitting(true);
    try {
      const res = await tmApi.admin.login(email.trim().toLowerCase(), password, totp || undefined);
      // Success
      onSuccess({ email: res.admin?.email || email, role: res.admin?.role || 'super' });
    } catch (e) {
      const code = e.code || 'http_error';
      if (code === 'rate_limited') {
        setRateLimited(true);
        setError('Too many login attempts. Wait 15 minutes and try again.');
        setTimeout(() => setRateLimited(false), 15 * 60 * 1000);
      } else if (code === 'invalid_credentials') {
        // Single failure path — backend collapses all rejections (wrong
        // password, wrong TOTP, not enrolled) into this one code so the
        // response can't be used as a password-cracked oracle.
        setError('Invalid email or password.');
        setTotp('');
      } else {
        setError(e.message || 'Login failed.');
      }
    } finally {
      setSubmitting(false);
    }
  };

  const confirmEnroll = async () => {
    if (submitting) return;
    if (!/^\d{6}$/.test(totp)) {
      setError('TOTP must be exactly 6 digits.');
      return;
    }
    setSubmitting(true);
    setError('');
    try {
      await tmApi.admin.confirm2fa(email.trim().toLowerCase(), password, totp);
      // Now log in for real
      const res = await tmApi.admin.login(email.trim().toLowerCase(), password, totp);
      onSuccess({ email: res.admin?.email || email, role: res.admin?.role || 'super' });
    } catch (e) {
      setError(e.message || 'Enrollment failed.');
    } finally {
      setSubmitting(false);
    }
  };

  // Explicit first-time enrollment — invoked manually via the "Set up 2FA"
  // link. The login endpoint no longer reveals "totp_enrollment_required",
  // so admins must opt into enrollment here on their first sign-in.
  const startEnroll = async () => {
    if (!email.includes('@') || password.length < 8) {
      setError('Enter your email + password first, then click Set up 2FA.');
      return;
    }
    setError(''); setSubmitting(true);
    try {
      const start = await tmApi.admin.start2fa(email.trim().toLowerCase(), password);
      setQrData(start);
      setStep('enroll-show');
      setTotp('');
    } catch (e) {
      // Backend collapses all rejection paths (wrong creds, already enrolled)
      // into invalid_credentials. If you're already enrolled, just use the
      // regular Sign in form — don't click Set up 2FA.
      const c = e.code || '';
      if (c === 'invalid_credentials') {
        setError('Invalid email or password (or already enrolled — use Sign in instead).');
      } else if (c === 'rate_limited') {
        setError('Too many attempts. Wait 15 minutes.');
      } else {
        setError(e.message || 'Could not start 2FA enrollment.');
      }
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div style={{ minHeight: '100vh', background: '#0A0A0A', color: '#EDEDED', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 24, fontFamily: "'Geist', system-ui, sans-serif", position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0, backgroundImage: 'linear-gradient(#1a1a1a 1px, transparent 1px), linear-gradient(90deg, #1a1a1a 1px, transparent 1px)', backgroundSize: '48px 48px', opacity: 0.4, maskImage: 'radial-gradient(ellipse at center, black 0%, transparent 70%)' }} />

      <div style={{ position: 'relative', width: '100%', maxWidth: 460, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 36 }}>
          <div style={{ width: 22, height: 22, borderRadius: 4, background: '#F59E0B', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: "'JetBrains Mono', monospace", fontSize: 12, fontWeight: 700, color: '#0A0A0A' }}>A</div>
          <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 14, letterSpacing: '0.18em', color: '#EDEDED' }}>ADMIN<span style={{ color: '#F59E0B' }}>·</span>CTL</div>
        </div>

        <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: '#565656', letterSpacing: '0.2em', marginBottom: 18, display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#F59E0B', boxShadow: '0 0 8px #F59E0B', animation: 'pulse 2s ease-in-out infinite' }} />
          <span>RESTRICTED · ADMINS ONLY</span>
        </div>

        {step === 'login' && (
          <>
            <h1 style={{ fontSize: 28, fontWeight: 500, letterSpacing: '-0.02em', margin: '0 0 12px 0', textAlign: 'center' }}>Admin sign-in</h1>
            <p style={{ fontSize: 13, color: '#8A8A8A', margin: '0 0 28px 0', textAlign: 'center', lineHeight: 1.5 }}>Email + password + 6-digit TOTP code from your authenticator app.</p>

            <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 8 }}>
              <input
                ref={emailRef}
                type="email"
                value={email}
                onChange={(e) => { setEmail(e.target.value); setError(''); }}
                onKeyDown={(e) => e.key === 'Enter' && submit()}
                placeholder="admin@example.com"
                disabled={submitting || rateLimited}
                autoComplete="email"
                style={inputStyle(error && !rateLimited && !email.includes('@'))}
              />
              <input
                type="password"
                value={password}
                onChange={(e) => { setPassword(e.target.value); setError(''); }}
                onKeyDown={(e) => e.key === 'Enter' && submit()}
                placeholder="password"
                disabled={submitting || rateLimited}
                autoComplete="current-password"
                style={inputStyle(false)}
              />
              <input
                type="text"
                inputMode="numeric"
                pattern="[0-9]{6}"
                maxLength={6}
                value={totp}
                onChange={(e) => { setTotp(e.target.value.replace(/\D/g, '').slice(0, 6)); setError(''); }}
                onKeyDown={(e) => e.key === 'Enter' && submit()}
                placeholder="6-digit TOTP (leave blank on first login)"
                disabled={submitting || rateLimited}
                autoComplete="one-time-code"
                style={{ ...inputStyle(false), letterSpacing: totp ? '0.4em' : 'normal', textAlign: totp ? 'center' : 'left' }}
              />
            </div>

            <button
              onClick={submit}
              disabled={submitting || rateLimited}
              style={amberBtn(submitting || rateLimited)}
              onMouseEnter={(e) => !submitting && !rateLimited && (e.target.style.background = '#d88a09')}
              onMouseLeave={(e) => (e.target.style.background = '#F59E0B')}
            >
              {submitting ? 'Verifying…' : 'Sign in'} <IconArrow size={14} stroke="#0A0A0A" />
            </button>

            {error && (
              <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: rateLimited ? '#F59E0B' : '#DC2626', marginTop: 14, display: 'flex', alignItems: 'center', gap: 6, textAlign: 'center' }}>
                <IconAlert size={12} stroke={rateLimited ? '#F59E0B' : '#DC2626'} /> {error}
              </div>
            )}

            <div style={{ marginTop: 28, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
              <button
                onClick={startEnroll}
                disabled={submitting || rateLimited}
                style={{
                  background: 'none', border: '1px dashed #5c3e08', cursor: 'pointer',
                  color: '#F59E0B', fontSize: 11, fontFamily: "'JetBrains Mono', monospace",
                  letterSpacing: '0.12em', padding: '8px 14px', borderRadius: 4,
                }}
              >
                FIRST TIME? · SET UP 2FA →
              </button>
              <button onClick={onBack} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#565656', fontSize: 11, fontFamily: "'JetBrains Mono', monospace", letterSpacing: '0.1em', padding: '6px 10px', borderRadius: 4 }}>
                ← back to user gate
              </button>
            </div>
          </>
        )}

        {step === 'enroll-show' && qrData && (
          <>
            <h1 style={{ fontSize: 24, fontWeight: 500, letterSpacing: '-0.02em', margin: '0 0 8px 0', textAlign: 'center' }}>Enroll TOTP</h1>
            <p style={{ fontSize: 13, color: '#8A8A8A', margin: '0 0 24px 0', textAlign: 'center', lineHeight: 1.5 }}>
              First login — scan with Google Authenticator / Authy / 1Password,<br/>then enter the 6-digit code below.
            </p>

            <div style={{ background: '#EDEDED', padding: 14, borderRadius: 8, marginBottom: 16 }}>
              <img src={qrData.qrDataUrl} alt="TOTP QR" style={{ display: 'block', width: 200, height: 200 }} />
            </div>

            <details style={{ width: '100%', marginBottom: 18 }}>
              <summary style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: '#8A8A8A', cursor: 'pointer', letterSpacing: '0.1em' }}>Can't scan? Show secret manually</summary>
              <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: '#EDEDED', background: '#141414', border: '1px solid #262626', padding: '8px 10px', borderRadius: 4, wordBreak: 'break-all', marginTop: 8 }}>
                {qrData.secret}
              </div>
            </details>

            <input
              type="text"
              inputMode="numeric"
              pattern="[0-9]{6}"
              maxLength={6}
              value={totp}
              onChange={(e) => { setTotp(e.target.value.replace(/\D/g, '').slice(0, 6)); setError(''); }}
              onKeyDown={(e) => e.key === 'Enter' && confirmEnroll()}
              placeholder="6-digit code"
              autoFocus
              style={{ ...inputStyle(false), letterSpacing: totp ? '0.4em' : 'normal', textAlign: 'center', fontSize: 22 }}
            />

            <button
              onClick={confirmEnroll}
              disabled={submitting}
              style={amberBtn(submitting)}
            >
              {submitting ? 'Confirming…' : 'Confirm and sign in'}
            </button>

            {error && (
              <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: '#DC2626', marginTop: 14, display: 'flex', alignItems: 'center', gap: 6 }}>
                <IconAlert size={12} stroke="#DC2626" /> {error}
              </div>
            )}
          </>
        )}

        <div style={{ position: 'absolute', bottom: -120, fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: '#404040', display: 'flex', gap: 20 }}>
          <span>v0.4.2-admin</span>
          <span>·</span>
          <span>2FA mandatory</span>
          <span>·</span>
          <span>rate-limited</span>
        </div>
      </div>
    </div>
  );
};

const inputStyle = (hasErr) => ({
  width: '100%',
  background: '#141414',
  border: `1px solid ${hasErr ? '#DC2626' : '#262626'}`,
  color: '#EDEDED',
  fontFamily: "'JetBrains Mono', monospace",
  fontSize: 14,
  padding: '13px 16px',
  borderRadius: 6,
  outline: 'none',
  boxSizing: 'border-box',
  transition: 'border-color 150ms',
});

const amberBtn = (disabled) => ({
  width: '100%',
  marginTop: 12,
  background: '#F59E0B',
  color: '#0A0A0A',
  border: 'none',
  padding: '13px 18px',
  borderRadius: 6,
  fontFamily: "'Geist', system-ui, sans-serif",
  fontSize: 14,
  fontWeight: 600,
  letterSpacing: '0.02em',
  cursor: disabled ? 'not-allowed' : 'pointer',
  opacity: disabled ? 0.5 : 1,
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  gap: 8,
  transition: 'background 150ms ease',
});

window.AdminGate = AdminGate;
