import type { Metadata } from "next";
import { headers } from "next/headers";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import prisma from "@/server/db/prisma";

const geistSans = Geist({
  variable: "--font-geist-sans",
  subsets: ["latin"],
});

const geistMono = Geist_Mono({
  variable: "--font-geist-mono",
  subsets: ["latin"],
});

export const metadata: Metadata = {
  title: "Nitescape - Digital Solutions Partner",
  description: "Welcome to Nitescape - Your Digital Solutions Partner",
  keywords: "digital solutions, web development, software development, IT services",
  icons: {
    icon: [
      { url: "/favicon-16x16.png", sizes: "16x16", type: "image/png" },
      { url: "/favicon-32x32.png", sizes: "32x32", type: "image/png" },
    ],
    apple: [{ url: "/apple-touch-icon.png", sizes: "180x180", type: "image/png" }],
    other: [{ rel: "icon", url: "/favicon.ico" }],
  },
  openGraph: {
    title: "Nitescape - Digital Solutions Partner",
    description: "Welcome to Nitescape - Your Digital Solutions Partner",
    type: "website",
  },
  twitter: {
    card: "summary_large_image",
    title: "Nitescape - Digital Solutions Partner",
    description: "Welcome to Nitescape - Your Digital Solutions Partner",
  },
  robots: "index, follow",
};

async function getGoogleAnalyticsId(): Promise<string> {
  if (process.env.NEXT_PUBLIC_GA_ID) return process.env.NEXT_PUBLIC_GA_ID;
  try {
    const settings = await prisma.googleSettings.findFirst({
      select: { googleAnalyticsId: true },
    });
    return settings?.googleAnalyticsId ?? "";
  } catch {
    return "";
  }
}

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const headersList = await headers();
  const nonce = headersList.get("x-nonce") ?? "";
  const gaId = await getGoogleAnalyticsId();

  return (
    <html lang="en">
      <head>
        {/* Removed Font Awesome CDN to reduce unused CSS. All icons are now loaded via @fortawesome/react-fontawesome. */}
        {/* Preload the navbar logo (above the fold) */}
        <link rel="preload" as="image" type="image/webp" href="/images/logo.webp" />
        <link rel="dns-prefetch" href="https://fonts.googleapis.com" />
        <link rel="dns-prefetch" href="https://fonts.gstatic.com" />
        <link rel="dns-prefetch" href="https://www.googletagmanager.com" />
        <link rel="preconnect" href="https://fonts.googleapis.com" crossOrigin="anonymous" />
        <link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
        <link
          rel="preload"
          as="style"
          href="https://fonts.googleapis.com/css2?family=Geist:wght@400;700&family=Geist+Mono:wght@400;700&display=swap"
        />
        {gaId && (
          <>
            <script
              async
              nonce={nonce}
              src={`https://www.googletagmanager.com/gtag/js?id=${gaId}`}
            />
            <script
              nonce={nonce}
              dangerouslySetInnerHTML={{
                __html: `
                  window.dataLayer = window.dataLayer || [];
                  function gtag(){dataLayer.push(arguments);}
                  gtag('js', new Date());
                  gtag('config', '${gaId}', { page_path: window.location.pathname });
                `,
              }}
            />
          </>
        )}
        {process.env.NEXT_PUBLIC_BASE_URL && <link rel="canonical" href={process.env.NEXT_PUBLIC_BASE_URL} />}
      </head>
      <body className={`${geistSans.variable} ${geistMono.variable}`} role="document">
        <main id="main-content" tabIndex={-1}>
          {children}
        </main>
      </body>
    </html>
  );
}
