import type { Metadata, Viewport } from "next";
import localFont from "next/font/local";
import "./globals.css";
import { cn } from "@/lib/utils";
import { siteConfig } from "@/lib/site";
import { GRAPH_IDS, JsonLd } from "@/lib/json-ld";
import { Navbar } from "@/components/navbar";
import { Footer } from "@/components/footer";
import { Analytics } from "@/components/analytics";
import { ConsentProvider } from "@/components/cookie-consent/ConsentProvider";
import { WhatsAppButton } from "@/components/whatsapp-button";
import { NewsletterPopup } from "@/components/newsletter/newsletter-popup";
import { OpenPanelComponent } from "@openpanel/nextjs";
import { OpenPanelAttribution } from "@/components/openpanel-attribution";

// Police auto-hébergée (next/font/local) → plus de fetch Google Fonts au build.
// WOFF2 variable (latin) fourni par @fontsource-variable/inter.
const inter = localFont({
  src: "../node_modules/@fontsource-variable/inter/files/inter-latin-wght-normal.woff2",
  display: "swap",
  weight: "100 900",
  style: "normal",
});

export const metadata: Metadata = {
  metadataBase: new URL(siteConfig.url),
  title: {
    default: "Courtier Énergie B2B : Ingénieurs & Optimisation | Acieb",
    template: "%s | Acieb Énergie",
  },
  description:
    "Cabinet de courtage en énergie pour professionnels dirigé par des ingénieurs. Audit gratuit, rémunération transparente. Réduisez vos factures d'électricité et gaz.",
  applicationName: "Acieb Énergie",
  authors: [{ name: "Acieb Énergie", url: "https://www.aciebenergie.fr" }],
  generator: "Next.js",
  referrer: "origin-when-cross-origin",
  creator: "Acieb Énergie",
  publisher: "Acieb Énergie",
  formatDetection: {
    email: false,
    address: false,
    telephone: false,
  },
  openGraph: {
    type: "website",
    locale: "fr_FR",
    siteName: "Acieb Énergie",
  },
  twitter: {
    card: "summary_large_image",
  },
  robots: {
    index: true,
    follow: true,
    googleBot: {
      index: true,
      follow: true,
      "max-video-preview": -1,
      "max-image-preview": "large",
      "max-snippet": -1,
    },
  },
  // Search engine ownership verification — values come from env vars so
  // the token can be rotated without code change. Only emit the meta tag
  // when the corresponding env var is set (avoids empty content="").
  verification: {
    ...(process.env.NEXT_PUBLIC_YANDEX_VERIFICATION
      ? { yandex: process.env.NEXT_PUBLIC_YANDEX_VERIFICATION }
      : {}),
    ...(process.env.NEXT_PUBLIC_GOOGLE_SITE_VERIFICATION
      ? { google: process.env.NEXT_PUBLIC_GOOGLE_SITE_VERIFICATION }
      : {}),
  },
  category: "business",
};

// Viewport + couleur de thème. colorScheme: "light" évite le flash blanc et
// laisse le navigateur styler les contrôles natifs ; themeColor aligne la chrome
// mobile sur la marque (cohérent avec app/manifest.ts).
export const viewport: Viewport = {
  width: "device-width",
  initialScale: 1,
  colorScheme: "light",
  themeColor: "#ea580c",
};

// JSON-LD global — Organization + WebSite sur TOUTES les pages (doc SEO Obsidian)
const globalJsonLd = {
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": ["ProfessionalService", "Organization"],
      "@id": GRAPH_IDS.organization,
      name: siteConfig.name,
      url: siteConfig.url,
      logo: {
        "@type": "ImageObject",
        "@id": GRAPH_IDS.logo,
        url: `${siteConfig.url}/logo.png`,
        contentUrl: `${siteConfig.url}/logo.png`,
        width: 512,
        height: 512,
        caption: siteConfig.name,
        inLanguage: siteConfig.locale,
      },
      image: `${siteConfig.url}/logo.png`,
      description: siteConfig.description,
      slogan:
        "Arrêtez de parler à des commerciaux. Confiez vos factures à des experts techniques.",
      address: { "@type": "PostalAddress", addressCountry: "FR" },
      contactPoint: {
        "@type": "ContactPoint",
        contactType: "customer service",
        availableLanguage: "French",
        url: `${siteConfig.url}/contact`,
      },
      priceRange: "Rémunération transparente (commission fournisseur ou honoraires)",
      areaServed: { "@type": "Country", name: "France" },
      sameAs: [
        "https://www.linkedin.com/company/acieb-courtage-electricité-gaz",
      ],
    },
    {
      "@type": "WebSite",
      "@id": GRAPH_IDS.website,
      url: siteConfig.url,
      name: siteConfig.name,
      alternateName: siteConfig.shortName,
      publisher: { "@id": GRAPH_IDS.organization },
      inLanguage: siteConfig.locale,
      potentialAction: {
        "@type": "SearchAction",
        target: {
          "@type": "EntryPoint",
          urlTemplate: `${siteConfig.url}/ressources/?q={search_term_string}`,
        },
        "query-input": "required name=search_term_string",
      },
    },
  ],
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="fr" suppressHydrationWarning>
      <head>
        {/* Preconnect/dns-prefetch vers l'instance OpenPanel self-hostée pour
            warm-up le TLS handshake avant le premier POST /api/track.
            Le script op1.js est servi en /public/op1.js (Vercel Edge), donc
            pas besoin de preconnect pour le script lui-même. */}
        <link
          rel="preconnect"
          href="https://analytics.elevaseo.app"
          crossOrigin="anonymous"
        />
        <link rel="dns-prefetch" href="https://analytics.elevaseo.app" />
        <link
          rel="alternate"
          type="application/rss+xml"
          title="Acieb Énergie - Blog RSS Feed"
          href="/feed.xml"
        />
        <JsonLd data={globalJsonLd} />
      </head>
      <body className={cn("antialiased", inter.className)}>
        {/* Skip-link : premier élément focusable, saute la navbar (WCAG 2.4.1) */}
        <a
          href="#main-content"
          className="sr-only focus:not-sr-only focus:absolute focus:left-4 focus:top-4 focus:z-[100] focus:rounded-md focus:bg-white focus:px-4 focus:py-2 focus:font-medium focus:text-gray-900 focus:shadow-lg focus:outline focus:outline-2 focus:outline-orange-700"
        >
          Aller au contenu principal
        </a>
        {/* Speculation Rules : prefetch des liens internes au survol (perf navigation) */}
        <script
          type="speculationrules"
          dangerouslySetInnerHTML={{
            __html: JSON.stringify({
              prefetch: [
                { where: { href_matches: "/*" }, eagerness: "moderate" },
              ],
            }),
          }}
        />
        <OpenPanelComponent
          clientId={process.env.NEXT_PUBLIC_OP_CLIENT_ID!}
          apiUrl={process.env.NEXT_PUBLIC_OP_API_URL!}
          // op1.js servi par /public/op1.js → Vercel Edge cache, ~50ms TTFB
          // (vs 800-2400ms depuis l'instance self-hostée sans CDN).
          // L'env var permet de basculer en CDN officiel ou self-host si besoin.
          scriptUrl={process.env.NEXT_PUBLIC_OP_SCRIPT_URL || "/op1.js"}
          trackScreenViews={true}
          trackOutgoingLinks={true}
          trackAttributes={true}
          disabled={process.env.NODE_ENV !== "production"}
        />
        <OpenPanelAttribution />
        <ConsentProvider>
          <Analytics />
          <Navbar />
          <div id="main-content" tabIndex={-1}>
            {children}
          </div>
          <Footer />
          <WhatsAppButton />
          <NewsletterPopup />
        </ConsentProvider>
      </body>
    </html>
  );
}
