// admin-shared.jsx — auth, login gate, shared icons + Confirm dialog.

const ADMIN_ICONS = {
  plus: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" {...p}><path d="M12 5v14M5 12h14" /></svg>,
  trash: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" /></svg>,
  check: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12l5 5L20 7" /></svg>,
  back: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M19 12H5M12 19l-7-7 7-7" /></svg>,
  logout: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9" /></svg>,
  lock: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="11" width="18" height="11" rx="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" /></svg>,
  inbox: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M22 12h-6l-2 3h-4l-2-3H2M5 4l-3 8v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3-8z" /></svg>,
  users: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M17 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9.5 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75" /></svg>,
  shield: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" /></svg>,
  cal: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="4" width="18" height="18" rx="2" /><path d="M16 2v4M8 2v4M3 10h18" /></svg>,
  doc: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6M8 13h8M8 17h5" /></svg>,
  chev: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M9 18l6-6-6-6" /></svg>,
  search: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="11" cy="11" r="8" /><path d="m21 21-4.35-4.35" /></svg>,
  edit: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 20h9M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z" /></svg>,
  eye: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><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>,
  vote: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M9 12l2 2 4-4M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z" /></svg>,
  info: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="12" r="10" /><path d="M12 16v-4M12 8h.01" /></svg>,
  trophy: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M6 9H4a2 2 0 0 1-2-2V5h4M18 9h2a2 2 0 0 0 2-2V5h-4M6 5h12v6a6 6 0 0 1-12 0V5zM12 17v4M8 21h8" /></svg>
};

// ── Auth ────────────────────────────────────────────────────
function useAuth() {
  const [session, setSession] = React.useState(null);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    // Try to restore session from ATS (which fetches from API)
    if (!window.ATS) { setLoading(false); return; }
    ATS.getSession().then(s => {
      setSession(s);
      setLoading(false);
    }).catch(() => {
      setLoading(false);
    });
  }, []);

  const logout = async () => {
    if (window.ATS) await ATS.clearSession();
    setSession(null);
    window.location.href = 'index.html';
  };

  const login = async (email, name, role, id) => {
    const s = { email, name, role: role || 'staff', id: id || 0, at: Date.now() };
    if (window.ATS) ATS.setSession(s);
    setSession(s);
  };

  return { session, loading, login, logout };
}

function LoginGate({ onLogin }) {
  const [email, setEmail] = React.useState('');
  const [pass, setPass] = React.useState('');
  const [err, setErr] = React.useState('');
  const [loggingIn, setLoggingIn] = React.useState(false);

  const submit = async (e) => {
    e.preventDefault();
    if (!email || !pass) { setErr('Both fields required.'); return; }
    setLoggingIn(true);
    try {
      const res = await fetch('/api/auth/sign-in/email', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password: pass }),
      });
      if (!res.ok) {
        const errData = await res.json().catch(() => ({}));
        setErr(errData.error || 'Invalid credentials');
        setLoggingIn(false);
        return;
      }

      // Fetch fresh session
      const sessionRes = await fetch('/api/auth/session', { credentials: 'include' });
      const sessionData = await sessionRes.json();
      if (!sessionData?.user) { setErr('Could not establish session'); setLoggingIn(false); return; }

      onLogin(
        sessionData.user.email,
        sessionData.user.name,
        sessionData.user.role || 'staff',
        sessionData.user.id
      );
    } catch (e) {
      setErr('Login failed: ' + e.message);
      setLoggingIn(false);
    }
  };

  return (
    <div style={{ minHeight: '100vh', display: 'grid', placeItems: 'center', padding: 24 }}>
      <div className="bg-aurora" />
      <div className="bg-grain" />
      <div className="glass-strong" style={{ width: '100%', maxWidth: 420, padding: 36 }}>
        <div className="admin-tag" style={{ marginBottom: 14 }}>
          <ADMIN_ICONS.lock width="11" height="11" /> Admin access
        </div>
        <h2 style={{ marginBottom: 6 }}>Officer log in</h2>
        <p className="sub" style={{ marginBottom: 24 }}>
          Sign in with your 4wos account.
        </p>
        <form className="form-grid" onSubmit={submit}>
          <div className="form-row">
            <label htmlFor="email">Email</label>
            <input id="email" type="email" required value={email}
            onChange={(e) => setEmail(e.target.value)} placeholder="admin@4wos.com" />
          </div>
          <div className="form-row">
            <label htmlFor="pass">Password</label>
            <input id="pass" type="password" required value={pass}
            onChange={(e) => setPass(e.target.value)} placeholder="••••••••" />
          </div>
          {err &&
          <div style={{ padding: '10px 14px', borderRadius: 10,
            background: 'rgba(248, 113, 113, 0.1)', border: '1px solid rgba(248, 113, 113, 0.3)',
            color: '#fecaca', fontSize: '0.85rem' }}>
              {err}
            </div>
          }
          <button type="submit" className="btn btn-primary modal-submit" disabled={loggingIn}>
            {loggingIn ? 'Signing in…' : 'Log in'}
          </button>
        </form>
      </div>
    </div>
  );
}

// ── Reusable inline modal ───────────────────────────────────
function Confirm({ open, onClose, onConfirm, title = 'Are you sure?', confirmText = 'Confirm',
  children, danger }) {
  return (
    <div className={'scrim' + (open ? ' open' : '')} onMouseDown={(e) => {
      if (e.target === e.currentTarget) onClose();
    }}>
      <div className="modal glass-strong compact">
        <h3 style={{ marginBottom: 12 }}>{title}</h3>
        {children}
        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 16 }}>
          <button className="btn btn-ghost btn-sm" onClick={onClose}>Cancel</button>
          <button className={'btn btn-sm' + (danger ? ' btn-danger' : ' btn-primary')}
            onClick={() => { onConfirm(); onClose(); }}>{confirmText}</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ADMIN_ICONS, useAuth, LoginGate, Confirm });