import type { Metadata } from "next";
import localFont from "next/font/local";
import "./globals.css";
import { AuthProvider } from '@/lib/AuthContext';
import { QueryProvider } from '@/lib/QueryProvider';
import { GoogleOAuthProvider } from '@react-oauth/google';
import { headers } from 'next/headers';
import { connection } from 'next/server';
import { getMetadataForRequest, getRequestMetadataInput } from '@/lib/siteSeo';
import { getCurrentDashboardUser } from '@/lib/dashboardData';
import Script from 'next/script';

const axiforma = localFont({
  src: [
    { path: "../public/font/axiforma/Axiforma-Thin.woff2", weight: "100", style: "normal" },
    { path: "../public/font/axiforma/Axiforma-Light.woff2", weight: "300", style: "normal" },
    { path: "../public/font/axiforma/Axiforma-Regular.woff2", weight: "400", style: "normal" },
    { path: "../public/font/axiforma/Axiforma-Medium.woff2", weight: "500", style: "normal" },
    { path: "../public/font/axiforma/Axiforma-SemiBold.woff2", weight: "600", style: "normal" },
    { path: "../public/font/axiforma/Axiforma-Bold.woff2", weight: "700", style: "normal" },
    { path: "../public/font/axiforma/Axiforma-ExtraBold.woff2", weight: "800", style: "normal" },
    { path: "../public/font/axiforma/Axiforma-Black.woff2", weight: "900", style: "normal" },
  ],
  variable: "--font-axiforma",
  display: "swap",
  fallback: ["Arial", "sans-serif"],
  adjustFontFallback: "Arial",
  preload: true,
});

export async function generateMetadata(): Promise<Metadata> {
  return getMetadataForRequest(getRequestMetadataInput(await headers()));
}

const APP_URL = process.env.NEXT_PUBLIC_APP_URL || 'https://tools.cambridgeveritas.com';

const ORG_SCHEMA = {
  '@context': 'https://schema.org',
  '@type': 'EducationalOrganization',
  '@id': 'https://cambridgeveritas.com/#organization',
  name: 'Cambridge Veritas',
  alternateName: 'Cambridge Veritas®',
  url: 'https://cambridgeveritas.com',
  logo: 'https://cambridgeveritas.com/logo/White%20logo.png',
  description:
    'Cambridge Veritas offers UK-regulated professional certifications in TESOL, IELTS, Voice & Accent, and Advanced Fluency — trusted by 25,000+ professionals across 50+ countries.',
  telephone: '+918068212576',
  email: 'contact@cambridgeveritas.com',
  foundingDate: '2014',
  areaServed: 'Worldwide',
  knowsAbout: [
    'TESOL Certification',
    'IELTS Training',
    'Voice and Accent Training',
    'Professional English Communication',
    'Advanced Fluency',
  ],
  sameAs: [
    'https://www.linkedin.com/company/cambridge-veritas',
    'https://www.youtube.com/@cambridgeveritas',
    'https://www.facebook.com/cambridgeveritas',
  ],
};

const WEBSITE_SCHEMA = {
  '@context': 'https://schema.org',
  '@type': 'WebSite',
  '@id': `${APP_URL}/#website`,
  name: 'Cambridge Veritas',
  url: APP_URL,
  publisher: { '@id': 'https://cambridgeveritas.com/#organization' },
};

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  await connection();
  const initialUser = await getCurrentDashboardUser().catch(() => null);

  return (
    <html
      lang="en"
      className={`${axiforma.variable} ${axiforma.className} h-full antialiased`}
      suppressHydrationWarning
    >
      <body className="min-h-full flex flex-col" suppressHydrationWarning>
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(ORG_SCHEMA) }}
        />
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(WEBSITE_SCHEMA) }}
        />
        <GoogleOAuthProvider clientId={process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID || ""}>
          <QueryProvider>
            <AuthProvider initialUser={initialUser} initialAuthResolved>
              {children}
            </AuthProvider>
          </QueryProvider>
        </GoogleOAuthProvider>

        {/* Meta Pixel */}
        <Script id="meta-pixel" strategy="afterInteractive">{`
          !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js');fbq('init','9783411215104147');fbq('track','PageView');
        `}</Script>
        <noscript><img height="1" width="1" style={{display:'none'}} src="https://www.facebook.com/tr?id=9783411215104147&ev=PageView&noscript=1" alt="" /></noscript>

        {/* Google Analytics */}
        <Script
          src="https://www.googletagmanager.com/gtag/js?id=G-VFDV086R05"
          strategy="afterInteractive"
        />
        <Script id="google-analytics" strategy="afterInteractive">{`
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
          gtag('config', 'G-VFDV086R05');
        `}</Script>

        {/* Zoho SalesIQ — hidden by default */}
        <style>{`
          [data-id=zsalesiq] {
            display: none !important;
            visibility: hidden !important;
            opacity: 0 !important;
            pointer-events: none !important;
          }
        `}</style>
        <Script id="zoho-salesiq-init" strategy="afterInteractive">{`
          window.$zoho = window.$zoho || {};
          $zoho.salesiq = $zoho.salesiq || { ready: function() {} };
        `}</Script>
        <Script
          id="zsiqscript"
          src="https://salesiq.zohopublic.in/widget?wc=siqb94598d0fc02cd56c17523654a0fec28b193db0b1af3d258c47cedcd968d180f85af0a64aac9f7f36efd8270a235149b"
          strategy="afterInteractive"
        />

        {/* Zoho PageSense */}
        <Script
          src="https://cdn-in.pagesense.io/js/veritasbridgelearnprivatelim/79788ad57a904a45bddbf9811f3589fa.js"
          strategy="afterInteractive"
        />
      </body>
    </html>
  );
}
