import { Outlet, createRootRoute } from "@tanstack/react-router";
import { getNonce } from "@repo/core-shared/security/tanstack";

export const Route = createRootRoute({
  loader: async () => {
    try {
      // Server-side during SSR: read nonce set by applySecurityHeaders middleware.
      // Fails gracefully on client-side navigation (nonce already in DOM from SSR).
      const { getEvent } = await import("vinxi/http");
      return { nonce: getNonce(getEvent().node.req) };
    } catch {
      return { nonce: "" };
    }
  },
  component: () => {
    const { nonce } = Route.useLoaderData();
    return (
      <>
        {/* nonce exposed to client so instrumentation-client.ts can read it */}
        <meta name="csp-nonce" content={nonce} />
        <Outlet />
      </>
    );
  },
});
