// tnych-login.jsx — Admin login screen (server-side auth + server-issued captcha)
const { useState: useLoginState, useEffect, useCallback } = React;

function CaptchaImage({ png }) {
  if (!png) {
    return <div style={{ width: 290, height: 92, borderRadius: 6, background: 'rgba(11,17,29,0.9)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, color: 'var(--text-dim)' }}>loading…</div>;
  }
  return (
    <img
      src={`data:image/png;base64,${png}`}
      alt="captcha"
      width={290} height={92}
      draggable={false}
      style={{ borderRadius: 6, display: 'block', userSelect: 'none', maxWidth: '100%' }}
    />
  );
}

function Login({ domain, onLogin, onBack }) {
  const [step,    setStep]    = useLoginState('creds');       // 'creds' | 'mfa'
  const [email,   setEmail]   = useLoginState('');
  const [pass,    setPass]    = useLoginState('');
  const [err,     setErr]     = useLoginState('');
  const [loading, setLoading] = useLoginState(false);
  const [showPw,  setShowPw]  = useLoginState(false);
  const [captcha, setCaptcha] = useLoginState(null);          // { id, svg }
  const [captchaInput, setCaptchaInput] = useLoginState('');
  const [mfaCode, setMfaCode] = useLoginState('');

  const loadCaptcha = useCallback(() => {
    setCaptcha(null);
    setCaptchaInput('');
    fetch('/api/auth/captcha')
      .then(r => r.json())
      .then(setCaptcha)
      .catch(() => setErr('Could not reach the server for a captcha.'));
  }, []);

  useEffect(() => { loadCaptcha(); }, [loadCaptcha]);

  const startOver = () => {
    setStep('creds'); setMfaCode(''); setPass(''); setErr('');
    loadCaptcha();
  };

  const submit = async (e) => {
    e.preventDefault();
    if (loading) return;
    if (!email || !pass) { setErr('Please enter your credentials.'); return; }
    if (!captcha || !captchaInput.trim()) { setErr('Please answer the captcha.'); return; }
    setErr(''); setLoading(true);
    try {
      const r = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: email.trim(),
          password: pass,
          captchaId: captcha.id,
          captchaAnswer: captchaInput.trim(),
        }),
      });
      const data = await r.json().catch(() => ({}));
      if (r.ok && data.mfaRequired) { setStep('mfa'); setErr(''); return; }
      if (r.ok) { onLogin(); return; } // MFA trust cookie still valid — no code needed
      setErr(data.error || 'Login failed.');
      loadCaptcha(); // captchas are single-use — always get a fresh one after a failure
    } catch (e2) {
      setErr('Could not reach the server.');
    } finally {
      setLoading(false);
    }
  };

  const submitMfa = async (e) => {
    e.preventDefault();
    if (loading) return;
    const code = mfaCode.trim();
    if (!/^\d{6}$/.test(code)) { setErr('Enter the 6-digit code from your authenticator app.'); return; }
    setErr(''); setLoading(true);
    try {
      const r = await fetch('/api/auth/mfa', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ code }),
      });
      const data = await r.json().catch(() => ({}));
      if (r.ok) { onLogin(); return; }
      setErr(data.error || 'Verification failed.');
      setMfaCode('');
      if (r.status === 401 || r.status === 429) startOver(); // pending login expired or burned
    } catch (e2) {
      setErr('Could not reach the server.');
    } finally {
      setLoading(false);
    }
  };

  const EyeIcon = showPw
    ? <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><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.94M9.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.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
    : <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><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>;

  return (
    <div style={{
      minHeight: '100dvh',
      background: 'var(--bg)',
      backgroundImage: 'radial-gradient(ellipse 70% 50% at 50% -5%, oklch(42% 0.10 190 / 0.13) 0%, transparent 60%)',
      display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center',
      padding: '20px',
    }}>
      {/* Logo */}
      <div style={{ textAlign:'center', marginBottom:32, animation:'fadeUp 0.35s ease both' }}>
        <div style={{ fontSize:20, fontWeight:700, letterSpacing:'-0.02em',
          textShadow:'0 0 28px var(--accent-glow), 0 0 60px var(--accent-glow)' }}>{domain}</div>
        <div style={{ fontSize:11, color:'var(--text-dim)', marginTop:4, letterSpacing:'0.08em', textTransform:'uppercase', fontWeight:600 }}>
          {step === 'mfa' ? 'Two-Factor Verification' : 'Admin Access'}
        </div>
      </div>

      {/* MFA card */}
      {step === 'mfa' && (
      <form onSubmit={submitMfa} style={{
        background:'var(--surface)', border:'1px solid var(--border)',
        borderRadius:18, padding:'28px 30px',
        width:'100%', maxWidth:360,
        animation:'fadeUp 0.35s ease both',
        boxShadow:'0 20px 60px oklch(0% 0 0 / 0.3)',
      }}>
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <p style={{ fontSize:13, color:'var(--text-muted)', lineHeight:1.6 }}>
            Enter the 6-digit code from your authenticator app for{' '}
            <strong style={{ color:'var(--text)', fontWeight:600 }}>{email.trim()}</strong>.
          </p>
          <input className="input" type="text" inputMode="numeric" autoComplete="one-time-code"
            value={mfaCode}
            onChange={e => setMfaCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
            placeholder="000000" autoFocus
            style={{ fontSize:22, letterSpacing:'0.45em', textAlign:'center', fontVariantNumeric:'tabular-nums' }} />
          {err && (
            <p style={{ fontSize:12, color:'var(--danger)', background:'oklch(62% 0.17 25 / 0.08)', borderRadius:6, padding:'8px 10px' }}>{err}</p>
          )}
          <button className="btn btn-primary" type="submit" disabled={loading || mfaCode.length !== 6}
            style={{ width:'100%', justifyContent:'center', marginTop:4, padding:'10px' }}>
            {loading
              ? <><span style={{ width:14, height:14, borderRadius:'50%', border:'2px solid currentColor', borderTopColor:'transparent', animation:'spin 0.7s linear infinite', display:'inline-block' }}/> Verifying…</>
              : 'Verify →'}
          </button>
          <button type="button" onClick={startOver} style={{
            background:'none', border:'none', cursor:'pointer', fontSize:12,
            color:'var(--text-dim)', fontFamily:'inherit', padding:0, marginTop:2,
          }}>← start over</button>
        </div>
      </form>
      )}

      {/* Credentials card */}
      {step === 'creds' && (
      <form onSubmit={submit} style={{
        background:'var(--surface)', border:'1px solid var(--border)',
        borderRadius:18, padding:'28px 30px',
        width:'100%', maxWidth:360,
        animation:'fadeUp 0.35s ease 0.08s both',
        boxShadow:'0 20px 60px oklch(0% 0 0 / 0.3)',
      }}>
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <div>
            <label style={{ fontSize:12, color:'var(--text-muted)', fontWeight:600, display:'block', marginBottom:6, letterSpacing:'0.02em' }}>Email</label>
            <input className="input" type="email" autoComplete="email"
              value={email} onChange={e => setEmail(e.target.value)}
              placeholder="noneya@business.gay" />
          </div>
          <div>
            <label style={{ fontSize:12, color:'var(--text-muted)', fontWeight:600, display:'block', marginBottom:6, letterSpacing:'0.02em' }}>Password</label>
            <div style={{ position:'relative' }}>
              <input className="input" type={showPw ? 'text' : 'password'} autoComplete="current-password"
                value={pass} onChange={e => setPass(e.target.value)}
                placeholder="••••••••••" style={{ paddingRight:40 }} />
              <button type="button" onClick={() => setShowPw(v => !v)} style={{
                position:'absolute', right:10, top:'50%', transform:'translateY(-50%)',
                background:'none', border:'none', cursor:'pointer',
                color:'var(--text-dim)', padding:2, display:'flex', alignItems:'center',
              }}>{EyeIcon}</button>
            </div>
          </div>
          {err && (
            <p style={{ fontSize:12, color:'var(--danger)', background:'oklch(62% 0.17 25 / 0.08)', borderRadius:6, padding:'8px 10px' }}>{err}</p>
          )}
          <button className="btn btn-primary" type="submit" disabled={loading}
            style={{ width:'100%', justifyContent:'center', marginTop:4, padding:'10px' }}>
            {loading
              ? <><span style={{ width:14, height:14, borderRadius:'50%', border:'2px solid currentColor', borderTopColor:'transparent', animation:'spin 0.7s linear infinite', display:'inline-block' }}/> Signing in…</>
              : 'Sign in →'}
          </button>
          <div style={{ background:'var(--surface-hi)', border:'1px solid var(--border)', borderRadius:10, padding:12, marginTop:12 }}>
            <label style={{ fontSize:11, color:'var(--text-muted)', fontWeight:600, display:'block', marginBottom:8, letterSpacing:'0.02em', textTransform:'uppercase' }}>Verification</label>
            <div style={{ display:'flex', gap:8, alignItems:'flex-end' }}>
              <div style={{ flex:1, display:'flex', flexDirection:'column', gap:8 }}>
                <CaptchaImage png={captcha && captcha.png} />
                <input className="input input-sm" type="text" value={captchaInput}
                  onChange={e => setCaptchaInput(e.target.value)}
                  autoComplete="off" autoCapitalize="characters" spellCheck={false}
                  placeholder="Enter the characters" style={{ fontSize:13, textTransform:'uppercase' }} />
              </div>
              <button type="button" onClick={loadCaptcha} title="New captcha"
                style={{ background:'none', border:'none', cursor:'pointer', color:'var(--text-dim)', padding:6, display:'flex', alignItems:'center', fontSize:18, marginBottom:4 }}>↻</button>
            </div>
          </div>
        </div>
      </form>
      )}

      <button onClick={onBack} style={{
        marginTop:18, background:'none', border:'none', cursor:'pointer',
        fontSize:12, color:'var(--text-dim)', fontFamily:'inherit', transition:'color 0.16s',
      }}
        onMouseEnter={e => e.currentTarget.style.color='var(--text-muted)'}
        onMouseLeave={e => e.currentTarget.style.color='var(--text-dim)'}>
        ← back to {domain}
      </button>
    </div>
  );
}

Object.assign(window, { Login });
