/* ==================================================================
   Admin login — username + password → {apiBase}/teacher/login.
   ------------------------------------------------------------------
   Rendered by app.jsx when window.APP.NEEDS_LOGIN is true. On success
   we store the bearer token via AppApi.setToken and re-bootstrap.
   Non-admin accounts are rejected here (the cockpit is the admin
   panel; teachers belong on the Teacher app). Name, mark and the
   help line come from window.BRAND (brand.js).
   ================================================================== */

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 B = window.BRAND || {};

  // Self-serve schools (<slug>.<BASE>): offer the Craft & Code account, which
  // signs in on my.<BASE> and comes back through sso.html. The backend says
  // whether this host has it; the default single-school install does not.
  const [sso, setSso] = React.useState(null);
  React.useEffect(() => {
    let live = true;
    fetch(window.AppApi.base + "/sso/config")
      .then(r => (r.ok ? r.json() : null))
      .then(d => { if (live && d && d.enabled && d.my_url && d.slug) setSso(d); })
      .catch(() => {});
    return () => { live = false; };
  }, []);
  const ssoHref = sso
    ? `${sso.my_url}/login?next=${encodeURIComponent(sso.slug)}&target=admin`
    : null;

  const submit = async (e) => {
    e?.preventDefault();
    if (!username.trim() || !password) return;
    setBusy(true); setErr(null);
    try {
      const r = await fetch(window.AppApi.base + "/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 Teacher app.");
      }
      window.AppApi.setToken(data.token);
      onLoggedIn();
    } catch (e) {
      setErr(String(e.message || e));
      setBusy(false);
    }
  };

  return (
    <div className="ui-login">
      {/* min(380px, 100%): a fixed width plus the wrapper's padding overflowed
          a 390px viewport, so the login screen itself scrolled sideways. */}
      <form onSubmit={submit} className="ui-login-card" aria-labelledby="login-title">
        <div className="ui-login-brand">
          <span className="nv-brand-mark" style={{ width: 36, height: 36 }}>
            <window.AppUI.BrandMark size={36}/>
          </span>
          <div style={{ minWidth: 0 }}>
            <div className="nv-brand-name">{B.orgName}</div>
            <div className="nv-brand-sub">{B.appName}</div>
          </div>
        </div>

        <h1 id="login-title" className="ui-login-title">Sign in</h1>
        <p className="ui-login-sub">
          {ssoHref ? "Use your Craft & Code account, or an admin username and password." : "Use your admin username and password."}
        </p>

        {ssoHref && (
          <>
            <a className="btn primary lg" href={ssoHref} style={{ width: "100%", textDecoration: "none" }}>
              Sign in with your Craft &amp; Code account
            </a>
            <div className="ui-login-or" style={{
              display: "flex", alignItems: "center", gap: 10, margin: "18px 0",
              fontSize: 12, color: "var(--ink-4)",
            }}>
              <span style={{ flex: 1, height: 1, background: "var(--line)" }}/>
              or
              <span style={{ flex: 1, height: 1, background: "var(--line)" }}/>
            </div>
          </>
        )}

        <div className="field" style={{ marginBottom: 14 }}>
          <label className="label" htmlFor="login-username">Username</label>
          <input id="login-username" className="input" autoFocus value={username}
            onChange={e => setUsername(e.target.value)} autoComplete="username"/>
        </div>

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

        {err && <div className="ui-alert red" role="alert" style={{ marginTop: 14 }}>{err}</div>}

        <button type="submit" className={ssoHref ? "btn lg" : "btn primary lg"} disabled={busy || !username.trim() || !password}
          style={{ width: "100%", marginTop: 20 }}>
          {busy ? "Signing in…" : "Sign in"}
        </button>

        <p className="ui-login-foot">
          Teachers: use the Teacher app. This panel only accepts admin accounts.
        </p>
        {(B.supportEmail || B.supportPhone) && (
          <p className="ui-login-foot" style={{ marginTop: 6 }}>
            Need help? {[B.supportEmail, B.supportPhone].filter(Boolean).join(" · ")}
          </p>
        )}
        {B.poweredBy && (
          <p className="ui-login-foot" style={{ marginTop: 14, color: "var(--ink-4)" }}>
            Powered by {B.poweredBy}
          </p>
        )}
      </form>
    </div>
  );
};

window.CockpitLogin = CockpitLogin;
