/* global React */
// auth.jsx — Forgot password, Reset password, 2FA screens + enrollment modal
// All async auth functions assume window.__sb is a configured Supabase client.

const { useState: useAuthState, useEffect: useAuthEffect, useRef: useAuthRef } = React;

// ── Shared card shell (matches LoginScreen visual) ────────────────────────────
function AuthCard({ title, subtitle, children }) {
  return (
    <div style={{ position: 'fixed', inset: 0, overflow: 'hidden', fontFamily: 'Inter, sans-serif' }}>
      <video autoPlay muted loop playsInline
        style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', zIndex: 0 }}>
        <source src="assets/videos/bg.mp4" type="video/mp4" />
        <source src="assets/videos/bg.webm" type="video/webm" />
      </video>
      <div style={{ position: 'absolute', inset: 0, background: 'rgba(10,14,20,0.68)', zIndex: 1 }} />
      <div style={{ position: 'relative', zIndex: 2, display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%' }}>
        <div style={{
          background: '#111827', border: '1px solid rgba(255,255,255,0.10)',
          borderRadius: 18, padding: '40px', width: 420,
          display: 'flex', flexDirection: 'column', alignItems: 'center',
          boxShadow: '0 32px 80px rgba(0,0,0,0.7)',
        }}>
          <img src="assets/logos/logo.png" alt="Consensio"
            style={{ width: '100%', marginBottom: 16, objectFit: 'contain', borderRadius: 8 }} />
          <div style={{ width: '100%', height: 1, background: 'rgba(255,255,255,0.08)', marginBottom: 24 }} />
          {title && (
            <div style={{ fontSize: 16, fontWeight: 600, color: '#E2E8F0', marginBottom: 6, textAlign: 'center', width: '100%' }}>
              {title}
            </div>
          )}
          {subtitle && (
            <div style={{ fontSize: 13, color: '#94A3B8', marginBottom: 24, textAlign: 'center', lineHeight: 1.6, width: '100%' }}>
              {subtitle}
            </div>
          )}
          {children}
        </div>
      </div>
    </div>
  );
}

const _AI = { // auth input/button shared styles
  input: {
    width: '100%', padding: '10px 14px',
    background: 'rgba(36,48,68,0.8)', border: '1px solid rgba(255,255,255,0.12)',
    borderRadius: 8, color: '#E2E8F0', fontSize: 14,
    fontFamily: 'Inter, sans-serif', outline: 'none', boxSizing: 'border-box',
  },
  primary: {
    width: '100%', padding: '12px', background: '#3B82F6', color: '#fff',
    border: 'none', borderRadius: 9, fontSize: 14, fontWeight: 600,
    cursor: 'pointer', fontFamily: 'Inter, sans-serif', marginBottom: 10, display: 'block',
  },
  ghost: {
    width: '100%', padding: '11px', background: 'transparent',
    border: '1px solid rgba(255,255,255,0.12)', color: '#94A3B8',
    borderRadius: 9, fontSize: 13, fontWeight: 500,
    cursor: 'pointer', fontFamily: 'Inter, sans-serif',
  },
  label: {
    display: 'block', color: '#94A3B8', fontSize: 11,
    fontWeight: 600, letterSpacing: '0.05em', textTransform: 'uppercase', marginBottom: 7,
  },
  error: { color: '#EF4444', fontSize: 12, marginBottom: 10 },
};

// ── Forgot password screen ────────────────────────────────────────────────────
function ForgotPasswordScreen({ onBack }) {
  const [email, setEmail]     = useAuthState('');
  const [sent, setSent]       = useAuthState(false);
  const [loading, setLoading] = useAuthState(false);
  const [error, setError]     = useAuthState('');

  const submit = async e => {
    e.preventDefault();
    if (!window.__sb) {
      setError('Supabase is not configured. Contact your administrator for a password reset.');
      return;
    }
    setLoading(true); setError('');
    const redirectTo = window.location.origin + window.location.pathname;
    const { error: err } = await window.__sb.auth.resetPasswordForEmail(email.trim(), { redirectTo });
    setLoading(false);
    if (err) { setError(err.message); return; }
    setSent(true);
  };

  return (
    <AuthCard
      title={sent ? 'Check your email' : 'Reset password'}
      subtitle={sent ? null : "Enter your account email and we'll send you a secure reset link."}>
      {sent ? (
        <div style={{ width: '100%', textAlign: 'center' }}>
          <div style={{ fontSize: 40, marginBottom: 14 }}>📬</div>
          <div style={{ fontSize: 13, color: '#94A3B8', lineHeight: 1.65, marginBottom: 24 }}>
            Sent to <strong style={{ color: '#E2E8F0' }}>{email}</strong>.<br />
            Click the link in the email to set a new password. It expires in 1 hour.
          </div>
          <button onClick={onBack} style={_AI.ghost}>Back to sign in</button>
        </div>
      ) : (
        <form onSubmit={submit} style={{ width: '100%' }}>
          <div style={{ marginBottom: 16 }}>
            <label style={_AI.label}>Email address</label>
            <input type="email" value={email} onChange={e => setEmail(e.target.value)}
              placeholder="your@email.com" autoFocus required style={_AI.input} />
          </div>
          {error && <p style={_AI.error}>{error}</p>}
          <button type="submit" disabled={loading}
            style={{ ..._AI.primary, opacity: loading ? 0.7 : 1, cursor: loading ? 'not-allowed' : 'pointer' }}>
            {loading ? 'Sending…' : 'Send reset link'}
          </button>
          <button type="button" onClick={onBack} style={_AI.ghost}>Back to sign in</button>
        </form>
      )}
    </AuthCard>
  );
}

// ── Reset password (after clicking the email link) ────────────────────────────
function ResetPasswordScreen({ onDone }) {
  const [pw, setPw]           = useAuthState('');
  const [pw2, setPw2]         = useAuthState('');
  const [showPw, setShowPw]   = useAuthState(false);
  const [loading, setLoading] = useAuthState(false);
  const [error, setError]     = useAuthState('');
  const [done, setDone]       = useAuthState(false);

  const submit = async e => {
    e.preventDefault();
    setError('');
    if (pw.length < 8)  { setError('Password must be at least 8 characters.'); return; }
    if (pw !== pw2)     { setError('Passwords do not match.'); return; }
    setLoading(true);
    const { error: err } = await window.__sb.auth.updateUser({ password: pw });
    setLoading(false);
    if (err) { setError(err.message); return; }
    setDone(true);
    setTimeout(onDone, 2000);
  };

  return (
    <AuthCard
      title={done ? 'Password updated ✓' : 'Set new password'}
      subtitle={done ? 'Redirecting to sign in…' : 'Choose a strong password for your account.'}>
      {done ? (
        <div style={{ fontSize: 44, textAlign: 'center' }}>✓</div>
      ) : (
        <form onSubmit={submit} style={{ width: '100%' }}>
          {[
            { label: 'New password',         value: pw,  set: setPw  },
            { label: 'Confirm new password', value: pw2, set: setPw2 },
          ].map(({ label, value, set }) => (
            <div key={label} style={{ marginBottom: 14 }}>
              <label style={_AI.label}>{label}</label>
              <input type={showPw ? 'text' : 'password'} value={value}
                onChange={e => { set(e.target.value); setError(''); }}
                autoComplete="new-password" required minLength={8} style={_AI.input} />
            </div>
          ))}
          <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', marginBottom: 16 }}>
            <input type="checkbox" checked={showPw} onChange={e => setShowPw(e.target.checked)}
              style={{ accentColor: '#3B82F6' }} />
            <span style={{ fontSize: 12, color: '#94A3B8' }}>Show passwords</span>
          </label>
          {error && <p style={_AI.error}>{error}</p>}
          <button type="submit" disabled={loading || !pw || !pw2}
            style={{ ..._AI.primary, opacity: (!pw || !pw2 || loading) ? 0.7 : 1, cursor: (!pw || !pw2 || loading) ? 'not-allowed' : 'pointer' }}>
            {loading ? 'Updating…' : 'Set new password'}
          </button>
        </form>
      )}
    </AuthCard>
  );
}

// ── Two-factor verification (required on login when 2FA is enrolled) ──────────
function TwoFactorVerifyScreen({ factorId, onVerified, onCancel }) {
  const [code, setCode]       = useAuthState('');
  const [loading, setLoading] = useAuthState(false);
  const [error, setError]     = useAuthState('');
  const inputRef              = useAuthRef(null);

  useAuthEffect(() => { inputRef.current?.focus(); }, []);

  const verify = async e => {
    e.preventDefault();
    if (code.length !== 6) return;
    setLoading(true); setError('');
    try {
      const { data: challenge, error: cErr } = await window.__sb.auth.mfa.challenge({ factorId });
      if (cErr) { setError(cErr.message); setLoading(false); return; }
      const { error: vErr } = await window.__sb.auth.mfa.verify({
        factorId, challengeId: challenge.id, code,
      });
      if (vErr) {
        setError('Invalid code. Check your authenticator app and try again.');
        setCode(''); setLoading(false); return;
      }
      onVerified();
    } catch (ex) {
      setError(ex.message); setLoading(false);
    }
  };

  return (
    <AuthCard title="Two-factor authentication"
      subtitle="Enter the 6-digit code from your authenticator app.">
      <form onSubmit={verify} style={{ width: '100%' }}>
        <div style={{ marginBottom: 16 }}>
          <label style={_AI.label}>Authentication code</label>
          <input
            ref={inputRef} type="text" inputMode="numeric"
            pattern="[0-9]{6}" maxLength={6}
            value={code} onChange={e => { setCode(e.target.value.replace(/\D/g, '')); setError(''); }}
            placeholder="000000" autoComplete="one-time-code"
            style={{
              ..._AI.input,
              textAlign: 'center', fontSize: 28, letterSpacing: '0.4em',
              fontFamily: 'JetBrains Mono, monospace', paddingLeft: 0,
            }}
          />
        </div>
        {error && <p style={_AI.error}>{error}</p>}
        <button type="submit" disabled={code.length !== 6 || loading}
          style={{ ..._AI.primary, opacity: (code.length !== 6 || loading) ? 0.7 : 1, cursor: (code.length !== 6 || loading) ? 'not-allowed' : 'pointer' }}>
          {loading ? 'Verifying…' : 'Verify'}
        </button>
        <button type="button" onClick={onCancel} style={_AI.ghost}>Use a different account</button>
      </form>
    </AuthCard>
  );
}

// ── Two-factor enrollment modal (Settings → Security tab) ─────────────────────
function TwoFactorSetupModal({ onClose, onEnrolled }) {
  const [step, setStep]           = useAuthState('loading');
  // 'loading' | 'scan' | 'verify' | 'done' | 'error' | 'manage'
  const [factorData, setFactorData] = useAuthState(null);
  const [enrolledFactors, setEnrolledFactors] = useAuthState([]);
  const [code, setCode]           = useAuthState('');
  const [error, setError]         = useAuthState('');
  const [loading, setLoading]     = useAuthState(false);

  useAuthEffect(() => {
    if (!window.__sb) { setStep('error'); setError('Supabase is not configured.'); return; }
    window.__sb.auth.mfa.listFactors().then(({ data }) => {
      const totps = data?.totp || [];
      setEnrolledFactors(totps);
      if (totps.length > 0) {
        setStep('manage'); // already has factors — show manage view
        return;
      }
      // Begin enrollment
      window.__sb.auth.mfa.enroll({ factorType: 'totp', friendlyName: 'Consensio' })
        .then(({ data: fd, error: err }) => {
          if (err) { setStep('error'); setError(err.message); return; }
          setFactorData(fd);
          setStep('scan');
        });
    });
  }, []);

  const unenroll = async factorId => {
    const { error: err } = await window.__sb.auth.mfa.unenroll({ factorId });
    if (err) { setError(err.message); return; }
    const updated = enrolledFactors.filter(f => f.id !== factorId);
    setEnrolledFactors(updated);
    if (updated.length === 0) setStep('scan'); // no more factors — start enrollment
  };

  const startEnroll = () => {
    setStep('loading');
    window.__sb.auth.mfa.enroll({ factorType: 'totp', friendlyName: 'Consensio' })
      .then(({ data: fd, error: err }) => {
        if (err) { setStep('error'); setError(err.message); return; }
        setFactorData(fd); setStep('scan');
      });
  };

  const verify = async e => {
    e.preventDefault();
    if (!factorData || code.length !== 6) return;
    setLoading(true); setError('');
    const { data: challenge, error: cErr } = await window.__sb.auth.mfa.challenge({ factorId: factorData.id });
    if (cErr) { setError(cErr.message); setLoading(false); return; }
    const { error: vErr } = await window.__sb.auth.mfa.verify({
      factorId: factorData.id, challengeId: challenge.id, code,
    });
    setLoading(false);
    if (vErr) { setError('Invalid code — check your app and try again.'); setCode(''); return; }
    setStep('done');
    onEnrolled?.();
  };

  return (
    <div style={{ position: 'fixed', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 500 }}
      onClick={onClose}>
      <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(2px)' }} />
      <div style={{
        position: 'relative', background: 'var(--bg-surface)',
        border: '1px solid var(--border-hover)', borderRadius: 14,
        width: 440, overflow: 'hidden', boxShadow: '0 24px 80px rgba(0,0,0,0.5)',
      }} onClick={e => e.stopPropagation()}>
        <div style={{ padding: '16px 20px 14px', borderBottom: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ fontWeight: 600, fontSize: 15 }}>Two-factor authentication (TOTP)</div>
          <button onClick={onClose} style={{ background: 'none', border: 0, cursor: 'pointer', color: 'var(--text-tertiary)', fontSize: 20, lineHeight: 1, padding: 0 }}>×</button>
        </div>

        <div style={{ padding: '24px 24px 28px' }}>
          {step === 'loading' && (
            <div style={{ textAlign: 'center', color: 'var(--text-secondary)', padding: '32px 0' }}>Setting up…</div>
          )}

          {step === 'error' && (
            <div style={{ color: 'var(--accent-danger)', fontSize: 13, padding: '8px 0' }}>{error}</div>
          )}

          {step === 'manage' && (
            <div>
              <div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 16, lineHeight: 1.6 }}>
                You have {enrolledFactors.length} authenticator{enrolledFactors.length !== 1 ? 's' : ''} enrolled. You will be asked for a code on every sign-in.
              </div>
              {enrolledFactors.map(f => (
                <div key={f.id} style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  padding: '12px 14px', background: 'var(--bg-raised)', borderRadius: 8, marginBottom: 8,
                }}>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{f.friendly_name || 'Authenticator app'}</div>
                    <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 }}>
                      Enrolled {new Date(f.created_at).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })}
                    </div>
                  </div>
                  <button onClick={() => unenroll(f.id)}
                    style={{ background: 'none', border: '1px solid var(--border)', borderRadius: 6, padding: '5px 10px', cursor: 'pointer', fontSize: 12, color: 'var(--accent-danger)' }}>
                    Remove
                  </button>
                </div>
              ))}
              {error && <div style={{ color: 'var(--accent-danger)', fontSize: 12, marginTop: 8 }}>{error}</div>}
              <div style={{ marginTop: 16, display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                <button onClick={onClose} className="btn">Close</button>
                <button onClick={startEnroll} className="btn btn-primary">Add authenticator</button>
              </div>
            </div>
          )}

          {step === 'scan' && factorData && (
            <form onSubmit={verify}>
              <div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 16, lineHeight: 1.6 }}>
                <strong style={{ color: 'var(--text-primary)' }}>Step 1</strong> — Scan this QR code with Google Authenticator, Authy, 1Password, or any TOTP app.
              </div>
              <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 16 }}>
                <img src={factorData.totp.qr_code} alt="2FA QR code"
                  style={{ width: 180, height: 180, imageRendering: 'pixelated', borderRadius: 8, background: '#fff', padding: 8 }} />
              </div>
              <div style={{ fontSize: 11, color: 'var(--text-secondary)', textAlign: 'center', marginBottom: 20 }}>
                Can't scan? Enter this key manually:<br />
                <span className="mono" style={{ fontSize: 12, color: 'var(--text-primary)', userSelect: 'all', letterSpacing: '0.05em' }}>
                  {factorData.totp.secret}
                </span>
              </div>
              <div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 10, lineHeight: 1.6 }}>
                <strong style={{ color: 'var(--text-primary)' }}>Step 2</strong> — Enter the 6-digit code your app shows to confirm.
              </div>
              <input
                type="text" inputMode="numeric" pattern="[0-9]{6}" maxLength={6}
                value={code} onChange={e => { setCode(e.target.value.replace(/\D/g, '')); setError(''); }}
                placeholder="000000" autoComplete="one-time-code" autoFocus
                style={{
                  width: '100%', padding: '10px 12px', background: 'var(--bg-base)',
                  border: '1px solid var(--border)', borderRadius: 7,
                  color: 'var(--text-primary)', fontSize: 22, letterSpacing: '0.4em',
                  fontFamily: 'var(--font-mono)', textAlign: 'center', boxSizing: 'border-box', marginBottom: 12,
                }}
              />
              {error && <div style={{ color: 'var(--accent-danger)', fontSize: 12, marginBottom: 10 }}>{error}</div>}
              <div style={{ display: 'flex', gap: 8 }}>
                <button type="button" onClick={onClose} className="btn" style={{ flex: 1 }}>Cancel</button>
                <button type="submit" className="btn btn-primary" style={{ flex: 2 }}
                  disabled={code.length !== 6 || loading}>
                  {loading ? 'Verifying…' : 'Enable 2FA'}
                </button>
              </div>
            </form>
          )}

          {step === 'done' && (
            <div style={{ textAlign: 'center', padding: '8px 0' }}>
              <div style={{ fontSize: 44, marginBottom: 12 }}>✓</div>
              <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 8 }}>2FA enabled</div>
              <div style={{ fontSize: 13, color: 'var(--text-secondary)', lineHeight: 1.6, marginBottom: 20 }}>
                Your account is now protected with two-factor authentication. You'll be asked for a code from your authenticator app on every sign-in.
              </div>
              <button className="btn btn-primary" onClick={onClose}>Done</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ForgotPasswordScreen, ResetPasswordScreen, TwoFactorVerifyScreen, TwoFactorSetupModal });
