/* === Login — name picker + PIN. No emails, no external identity. === */

function Login({ onLogin }) {
  const [users, setUsers] = React.useState(null);
  const [picked, setPicked] = React.useState(null);
  const [pin, setPin] = React.useState("");
  const [err, setErr] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  const [initNeeded, setInitNeeded] = React.useState(false);

  const loadUsers = React.useCallback(async () => {
    try {
      const list = await window.Store.listUsers();
      setUsers(list);
      setInitNeeded(window.Store.mode === "api" && list.length === 0);
    } catch (e) {
      setErr(String(e.message || e));
      setUsers([]);
    }
  }, []);
  React.useEffect(() => { loadUsers(); }, [loadUsers]);

  async function submit(e) {
    e.preventDefault();
    if (!picked || !pin) return;
    setBusy(true); setErr(null);
    try {
      const user = await window.Store.login(picked.name, pin);
      onLogin(user);
    } catch (ex) {
      setErr(String(ex.message || ex));
    } finally {
      setBusy(false);
    }
  }

  async function initDb() {
    setBusy(true); setErr(null);
    try {
      await window.Store.initDatabase();
      setInitNeeded(false);
      await loadUsers();
    } catch (ex) {
      setErr(String(ex.message || ex));
    } finally {
      setBusy(false);
    }
  }

  return (
    <div style={{
      minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center",
      background: "var(--bg)", padding: 20,
    }}>
      <div className="card" style={{ width: 420, padding: 0 }}>
        <div style={{ padding: "22px 26px 16px", borderBottom: "1px solid var(--rule)" }}>
          <div className="eyebrow">Project tracker</div>
          <div style={{ fontFamily: "var(--serif)", fontSize: 24, fontWeight: 600, marginTop: 8, letterSpacing: "-.012em" }}>
            Retirement Savings
          </div>
          <div className="section-sub" style={{ marginTop: 4 }}>
            Sign in to view and edit. All changes are attributed and kept in the edit history.
          </div>
        </div>

        <div style={{ padding: "18px 26px 24px" }}>
          {users === null ? (
            <div className="row" style={{ gap: 10, color: "var(--ink-mute)", fontSize: 12 }}>
              <span className="spinner"></span> Loading accounts…
            </div>
          ) : initNeeded ? (
            <div>
              <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5 }}>
                First run — the database is empty. Initialize it with the default accounts
                and the seed dataset. Default PINs are in <span className="mono">DEPLOY.md</span>;
                change them after signing in.
              </div>
              <button className="btn btn--primary" style={{ marginTop: 14 }} disabled={busy} onClick={initDb}>
                {busy ? "Initializing…" : "Initialize database"}
              </button>
            </div>
          ) : (
            <form onSubmit={submit}>
              <div className="eyebrow" style={{ marginBottom: 8 }}>Who are you?</div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                {users.map((u) => (
                  <button type="button" key={u.id}
                          onClick={() => { setPicked(u); setErr(null); }}
                          className="btn"
                          style={picked && picked.id === u.id ? {
                            background: "var(--navy)", color: "white", borderColor: "var(--navy)",
                          } : null}>
                    {u.name}
                    <span className="mono" style={{
                      fontSize: 9, letterSpacing: ".1em", textTransform: "uppercase",
                      color: picked && picked.id === u.id ? "rgba(255,255,255,.7)" : "var(--ink-faint)",
                    }}>{u.role}</span>
                  </button>
                ))}
              </div>

              {picked ? (
                <div style={{ marginTop: 16 }}>
                  <div className="eyebrow" style={{ marginBottom: 8 }}>PIN</div>
                  <div className="row" style={{ gap: 10 }}>
                    <input
                      autoFocus
                      type="password"
                      inputMode="numeric"
                      value={pin}
                      onChange={(e) => setPin(e.target.value)}
                      placeholder="••••"
                      style={{
                        width: 120, padding: "8px 12px", borderRadius: 5,
                        border: "1px solid var(--border)", background: "var(--surface-2)",
                        font: "600 16px/1 var(--mono)", letterSpacing: ".3em",
                        color: "var(--ink)", outline: "none", textAlign: "center",
                      }}
                    />
                    <button className="btn btn--primary" type="submit" disabled={busy || !pin}>
                      {busy ? "Signing in…" : "Sign in"}
                    </button>
                  </div>
                </div>
              ) : null}

              {err ? (
                <div style={{
                  marginTop: 14, padding: "8px 12px", borderRadius: 4,
                  background: "var(--red-bg)", color: "var(--red)", fontSize: 12,
                }}>{err}</div>
              ) : null}

              {window.Store.mode === "local" ? (
                <div className="mono faint" style={{ fontSize: 10, marginTop: 18, lineHeight: 1.6 }}>
                  LOCAL DEMO MODE — data stays in this browser.<br />
                  PINs: Andrew 1111 · John 2222 · Team member 3333
                </div>
              ) : null}
            </form>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Login });
