/* Admin — simple login + view sign-in leads (no mock auth). */
const ADMIN_TOKEN_KEY = 'fp-admin-token';

function AdminScreen() {
  const [token, setToken] = useState(() => sessionStorage.getItem(ADMIN_TOKEN_KEY) || '');
  const [user, setUser] = useState('');
  const [pass, setPass] = useState('');
  const [loginErr, setLoginErr] = useState('');
  const [loginBusy, setLoginBusy] = useState(false);
  const [signins, setSignins] = useState([]);
  const [loadErr, setLoadErr] = useState('');
  const [loading, setLoading] = useState(false);

  async function loadSignins(authToken) {
    setLoading(true);
    setLoadErr('');
    try {
      const res = await fetch('/api/auth/admin/signins', {
        headers: { Authorization: 'Bearer ' + authToken, Accept: 'application/json' },
      });
      const data = await res.json().catch(() => ({}));
      if (res.status === 401) {
        sessionStorage.removeItem(ADMIN_TOKEN_KEY);
        setToken('');
        throw new Error('Session expired — sign in again');
      }
      if (!res.ok) throw new Error(data.error || 'Could not load sign-ins');
      setSignins(data.signins || []);
    } catch (e) {
      setLoadErr(e.message);
      setSignins([]);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    if (token) loadSignins(token);
  }, [token]);

  async function login(e) {
    e.preventDefault();
    setLoginErr('');
    setLoginBusy(true);
    try {
      const res = await fetch('/api/auth/admin/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({ username: user.trim(), password: pass }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || 'Login failed');
      sessionStorage.setItem(ADMIN_TOKEN_KEY, data.token);
      setToken(data.token);
      setPass('');
    } catch (ex) {
      setLoginErr(ex.message || 'Invalid credentials');
    } finally {
      setLoginBusy(false);
    }
  }

  async function logout() {
    if (token) {
      try {
        await fetch('/api/auth/admin/logout', {
          method: 'POST',
          headers: { Authorization: 'Bearer ' + token },
        });
      } catch (_) { /* ignore */ }
    }
    sessionStorage.removeItem(ADMIN_TOKEN_KEY);
    setToken('');
    setSignins([]);
    setUser('');
  }

  if (!token) {
    return (
      <div className="admin-wrap">
        <div className="admin-card">
          <div className="brand-mark" style={{ margin: '0 auto 16px', width: 48, height: 48 }} aria-hidden="true">
            <span className="brand-mark-text">CSP</span>
          </div>
          <h1 className="h1" style={{ textAlign: 'center', marginBottom: 6 }}>Admin Sign In</h1>
          <p className="muted" style={{ textAlign: 'center', marginBottom: 20, fontSize: 14 }}>
            View visitor sign-ins collected after the 10-minute usage gate.
          </p>
          <form onSubmit={login}>
            <label className="label-up">Username</label>
            <input className="key-input gate-input" value={user} onChange={(e) => setUser(e.target.value)} autoComplete="username" />
            <label className="label-up" style={{ marginTop: 12 }}>Password</label>
            <input className="key-input gate-input" type="password" value={pass} onChange={(e) => setPass(e.target.value)} autoComplete="current-password" />
            {loginErr && <div className="gate-err">{loginErr}</div>}
            <button type="submit" className="pill active gate-submit" disabled={loginBusy || !user || !pass}>
              {loginBusy ? 'Signing in…' : 'Sign in'}
            </button>
          </form>
          <p className="muted" style={{ marginTop: 16, fontSize: 12, textAlign: 'center' }}>
            Set <code>ADMIN_USER</code> and <code>ADMIN_PASSWORD</code> in your server environment.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="admin-wrap admin-dash">
      <div className="admin-top">
        <div>
          <h1 className="h1" style={{ marginBottom: 4 }}>Sign-in Leads</h1>
          <p className="muted" style={{ margin: 0 }}>{signins.length} submission{signins.length === 1 ? '' : 's'} stored</p>
        </div>
        <div className="pill-row">
          <button className="pill" onClick={() => loadSignins(token)} disabled={loading}>{loading ? '…' : 'Refresh'}</button>
          <button className="pill" onClick={logout}>Sign out</button>
          <a className="pill" href="/markets">← Back to site</a>
        </div>
      </div>

      {loadErr && <div className="banner err section">{loadErr}</div>}

      <div className="card section" style={{ padding: 0, overflow: 'auto' }}>
        <table className="data-table admin-table">
          <thead>
            <tr>
              <th>When</th>
              <th>Name</th>
              <th>Email</th>
              <th>Phone</th>
              <th>Visitor</th>
            </tr>
          </thead>
          <tbody>
            {signins.length ? signins.map((s) => (
              <tr key={s.id}>
                <td className="mono-num" style={{ fontSize: 12, whiteSpace: 'nowrap' }}>
                  {new Date(s.createdAt).toLocaleString('en-IN', { dateStyle: 'medium', timeStyle: 'short' })}
                </td>
                <td style={{ fontWeight: 600 }}>{s.name}</td>
                <td><a href={'mailto:' + s.email} style={{ color: 'var(--accent)' }}>{s.email}</a></td>
                <td className="mono-num">{s.phone}</td>
                <td className="muted" style={{ fontSize: 11, maxWidth: 120, overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.visitorId || '—'}</td>
              </tr>
            )) : (
              <tr>
                <td colSpan={5} className="muted" style={{ padding: 24, textAlign: 'center' }}>
                  {loading ? 'Loading…' : 'No sign-ins yet. They appear when visitors pass the 10-minute gate.'}
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

Object.assign(window, { AdminScreen });
