// main.jsx — async bootstrap: load live data from the backend, then mount.
const rootEl = document.getElementById("root");

function Splash({ error }) {
  return (
    <div style={{ height: "100vh", display: "grid", placeItems: "center", background: "var(--bg-2)" }}>
      <div style={{ textAlign: "center", color: "var(--fg-3)" }}>
        <img src="assets/logo-dark.png" alt="Maxab Hub" style={{ height: 34, marginBottom: 16 }} />
        {error ? (
          <>
            <div style={{ color: "var(--color-danger)", fontWeight: 700, marginBottom: 6 }}>Couldn’t reach the server</div>
            <div style={{ fontSize: 13, maxWidth: 360 }}>{String(error)}</div>
            <button className="btn btn--primary" style={{ marginTop: 16 }} onClick={() => location.reload()}>Retry</button>
          </>
        ) : (
          <div style={{ fontSize: 14 }}>Loading your sales workspace…</div>
        )}
      </div>
    </div>
  );
}

let _root;
// Resolve the auth context robustly. The very first fetch a freshly-loaded page
// issues can transiently fail (connection setup race) — so retry a couple of
// times, and if /auth/me still won't resolve, fall back to the PUBLIC /health to
// learn whether auth is enabled. Without this, a transient failure made the
// catch assume "auth off" and then dead-end on the bootstrap 401 (the login
// screen never appeared when MAXAB_AUTH=1).
async function resolveAuth() {
  for (let i = 0; i < 3; i++) {
    try { return await API.auth.me(); } catch { await new Promise((r) => setTimeout(r, 250 * (i + 1))); }
  }
  const h = await API.health().catch(() => null);
  return h ? { authEnabled: !!h.authEnabled, user: null } : { authEnabled: false, user: null };
}
async function boot() {
  _root = _root || ReactDOM.createRoot(rootEl);
  _root.render(<Splash />);
  try {
    // Auth gate (no-op when the server runs without MAXAB_AUTH).
    const me = await resolveAuth();
    window.DATA.meta = window.DATA.meta || {};
    if (me.authEnabled && !me.user) { _root.render(<ErrorBoundary><LoginScreen onSuccess={() => boot()} /></ErrorBoundary>); return; }
    await Actions.refreshBootstrap();
    // refreshBootstrap overwrites DATA.meta — restore auth context after it.
    window.DATA.meta = window.DATA.meta || {};
    DATA.meta.authEnabled = me.authEnabled;
    DATA.meta.user = me.user;
    // ErrorBoundary guarantees a render crash never blanks the app (no refresh).
    _root.render(<ErrorBoundary><App /></ErrorBoundary>);
  } catch (err) {
    console.error("Bootstrap failed:", err);
    _root.render(<Splash error={err.message} />);
  }
}

boot();
