// LoginScreen — sign in / create account. Reuses the onboard CSS palette so
// new users land on something that feels like the rest of the app. On success,
// api.login/register stores the returned token in localStorage and we reload
// to re-bootstrap through getUser().
const { useState: useState_L } = React;

function LoginScreen() {
  const [mode, setMode]       = useState_L("signin"); // signin | register
  const [username, setU]      = useState_L("");
  const [password, setP]      = useState_L("");
  const [name, setName]       = useState_L("");
  const [busy, setBusy]       = useState_L(false);
  const [err, setErr]         = useState_L("");

  const canSubmit =
    username.trim().length >= 3 &&
    password.length >= 8 &&
    (mode === "signin" || name.trim().length > 0);

  const submit = async (e) => {
    e?.preventDefault?.();
    if (!canSubmit || busy) return;
    setBusy(true); setErr("");
    try {
      if (mode === "signin") {
        await api.login({ username: username.trim(), password });
      } else {
        await api.register({ username: username.trim(), password, name: name.trim() });
      }
      // Fresh bootstrap — App reads /api/user, sees onboarded flag, routes correctly.
      location.reload();
    } catch (ex) {
      const msg = ex?.status === 401 ? "Wrong username or password."
                : ex?.status === 409 ? "Username is taken."
                : ex?.status === 429 ? "Too many attempts. Wait a minute."
                : "Couldn't reach the server.";
      setErr(msg);
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="onboard login-screen">
      <div className="login-brand">
        <div className="mark">f</div>
        <div className="login-wordmark">FUTURE SELF</div>
      </div>

      <div className="login-tabs" role="tablist">
        <button
          className={`login-tab ${mode === "signin" ? "on" : ""}`}
          onClick={() => { setMode("signin"); setErr(""); }}
          role="tab"
        >Sign in</button>
        <button
          className={`login-tab ${mode === "register" ? "on" : ""}`}
          onClick={() => { setMode("register"); setErr(""); }}
          role="tab"
        >Create account</button>
      </div>

      <form className="login-form" onSubmit={submit}>
        {mode === "register" && (
          <div className="onboard-field">
            <label className="login-label">Your name</label>
            <input
              className="text-input"
              value={name}
              onChange={e => setName(e.target.value)}
              placeholder="Kaku"
              autoComplete="name"
            />
          </div>
        )}
        <div className="onboard-field">
          <label className="login-label">Username</label>
          <input
            className="text-input"
            value={username}
            onChange={e => setU(e.target.value)}
            placeholder="kaku"
            autoCapitalize="none"
            autoCorrect="off"
            autoComplete="username"
          />
        </div>
        <div className="onboard-field">
          <label className="login-label">Password</label>
          <input
            className="text-input"
            type="password"
            value={password}
            onChange={e => setP(e.target.value)}
            placeholder="8+ characters"
            autoComplete={mode === "signin" ? "current-password" : "new-password"}
          />
        </div>

        {err && <div className="onboard-error" role="alert">{err}</div>}

        <button
          type="submit"
          className="onboard-next login-submit"
          disabled={!canSubmit || busy}
        >
          {busy ? "…" : mode === "signin" ? "Sign in" : "Create account"}
        </button>
      </form>
    </div>
  );
}

Object.assign(window, { LoginScreen });
