import { Suspense } from "react"
import type { Metadata } from "next"
import { Inter as FontSans, JetBrains_Mono, Sora, Source_Code_Pro } from "next/font/google"
import "./globals.css"
import { cn } from "@/lib/utils"
import { ThemeProvider } from "@/components/theme-provider"
import { Auth0Provider } from "@auth0/nextjs-auth0"
import { Toaster } from "@/components/ui/toaster"
import { Toaster as SonnerToaster } from "sonner"
import { auth0 } from "@/lib/auth0"
import Script from "next/script"
import { PHProvider } from "./providers"
import PostHogPageView from "./PostHogPageView"

const fontSans = FontSans({
  subsets: ["latin"],
  variable: "--font-sans",
  display: "swap",
})

const jetbrainsMono = JetBrains_Mono({
  subsets: ["latin"],
  weight: ["400", "600"],
  variable: "--font-jetbrains-mono",
  display: "swap",
})

const sora = Sora({
  subsets: ["latin"],
  weight: ["400", "600"],
  variable: "--font-sora",
  display: "swap",
  preload: false, // Only used on onboarding — skip preload on every page
})

const sourceCodePro = Source_Code_Pro({
  subsets: ["latin"],
  weight: ["400"],
  variable: "--font-source-code-pro",
  display: "swap",
  preload: false, // Only used on onboarding — skip preload on every page
})

export const metadata: Metadata = {
  title: "Codeflash",
  description: "Optimize the performance of your code.",
}

// Async server component: streams Intercom snippet after session resolves.
// Extracted from the root layout so auth0.getSession() (which reads headers())
// doesn't block the entire page shell from prerendering.
async function IntercomScript() {
  const session = await auth0.getSession()

  const baseSnippet = `var APP_ID = "ljxo1nzr";
(function(){var w=window;var ic=w.Intercom;if(typeof ic==="function"){ic('reattach_activator');ic('update',w.intercomSettings);}else{var d=document;var i=function(){i.c(arguments);};i.q=[];i.c=function(args){i.q.push(args);};w.Intercom=i;var l=function(){var s=d.createElement('script');s.type='text/javascript';s.async=true;s.src='https://widget.intercom.io/widget/' + APP_ID;var x=d.getElementsByTagName('script')[0];x.parentNode.insertBefore(s, x);};if(document.readyState==='complete'){l();}else if(w.attachEvent){w.attachEvent('onload',l);}else{w.addEventListener('load',l,false);}}})();`

  const bootSnippet = session
    ? `window.Intercom('boot', {
  app_id: "ljxo1nzr",
  name: ${JSON.stringify(session.user.name ?? "")},
  nickname: ${JSON.stringify(session.user.nickname ?? "")},
  picture: ${JSON.stringify(session.user.picture ?? "")},
  user_id: ${JSON.stringify(session.user.sub ?? "")},
  email: null,
});`
    : `window.Intercom('boot', { app_id: "ljxo1nzr" });`

  return (
    <Script
      id="intercom-script"
      strategy="lazyOnload"
      dangerouslySetInnerHTML={{ __html: baseSnippet + "\n" + bootSnippet }}
    />
  )
}

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" suppressHydrationWarning>
      <PHProvider>
        <body
          className={cn(
            "min-h-screen bg-background font-sans antialiased",
            fontSans.variable,
            jetbrainsMono.variable,
            sora.variable,
            sourceCodePro.variable,
          )}
        >
          <Suspense fallback={null}>
            <PostHogPageView />
          </Suspense>
          <Auth0Provider>
            <ThemeProvider
              attribute="class"
              defaultTheme="system"
              enableSystem
              disableTransitionOnChange
            >
              {children}
              <Toaster />
              <SonnerToaster position="top-right" richColors />
            </ThemeProvider>
          </Auth0Provider>
          <Suspense fallback={null}>
            <IntercomScript />
          </Suspense>
          <Script
            id="crisp-chat-script"
            strategy="lazyOnload"
            dangerouslySetInnerHTML={{
              __html: `window.$crisp=[];window.CRISP_WEBSITE_ID="3e855999-42a1-4543-accf-afc369edfca0";(function(){d=document;s=d.createElement("script");s.src="https://client.crisp.chat/l.js";s.async=1;d.getElementsByTagName("head")[0].appendChild(s);})();`,
            }}
          />
        </body>
      </PHProvider>
    </html>
  )
}
