/* P.E.S.T Web App — Login (real auth via nc-proxy.php) */
function Login({ onLoggedIn, onGuest }) {
  const store = useStore();
  const [u, setU] = useState("");
  const [p, setP] = useState("");
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    if (!u.trim() || !p.trim()) { setErr("Enter your issued username and password."); return; }
    setErr(""); setBusy(true);
    const r = await store.login(u.trim(), p);
    setBusy(false);
    if (r.ok) { onLoggedIn && onLoggedIn(); }
    else { setErr(r.error); }
  };

  return (
    <div className="login">
      <div className="app-bg"></div>
      <div className="app-grid"></div>
      <form className="login-card login-glitch" onSubmit={submit}>
        <div className="login-bar">
          <span className="dots"><i></i><i></i><i></i></span>
          <span>pest@hive ~ // secure_node_access</span>
        </div>
        <div className="login-body">
          <div className="login-emblem">
            <img src="assets/pest-emblem.png" alt="P.E.S.T" />
            <span className="wm grad-text" data-text="P.E.S.T">P.E.S.T</span>
            <span className="sub">Member Access</span>
          </div>
          <div className="login-form">
            <div className="field">
              <label>Username</label>
              <input className="input mono" value={u} onChange={(e) => setU(e.target.value)} placeholder="your-handle" autoFocus />
            </div>
            <div className="field">
              <label>Password</label>
              <input className="input mono" type="password" value={p} onChange={(e) => setP(e.target.value)} placeholder="••••••••" />
            </div>
            {err && <div className="login-err">{err}</div>}
            <button className="btn btn-primary btn-block" type="submit" disabled={busy}>
              <window.AIcon.key /> {busy ? "Authenticating…" : "Authenticate"}
            </button>
          </div>
          <div className="login-note">
            Access is granted by P.E.S.T. Credentials are <b>issued by an admin</b>; you can change your
            username &amp; password later in your profile.
          </div>
          <button type="button" className="guest-link" onClick={onGuest}>View the public board <span>↗</span></button>
          <div className="login-legal">
            <a href="https://pestdao.xyz/legal-notice.html" target="_blank" rel="noreferrer">Legal Notice</a>
            <span> · </span>
            <a href="https://pestdao.xyz/privacy.html" target="_blank" rel="noreferrer">Privacy</a>
          </div>
        </div>
      </form>
    </div>
  );
}

window.Login = Login;
