import type { Metadata } from "next";
import { Inter } from "next/font/google";
import Script from "next/script";
import "./globals.css";
import { siteConfig } from "@/lib/site-config";
import { allProviders, guideFaq } from "@/lib/vpn-data";

const inter = Inter({
  variable: "--font-inter",
  subsets: ["latin"],
  weight: ["400", "500", "600", "700", "800", "900"],
  display: "swap",
});

const title = "Top 10 VPNs For Mac in 2026 | Mac VPN Guide";

export const metadata: Metadata = {
  metadataBase: new URL(siteConfig.url),
  title,
  description: siteConfig.description,
  keywords: siteConfig.keywords,
  robots: "index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1",
  alternates: {
    canonical: siteConfig.url,
  },
  icons: {
    icon: "/favicon.ico",
    apple: "/icon-512.png",
  },
  other: {
    "theme-color": "#0A84FF",
  },
  openGraph: {
    type: "website",
    siteName: siteConfig.guideName,
    title,
    description: siteConfig.description,
    url: siteConfig.url,
    images: [{ url: "/icon-512.png", width: 512, height: 512 }],
    locale: "en_US",
  },
  twitter: {
    card: "summary",
    title,
    description: siteConfig.description,
    images: ["/icon-512.png"],
  },
};

/** Built from the same data the page renders, so structured data can't drift. */
const structuredData = {
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "Organization",
      "@id": `${siteConfig.url}#org`,
      name: siteConfig.operator,
      url: siteConfig.url,
      logo: `${siteConfig.url}icon-512.png`,
    },
    {
      "@type": "WebSite",
      "@id": `${siteConfig.url}#website`,
      url: siteConfig.url,
      name: siteConfig.guideName,
      inLanguage: "en",
      publisher: { "@id": `${siteConfig.url}#org` },
    },
    {
      "@type": "ItemList",
      "@id": `${siteConfig.url}#picks`,
      name: title,
      description: siteConfig.description,
      itemListOrder: "https://schema.org/ItemListOrderDescending",
      numberOfItems: allProviders.length,
      itemListElement: allProviders.map((provider, i) => ({
        "@type": "ListItem",
        position: i + 1,
        item: {
          "@type": "SoftwareApplication",
          name: provider.name,
          applicationCategory: "SecurityApplication",
          applicationSubCategory: "VPN",
          operatingSystem: "macOS",
          url: provider.url,
        },
      })),
    },
    {
      "@type": "FAQPage",
      "@id": `${siteConfig.url}#faq`,
      mainEntity: guideFaq.map((item) => ({
        "@type": "Question",
        name: item.question,
        acceptedAnswer: { "@type": "Answer", text: item.answer },
      })),
    },
  ],
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html
      lang="en"
      data-scroll-behavior="smooth"
      className={`${inter.variable} h-full antialiased`}
    >
      <head>
        {/* Google Tag Manager */}
        <Script id="gtm" strategy="afterInteractive">
          {`(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-KX8VKRVH');`}
        </Script>
        {/* End Google Tag Manager */}
        <Script
          src="https://www.googletagmanager.com/gtag/js?id=G-0Z1Y6B0Q8L"
          strategy="afterInteractive"
        />
        <Script id="gtag-init" strategy="afterInteractive">
          {`
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            var dbg = new URLSearchParams(location.search).has('debug');
            gtag('config', 'G-0Z1Y6B0Q8L', dbg ? { debug_mode: true } : {});
            gtag('config', 'AW-801951719');

            (function () {
              var g = new URLSearchParams(location.search).get('gclid');
              if (g) {
                localStorage.setItem('gclid', g);
                document.cookie = 'gclid=' + g + ';max-age=7776000;path=/';
              }
            })();

            gtag('get', 'G-0Z1Y6B0Q8L', 'client_id', function (id) {
              try { localStorage.setItem('ga_cid', id); } catch (e) {}
            });

            (function () {
              document.addEventListener('click', function (e) {
                var t = e.target;
                if (!t || typeof t.closest !== 'function') return;

                var ours = t.closest('a[href*="vpnproxymaster.app"]');
                if (ours) {
                  if (typeof gtag === 'function') {
                    gtag('event', 'product_visit_click', { product: 'vpnfast', platform: 'mac' });
                  }
                  return;
                }

                var out = t.closest('a[rel~="sponsored"]');
                if (out && typeof gtag === 'function') {
                  gtag('event', 'outbound_visit_click', {
                    destination: out.hostname,
                    link_url: out.href
                  });
                }
              }, true);
            })();
          `}
        </Script>
      </head>
      <body className="min-h-full flex flex-col bg-background text-ink">
        {/* Google Tag Manager (noscript) */}
        <noscript>
          <iframe
            src="https://www.googletagmanager.com/ns.html?id=GTM-KX8VKRVH"
            height="0"
            width="0"
            style={{ display: "none", visibility: "hidden" }}
          />
        </noscript>
        {/* End Google Tag Manager (noscript) */}
        {children}
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(structuredData) }}
        />
      </body>
    </html>
  );
}
