import NextAuthProvider from "@/lib/NextAuthProvider";
import type { Metadata } from "next";
import { getServerSession } from "next-auth";
import { Figtree } from "next/font/google";
import { Toaster } from "sonner";
import Footer from "../layouts/footer";
import Navbar from "../layouts/header";
import { authOptions } from "@/lib/auth-options";
import "./globals.css";
import QueryProvider from "./QueryClientProvider";
import SettingsStoreHydration from "./SettingsStoreHydration";

const figtree = Figtree({
  variable: "--font-figtree",
  subsets: ["latin"],
  weight: ["300", "400", "500", "600", "700", "800", "900"],
});

export const metadata: Metadata = {
  title: "ReelFlix",
  description: "Watch your favorite movies and TV shows",
};

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const session = await getServerSession(authOptions as any);

  // Warm the TLS handshake to the API and image CDN while the document is
  // still parsing — Lighthouse measured ~290ms lost to the API connection.
  const apiOrigin = originOf(process.env.NEXT_PUBLIC_API_ENDPOINT);
  const imageOrigin = originOf(process.env.NEXT_PUBLIC_IMAGE_BASE_URL);

  return (
    <html lang="en">
      <head>
        {apiOrigin && (
          <>
            <link rel="preconnect" href={apiOrigin} crossOrigin="" />
            <link rel="dns-prefetch" href={apiOrigin} />
          </>
        )}
        {imageOrigin && (
          <>
            <link rel="preconnect" href={imageOrigin} crossOrigin="" />
            <link rel="dns-prefetch" href={imageOrigin} />
          </>
        )}
      </head>
      <body className={`${figtree.variable}  antialiased`}>
        <SettingsStoreHydration />
        <NextAuthProvider session={session}>
          <QueryProvider>
            <Navbar />
            <Toaster richColors />
            {children}
          </QueryProvider>
        </NextAuthProvider>
        <Footer />
      </body>
    </html>
  );
}

function originOf(value?: string) {
  if (!value) return null;
  try {
    return new URL(value).origin;
  } catch {
    return null;
  }
}
