import { GoogleAnalytics } from "@next/third-parties/google";
import { OpenPanelComponent } from "@openpanel/nextjs";
import pick from "lodash/pick";
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import { notFound } from "next/navigation";
import { hasLocale, NextIntlClientProvider } from "next-intl";
import { setRequestLocale } from "next-intl/server";
import { Footer } from "@/components/sections/footer";
import Header from "@/components/sections/header";
import { TranslationAlternatesProvider } from "@/contexts/translation-alternates";
import { routing } from "@/i18n/routing";

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

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

export function generateStaticParams() {
  return routing.locales.map((locale) => ({ locale }));
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: string }>;
}): Promise<Metadata> {
  const { locale } = await params;

  const titles: Record<string, string> = {
    fr: "ElevaSEO | Agence Headless CMS & Performance Web",
    en: "ElevaSEO | Headless CMS & Performance-Driven Web Development",
  };

  const descriptions: Record<string, string> = {
    fr: "Agence headless CMS : Next.js, Shopify & WordPress. Lighthouse 95+, chargement < 1,5 s. Libérez l'agilité de votre équipe marketing.",
    en: "We build high-performance headless websites with Next.js, Shopify & WordPress. 95+ Lighthouse scores, sub-1.5s load times, measurable growth.",
  };

  return {
    title: {
      default: titles[locale] || titles.en,
      template: "%s | ElevaSEO",
    },
    description: descriptions[locale] || descriptions.en,
    metadataBase: new URL("https://www.elevaseo.com"),
    openGraph: {
      type: "website",
      locale: locale === "fr" ? "fr_FR" : "en_US",
      siteName: "ElevaSEO",
      url:
        locale === "fr"
          ? "https://www.elevaseo.com/"
          : `https://www.elevaseo.com/${locale}`,
    },
    twitter: {
      card: "summary_large_image",
      site: "@elevaseo",
      creator: "@elevaseo",
    },
    robots: {
      index: true,
      follow: true,
      "max-image-preview": "large" as const,
      "max-snippet": -1,
      "max-video-preview": -1,
    },
    // Search engine ownership verification meta tags.
    // Set the corresponding env vars (NEXT_PUBLIC_..._VERIFICATION) to enable
    // each tag. Leave unset and the tag is simply not rendered. These are
    // public values — they appear in HTML — so they live in NEXT_PUBLIC_*.
    //
    // Yandex: https://webmaster.yandex.com/ → Settings → Rights → HTML tag
    // Google: https://search.google.com/search-console/ → Settings → Ownership verification → HTML tag
    // Bing:   https://www.bing.com/webmasters/ → Site settings → Verify ownership → HTML Meta Tag
    verification: {
      ...(process.env.NEXT_PUBLIC_YANDEX_VERIFICATION
        ? { yandex: process.env.NEXT_PUBLIC_YANDEX_VERIFICATION }
        : {}),
      ...(process.env.NEXT_PUBLIC_GOOGLE_VERIFICATION
        ? { google: process.env.NEXT_PUBLIC_GOOGLE_VERIFICATION }
        : {}),
      ...(process.env.NEXT_PUBLIC_BING_VERIFICATION
        ? {
            other: {
              "msvalidate.01": process.env.NEXT_PUBLIC_BING_VERIFICATION,
            },
          }
        : {}),
    },
    other: {
      "theme-color": "#fd105e",
    },
  };
}

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

  if (!hasLocale(routing.locales, locale)) {
    notFound();
  }

  setRequestLocale(locale);

  const messages = (await import(`../../messages/${locale}.json`)).default;

  // Only pass shared namespaces (header/footer) to root provider.
  // Page-specific namespaces are provided via nested NextIntlClientProvider
  // in each page. This reduces RSC payload from ~150KB to ~15KB per page.
  const sharedMessages = pick(messages, [
    "common",
    "nav",
    "footer",
    "breadcrumbs",
    "notFound",
  ]) as typeof messages;

  const websiteJsonLd = {
    "@context": "https://schema.org",
    "@type": "WebSite",
    name: "ElevaSEO",
    url: "https://www.elevaseo.com",
    potentialAction: {
      "@type": "SearchAction",
      target: {
        "@type": "EntryPoint",
        urlTemplate: `https://www.elevaseo.com${locale === "fr" ? "" : "/en"}/blog?q={search_term_string}`,
      },
      "query-input": "required name=search_term_string",
    },
    inLanguage: [
      { "@type": "Language", name: "French", alternateName: "fr" },
      { "@type": "Language", name: "English", alternateName: "en" },
    ],
  };

  const navigationJsonLd = {
    "@context": "https://schema.org",
    "@type": "SiteNavigationElement",
    name: locale === "fr" ? "Navigation principale" : "Main navigation",
    hasPart: [
      {
        "@type": "WebPage",
        name: locale === "fr" ? "Accueil" : "Home",
        url: "https://www.elevaseo.com",
      },
      {
        "@type": "WebPage",
        name: "Services",
        url: `https://www.elevaseo.com${locale === "fr" ? "" : "/en"}/services`,
      },
      {
        "@type": "WebPage",
        name: "Blog",
        url: `https://www.elevaseo.com${locale === "fr" ? "" : "/en"}/blog`,
      },
      {
        "@type": "WebPage",
        name: locale === "fr" ? "A propos" : "About",
        url: `https://www.elevaseo.com${locale === "fr" ? "" : "/en"}/about`,
      },
      {
        "@type": "WebPage",
        name: "Contact",
        url: `https://www.elevaseo.com${locale === "fr" ? "" : "/en"}/contact`,
      },
    ],
  };

  const organizationJsonLd = {
    "@context": "https://schema.org",
    "@type": "Organization",
    name: "ElevaSEO",
    url: "https://www.elevaseo.com",
    logo: "https://www.elevaseo.com/logo.webp",
    description:
      locale === "fr"
        ? "Agence web spécialisée en architecture headless CMS, SEO technique et optimisation de la performance. Sites Next.js, Shopify Headless et WordPress Headless avec scores Lighthouse 95+."
        : "Performance-driven web agency specializing in headless CMS architecture, technical SEO, and CRO. We build high-performance websites with Next.js, Shopify Headless, and WordPress Headless.",
    founder: {
      "@type": "Person",
      name: "Bastien Allain",
      jobTitle:
        locale === "fr"
          ? "Fondateur & Specialiste Headless"
          : "Founder & Headless Specialist",
      url: "https://www.elevaseo.com/about",
      sameAs: ["https://www.linkedin.com/in/bastien-allain-372392389/"],
    },
    foundingDate: "2024",
    areaServed: ["FR", "US", "GB", "CA", "BE", "CH"],
    contactPoint: {
      "@type": "ContactPoint",
      contactType: "customer service",
      url: "https://www.elevaseo.com/contact",
      availableLanguage: ["French", "English"],
    },
    sameAs: [
      "https://twitter.com/elevaseo",
      "https://www.linkedin.com/company/elevaseo",
      "https://github.com/elevaseo",
    ],
    knowsAbout: [
      "Headless CMS",
      "Next.js",
      "Shopify",
      "WordPress",
      "SEO",
      "CRO",
      "Core Web Vitals",
      "TypeScript",
      "React",
    ],
  };

  return (
    <html data-scroll-behavior="smooth" lang={locale} suppressHydrationWarning>
      <head>
        <link
          href={`${locale === "fr" ? "" : `/${locale}`}/blog/rss.xml`}
          rel="alternate"
          title="ElevaSEO Blog"
          type="application/rss+xml"
        />
      </head>
      <body
        className={`${geistSans.variable} ${geistMono.variable} min-h-screen bg-gradient-to-br from-[#000] to-[#1A2428] text-white antialiased`}
      >
        <script
          dangerouslySetInnerHTML={{
            __html: JSON.stringify(organizationJsonLd),
          }}
          type="application/ld+json"
        />
        <script
          dangerouslySetInnerHTML={{
            __html: JSON.stringify(websiteJsonLd),
          }}
          type="application/ld+json"
        />
        <script
          dangerouslySetInnerHTML={{
            __html: JSON.stringify(navigationJsonLd),
          }}
          type="application/ld+json"
        />
        <NextIntlClientProvider locale={locale} messages={sharedMessages}>
          <TranslationAlternatesProvider>
            <Header />
            <main className="pt-16">{children}</main>
            <Footer />
          </TranslationAlternatesProvider>
        </NextIntlClientProvider>
        <OpenPanelComponent
          apiUrl={process.env.NEXT_PUBLIC_OP_API_URL ?? ""}
          clientId={process.env.NEXT_PUBLIC_OP_CLIENT_ID ?? ""}
          scriptUrl="https://analytics.elevaseo.app/op1.js"
          trackAttributes={true}
          trackOutgoingLinks={true}
          trackScreenViews={true}
        />
        <GoogleAnalytics gaId="G-T5SXH37NM6" />
      </body>
    </html>
  );
}
