/* ============================================================
   Login screen — username + password against /api/login
   ============================================================ */

function Login({ onSuccess }) {
  const Ic = window.Icons;
  const [user, setUser] = React.useState("");
  const [pw, setPw] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState("");

  async function submit(e) {
    e.preventDefault();
    if (!user.trim() || !pw) return;
    setBusy(true);
    setError("");
    try {
      const res = await fetch("/api/login", {
        method: "POST",
        headers: { "content-type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ username: user.trim(), password: pw }),
      });
      if (!res.ok) {
        setError("Wrong username or password");
        setPw("");
        setBusy(false);
        return;
      }
      const me = await res.json();
      onSuccess(me);
    } catch (err) {
      setError("Couldn't reach the server");
      setBusy(false);
    }
  }

  return (
    <div className="login">
      <div className="login-card">
        <div className="login-mark">
          <div className="mirrorball spinning" style={{ width: "100%", height: "100%" }} />
        </div>
        <h1 className="login-title">DISCO<em>·</em>THÈQUE</h1>
        <p className="login-sub">Members only · since '78</p>

        <form className="login-form" onSubmit={submit}>
          <input
            className="login-input"
            type="text"
            placeholder="Username"
            autoCapitalize="none"
            autoCorrect="off"
            spellCheck={false}
            value={user}
            onChange={(e) => { setUser(e.target.value); setError(""); }}
            autoFocus
          />
          <input
            className={"login-input " + (error ? "error" : "")}
            type="password"
            placeholder="Password"
            value={pw}
            onChange={(e) => { setPw(e.target.value); setError(""); }}
          />
          <button className="login-btn" type="submit" disabled={busy}>
            {busy ? "Checking…" : "Step Inside"}
          </button>
          {error && (
            <div style={{ color: "var(--pink)", fontSize: 12, marginTop: 4, letterSpacing: "0.05em" }}>
              {error}
            </div>
          )}
        </form>

        <p className="login-hint">No account? Ask the host.</p>
      </div>
    </div>
  );
}

Object.assign(window, { Login });
