/* global React */
// Admin authentication gate — wraps AdminConsole with a login screen.

const { useState: useStateL } = React;

function LoginForm({ onSuccess }) {
  const [username, setUsername] = useStateL("");
  const [password, setPassword] = useStateL("");
  const [error, setError] = useStateL("");
  const [loading, setLoading] = useStateL(false);

  const submit = (e) => {
    e.preventDefault();
    setError("");
    setLoading(true);
    Promise.resolve(window.CSAuth.login(username, password))
      .then(res => {
        setLoading(false);
        if (res.ok) onSuccess();
        else {
          setError(res.error);
          setPassword("");
        }
      })
      .catch(err => {
        setLoading(false);
        setError(err.message || String(err));
        setPassword("");
      });
  };

  return (
    <div className="login-root">
      <form className="login-card" onSubmit={submit}>
        <div className="login-brand">
          <div className="app-brand-mark login-brand-mark">CS</div>
          <div>
            <div className="login-eyebrow">CS Schedule · Admin</div>
            <h1 className="login-title">Sign in</h1>
          </div>
        </div>

        <p className="login-desc">
          The Admin panel is restricted. Enter your administrator credentials to manage the roster.
        </p>

        <label className="login-field">
          <span>Username</span>
          <input
            type="text"
            autoComplete="username"
            autoFocus
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            placeholder="admin"
          />
        </label>

        <label className="login-field">
          <span>Password</span>
          <input
            type="password"
            autoComplete="current-password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="••••••••"
          />
        </label>

        {error && <div className="login-error">⚠ {error}</div>}

        <button type="submit" className="login-btn" disabled={loading || !username || !password}>
          {loading ? "Signing in…" : "Sign in"}
        </button>

        <div className="login-hint">
          Default credentials: <code>admin</code> / <code>admin</code> —
          replace in <code>config.js</code> (or inject from env at deploy time).
        </div>
      </form>
    </div>
  );
}

function AdminGate({ people, setPeople, leadHistory, setLeadHistory }) {
  const [authed, setAuthed] = useStateL(() => window.CSAuth.isAuthed());

  if (!authed) {
    return <LoginForm onSuccess={() => setAuthed(true)} />;
  }
  return (
    <window.AdminConsole
      people={people}
      setPeople={setPeople}
      leadHistory={leadHistory}
      setLeadHistory={setLeadHistory}
      onLogout={() => { window.CSAuth.logout(); setAuthed(false); }}
    />
  );
}

window.LoginForm = LoginForm;
window.AdminGate = AdminGate;
