// admin-auth.jsx — admin login gate.
// Credentials are verified server-side by the admin-auth-verify edge
// function (bcrypt compare against the admin_users table). Loaded after
// admin-shell.jsx (needs window.Icon) and before admin-main.jsx.
const { useState: useStateAuth } = React;
const AuthIcon = window.Icon;

const ADMIN_SESSION_KEY = 'wf_admin_session';

const AdminAuth = {
  get() {
    try { const r = localStorage.getItem(ADMIN_SESSION_KEY); return r ? JSON.parse(r) : null; }
    catch (e) { return null; }
  },
  set(user) { try { localStorage.setItem(ADMIN_SESSION_KEY, JSON.stringify(user)); } catch (e) {} },
  clear() { try { localStorage.removeItem(ADMIN_SESSION_KEY); } catch (e) {} },
  async login(email, password) {
    const SUPABASE_URL = 'https://iwvlmpgeodctctmaacja.supabase.co';
    const SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Iml3dmxtcGdlb2RjdGN0bWFhY2phIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjYwMzY3MTUsImV4cCI6MjA4MTYxMjcxNX0.hMs9OGPTdhPAs0lSKzDWE1Cc-K27NoW11--niolkoWY';
    try {
      const res = await fetch(`${SUPABASE_URL}/functions/v1/admin-auth-verify`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${SUPABASE_ANON_KEY}` },
        body: JSON.stringify({ email: String(email).trim().toLowerCase(), password }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.valid) {
        return { error: data.error || 'Invalid email or password.' };
      }
      AdminAuth.set(data.user);
      return { user: data.user };
    } catch (e) {
      return { error: 'Login failed — check your connection and try again.' };
    }
  },
};

function LoginScreen({ onSuccess }) {
  const [email, setEmail]       = useStateAuth('');
  const [password, setPassword] = useStateAuth('');
  const [error, setError]       = useStateAuth('');
  const [busy, setBusy]         = useStateAuth(false);

  const submit = async (e) => {
    e.preventDefault();
    if (busy || !email || !password) return;
    setBusy(true); setError('');
    const res = await AdminAuth.login(email, password);
    setBusy(false);
    if (res.error) setError(res.error);
    else onSuccess(res.user);
  };

  const field = {
    width: '100%', padding: '11px 13px', border: '1px solid #E5E7EB', borderRadius: 10,
    fontFamily: 'inherit', fontSize: 14, color: '#1A2B3B', outline: 'none', background: '#fff',
  };
  const label = { display: 'block', fontSize: 11, fontWeight: 800, color: '#9CA3AF',
    textTransform: 'uppercase', letterSpacing: '0.07em', marginBottom: 6 };

  return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#F9FAFB', padding: 24 }}>
      <form onSubmit={submit} style={{ width: 'min(380px,100%)', background: '#fff', border: '1px solid #E5E7EB', borderRadius: 18, padding: '34px 32px', boxShadow: '0 16px 48px rgba(16,24,40,0.08)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 26 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: '#F97316', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <AuthIcon name="Zap" size={18} color="#fff" fill="#fff" />
          </div>
          <div>
            <div style={{ fontSize: 16, fontWeight: 900, color: '#1A2B3B' }}>WiseFunnel Admin</div>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#9CA3AF' }}>Sign in to continue</div>
          </div>
        </div>

        <div style={{ marginBottom: 14 }}>
          <label style={label}>Email</label>
          <input type="email" value={email} onChange={e => setEmail(e.target.value)} autoFocus
            style={field} placeholder="you@wisefunnel.io" />
        </div>
        <div style={{ marginBottom: 18 }}>
          <label style={label}>Password</label>
          <input type="password" value={password} onChange={e => setPassword(e.target.value)}
            style={field} placeholder="••••••••••" />
        </div>

        {error && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 7, background: '#FFF1F2', border: '1px solid #FECDD3', color: '#F43F5E', fontSize: 12, fontWeight: 600, padding: '9px 12px', borderRadius: 9, marginBottom: 16 }}>
            <AuthIcon name="ShieldAlert" size={14} color="#F43F5E" />{error}
          </div>
        )}

        <button type="submit" disabled={busy || !email || !password}
          style={{ width: '100%', padding: '12px', borderRadius: 11, border: 'none', cursor: (busy || !email || !password) ? 'not-allowed' : 'pointer',
            background: '#1A2B3B', color: '#fff', fontFamily: 'inherit', fontSize: 14, fontWeight: 800,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, opacity: (busy || !email || !password) ? 0.55 : 1 }}>
          {busy ? <><AuthIcon name="Loader" size={15} color="#fff" /> Signing in…</> : 'Sign In'}
        </button>

        <div style={{ marginTop: 18, textAlign: 'center', fontSize: 10, fontWeight: 700, color: '#D1D5DB', textTransform: 'uppercase', letterSpacing: '0.12em' }}>
          Encrypted Admin Access
        </div>
      </form>
    </div>
  );
}

Object.assign(window, { AdminAuth, LoginScreen });
