// ============================================================
// app.jsx — the gate: loading → sign in → checking → shell,
// or "no access" for a signed-in account that is not a member.
// ============================================================

// Local design preview: http://localhost:<port>/?preview shows the shell
// without signing in. Only on localhost, and the shell has no data —
// every arete.* table is still locked by RLS on the server.
const PREVIEW = ["localhost", "127.0.0.1"].includes(window.location.hostname)
  && new URLSearchParams(window.location.search).has("preview");

function Root() {
  const { session, ready } = window.useSupaAuth();
  const access = window.useMembership(PREVIEW ? null : session);

  // after the sign-in round trip, go to the page asked for (?next=) and
  // drop `next` from the address bar
  React.useEffect(() => {
    if (access.status !== "member") return;
    const { hash, search } = window.AreteRoutes.takeNext(window.location.search);
    if (search === window.location.search && !hash) return;
    window.history.replaceState(null, "", window.location.pathname + search + (hash || window.location.hash));
    if (hash) window.dispatchEvent(new HashChangeEvent("hashchange"));
  }, [access.status]);

  if (PREVIEW) return <window.Shell email="preview@localhost" preview />;
  if (!ready) return <div className="boot" aria-live="polite">Loading…</div>;
  if (!session) return <window.SignIn />;
  if (access.status === "checking") return <window.Checking />;
  if (access.status === "error") return <window.AccessError message={access.message} onRetry={access.retry} />;
  if (access.status === "denied") return <window.NoAccess email={session.user.email} />;
  const meta = session.user.user_metadata || {};
  return <window.Shell email={session.user.email} fullName={meta.full_name || meta.name || ""} />;
}

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