import type { Metadata } from "next";
import type { ReactNode } from "react";
import { Outfit, Fira_Code } from "next/font/google";
import { AuthProvider } from "@/lib/auth/auth-context";
import { ErrorBoundary } from "@/components/error-boundary";
import { ThemeProvider } from "@/providers/ThemeProvider";
import { ReactQueryProvider } from "@/providers/ReactQueryProvider";
import "./globals.css";

export const dynamic = "force-dynamic";

export const metadata: Metadata = {
  title: "Mosaic Stack",
  description: "Mosaic Stack Web Application",
  icons: {
    icon: "/favicon.ico",
  },
};

const outfit = Outfit({
  subsets: ["latin"],
  variable: "--font-outfit",
  display: "swap",
});

const firaCode = Fira_Code({
  subsets: ["latin"],
  variable: "--font-fira-code",
  display: "swap",
});

/**
 * Runtime env vars injected as a synchronous script so client-side modules
 * can read them before React hydration.  This allows Docker env vars to
 * override the build-time baked NEXT_PUBLIC_* values.
 */
function runtimeEnvScript(): string {
  const env: Record<string, string> = {};
  for (const key of [
    "NEXT_PUBLIC_API_URL",
    "NEXT_PUBLIC_ORCHESTRATOR_URL",
    "NEXT_PUBLIC_AUTH_MODE",
  ]) {
    const value = process.env[key];
    if (value) {
      env[key] = value;
    }
  }
  return `window.__MOSAIC_ENV__=${JSON.stringify(env)};`;
}

export default function RootLayout({ children }: { children: ReactNode }): React.JSX.Element {
  return (
    <html lang="en" className={`${outfit.variable} ${firaCode.variable}`}>
      <head>
        <script dangerouslySetInnerHTML={{ __html: runtimeEnvScript() }} />
      </head>
      <body>
        <ThemeProvider>
          <ReactQueryProvider>
            <ErrorBoundary>
              <AuthProvider>{children}</AuthProvider>
            </ErrorBoundary>
          </ReactQueryProvider>
        </ThemeProvider>
      </body>
    </html>
  );
}
