/* === Boot — login gate, state load, then render the App === */

function Root() {
  const [user, setUser] = React.useState(() => window.Store.session());
  const [ready, setReady] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const [, bump] = React.useReducer((x) => x + 1, 0);

  // Dev convenience: ?as=Andrew&pin=1111 signs in automatically (local testing).
  React.useEffect(() => {
    if (user) return;
    const q = new URLSearchParams(location.search);
    const as = q.get("as"), pin = q.get("pin");
    if (as && pin) window.Store.login(as, pin).then(setUser).catch((e) => setErr(String(e.message || e)));
  }, []);

  React.useEffect(() => {
    if (!user) return;
    let alive = true;
    (async () => {
      try {
        await window.Store.init();
        if (alive) setReady(true);
      } catch (e) {
        if (alive) setErr(String(e.message || e));
      }
    })();
    return () => { alive = false; };
  }, [user]);

  // Re-render the whole app when the store commits a change.
  React.useEffect(() => window.Store.subscribe(bump), []);

  if (!user) return <Login onLogin={setUser} />;

  if (err) {
    return (
      <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", background: "var(--bg)" }}>
        <div className="card" style={{ padding: 24, maxWidth: 440 }}>
          <div style={{ fontFamily: "var(--serif)", fontSize: 18, fontWeight: 600 }}>Couldn't load data</div>
          <div style={{ marginTop: 8, fontSize: 13, color: "var(--red)" }}>{err}</div>
          <div className="row" style={{ marginTop: 16 }}>
            <button className="btn" onClick={() => location.reload()}>Retry</button>
            <button className="btn btn--ghost" onClick={() => window.Store.logout()}>Sign out</button>
          </div>
        </div>
      </div>
    );
  }

  if (!ready) {
    return (
      <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", background: "var(--bg)", gap: 10, color: "var(--ink-mute)", fontFamily: "var(--mono)", fontSize: 12 }}>
        <span className="spinner"></span> Loading tracker…
      </div>
    );
  }

  return <App />;
}

ReactDOM.createRoot(document.getElementById("root")).render(<Root />);
