/* ==================================================================
   Cockpit login — username + password → /api/teacher/login.
   ------------------------------------------------------------------
   Rendered by app.jsx when window.KX.NEEDS_LOGIN is true. On success
   we store the bearer token via KXApi.setToken and re-bootstrap.
   Non-admin accounts are rejected here (the cockpit is the admin
   panel; teachers belong on the mobile app).
   ================================================================== */

const CockpitLogin = ({ onLoggedIn }) => {
  const [username, setUsername] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);

  const submit = async (e) => {
    e?.preventDefault();
    if (!username.trim() || !password) return;
    setBusy(true); setErr(null);
    try {
      const r = await fetch("/api/teacher/login", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ username: username.trim(), password }),
      });
      const data = await r.json().catch(() => ({}));
      if (!r.ok) throw new Error(data?.error || `login failed (${r.status})`);
      if (data?.teacher?.role !== "admin") {
        throw new Error("This panel is admin-only. Teachers should use the mobile app.");
      }
      window.KXApi.setToken(data.token);
      onLoggedIn();
    } catch (e) {
      setErr(String(e.message || e));
      setBusy(false);
    }
  };

  return (
    <div style={{
      position: "fixed", inset: 0, display: "grid", placeItems: "center",
      background: "var(--bg-0)", padding: 16,
    }}>
      {/* 380px + the wrapper's padding overflowed a 390px viewport, so the
          login screen itself scrolled sideways. Cap against the padding. */}
      <form onSubmit={submit} style={{
        width: "min(380px, 100%)",
        background: "#fff",
        border: "1px solid var(--line-strong)",
        borderRadius: 24, padding: 28,
        boxShadow: "var(--shadow-pop)",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 20 }}>
          {/* Near-black, matching the cockpit's brand mark. Not --accent: that
              is user-tintable and a pale tint leaves the "K" unreadable. */}
          <div style={{
            width: 40, height: 40, borderRadius: 12,
            background: "var(--ink-btn)", color: "#fff",
            display: "grid", placeItems: "center", fontWeight: 700, fontSize: 17,
          }}>K</div>
          <div>
            <div style={{ color: "var(--ink-0)", fontSize: 17, fontWeight: 700, letterSpacing: "-0.3px" }}>Adarshabani</div>
            <div className="muted" style={{ fontSize: 10, fontWeight: 600, letterSpacing: "1.4px", textTransform: "uppercase" }}>
              Admin Cockpit
            </div>
          </div>
        </div>

        <label style={{ display: "block", color: "var(--ink-2)", fontSize: 11, marginBottom: 4 }}>Username</label>
        <input className="input" autoFocus value={username} onChange={e => setUsername(e.target.value)}
          autoComplete="username" style={{ width: "100%", marginBottom: 12 }}/>

        <label style={{ display: "block", color: "var(--ink-2)", fontSize: 11, marginBottom: 4 }}>Password</label>
        <input className="input" type="password" value={password} onChange={e => setPassword(e.target.value)}
          autoComplete="current-password" style={{ width: "100%" }}/>

        {err && (
          <div style={{
            marginTop: 12, padding: "8px 10px",
            background: "var(--red-bg)", border: "1px solid rgba(229,72,77,0.3)",
            borderRadius: 10, color: "var(--red)", fontSize: 12,
          }}>{err}</div>
        )}

        <button type="submit" className="btn primary" disabled={busy || !username.trim() || !password}
          style={{ width: "100%", justifyContent: "center", marginTop: 16, padding: "8px 12px" }}>
          {busy ? "Signing in…" : "Sign in"}
        </button>

        <p className="muted" style={{ fontSize: 11, marginTop: 14, textAlign: "center" }}>
          Teachers: use the mobile app. This panel only accepts admin accounts.
        </p>
      </form>
    </div>
  );
};

window.CockpitLogin = CockpitLogin;
