import Layout from "@/components/Layout";
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "../globals.css";
import { NextIntlClientProvider } from "next-intl";
import { getMessages } from "next-intl/server";
import { notFound } from "next/navigation";
import { LazyMotion, domAnimation } from "framer-motion";
import AnalyticsProvider from "@/components/analytics/AnalyticsProvider";
import { config } from "@/lib/config";

const inter = Inter({
  subsets: ["latin"],
  display: "swap",
  variable: "--font-inter",
  weight: ["400", "700", "800"], // Explicit weights to optimize download
});

export const metadata: Metadata = {
  metadataBase: new URL("https://www.mb-grid-solutions.com"),
  title: {
    default: "MB Grid Solutions | Energiekabelprojekte & Technische Beratung",
    template: "%s | MB Grid Solutions",
  },
  description:
    "Ihr spezialisierter Partner für herstellerneutrale technische Beratung und Projektbegleitung bei Energiekabelprojekten bis 110 kV. Expertise in Mittel- und Hochspannungsnetzen.",
  keywords: [
    "Energiekabel",
    "Hochspannung",
    "Mittelspannung",
    "Kabelprojekte",
    "Technische Beratung",
    "Engineering",
    "Energiewende",
    "110 kV",
  ],
  authors: [{ name: "MB Grid Solutions & Services GmbH" }],
  creator: "MB Grid Solutions & Services GmbH",
  publisher: "MB Grid Solutions & Services GmbH",
  formatDetection: {
    email: false,
    address: false,
    telephone: false,
  },
  openGraph: {
    type: "website",
    locale: "de_DE",
    url: "https://www.mb-grid-solutions.com",
    siteName: "MB Grid Solutions",
    title: "MB Grid Solutions | Energiekabelprojekte & Technische Beratung",
    description:
      "Spezialisierter Partner für Energiekabelprojekte bis 110 kV. Herstellerneutrale technische Beratung und Projektbegleitung.",
  },
  twitter: {
    card: "summary_large_image",
    title: "MB Grid Solutions | Energiekabelprojekte & Technische Beratung",
    description: "Spezialisierter Partner für Energiekabelprojekte bis 110 kV.",
  },
  robots: {
    index: true,
    follow: true,
    googleBot: {
      index: true,
      follow: true,
      "max-video-preview": -1,
      "max-image-preview": "large",
      "max-snippet": -1,
    },
  },
};

export default async function RootLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;

  // Validate that the incoming `locale` is supported
  if (locale !== "de") {
    notFound();
  }

  // Providing all messages to the client
  // side is the easiest way to get started
  const messages = await getMessages();

  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "Organization",
    name: "MB Grid Solutions & Services GmbH",
    url: "https://www.mb-grid-solutions.com",
    logo: "https://www.mb-grid-solutions.com/assets/logo.png",
    description:
      "Ihr spezialisierter Partner für herstellerneutrale technische Beratung und Projektbegleitung bei Energiekabelprojekten bis 110 kV.",
    address: {
      "@type": "PostalAddress",
      streetAddress: "Raiffeisenstraße 22",
      addressLocality: "Remshalden",
      postalCode: "73630",
      addressCountry: "DE",
    },
    contactPoint: {
      "@type": "ContactPoint",
      email: "info@mb-grid-solutions.com",
      contactType: "customer service",
    },
  };

  // Track pageview on the server
  // This is safe to call here because layout is a Server Component
  const serverServices = (
    await import("@/lib/services/create-services.server")
  ).getServerAppServices();

  // Populate analytics context with headers for high-fidelity server-side tracking
  const { headers } = await import("next/headers");
  const requestHeaders = await headers();

  if (serverServices.analytics.setServerContext) {
    serverServices.analytics.setServerContext({
      userAgent: requestHeaders.get("user-agent") || undefined,
      language:
        requestHeaders.get("accept-language")?.split(",")[0] || undefined,
      referrer: requestHeaders.get("referer") || undefined,
      ip: requestHeaders.get("x-forwarded-for")?.split(",")[0] || undefined,
    });
  }

  // Track server-side (initial load)
  // serverServices.analytics.trackPageview("/"); // Removed to avoid double-tracking and incorrect path reporting

  return (
    <html lang={locale} className={`${inter.variable}`}>
      <head>
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
        />
      </head>
      <body className="antialiased">
        <NextIntlClientProvider messages={messages}>
          <AnalyticsProvider websiteId={config.analytics.umami.websiteId} />
          <LazyMotion features={domAnimation}>
            <Layout>{children}</Layout>
          </LazyMotion>
        </NextIntlClientProvider>
      </body>
    </html>
  );
}
