import type { Metadata } from "next"
import { Inter as FontSans } from "next/font/google"
import "./globals.css"
import { cn } from "@/lib/utils"
import { ThemeProvider } from "@/components/theme-provider"
import { UserProvider } from "@auth0/nextjs-auth0/client"
import { Toaster } from "@/components/ui/toaster"
import { getSession } from "@auth0/nextjs-auth0"
import Script from "next/script"
import { PHProvider } from "./providers"
import dynamic from "next/dynamic"

const PostHogPageView = dynamic(async () => await import("./PostHogPageView"), {
  ssr: false,
})

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

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

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode
}): Promise<JSX.Element> {
  const session = await getSession()
  let intercomSnippet: string = `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);}}})();
`

  if (session != null) {
    const user = session.user
    intercomSnippet += `
             window.Intercom('boot', {
                app_id: "ljxo1nzr",
                name: "${user.name}",
                nickname: "${user.nickname}",
                picture: "${user.picture}",
                user_id: "${user.sub}",
                email: null, //"${user.email}", // can be undefined
              });
             `
  } else {
    // logged out users don't have a nickname or email etc
    intercomSnippet += `
             window.Intercom('boot', {
                app_id: "ljxo1nzr"
              });
             `
  }

  /*
  <Script
            src="https://app.posthog.com/static/array.js"
            strategy="afterInteractive"
            onLoad={() => {
              window.posthog = window.posthog || []
              window.posthog.init("phc_aUO790jHd7z1SXwsYCz8dRApxueplZlZWeDSpKc5hol", {
                api_host: "https://app.posthog.com",
              })
            }}
          />
   */

  return (
    <html lang="en">
      <PHProvider>
        <head>
          <Script
            id="intercom-script"
            strategy="afterInteractive"
            dangerouslySetInnerHTML={{
              __html: intercomSnippet,
            }}
          />
        </head>
        <body className={cn("min-h-screen bg-background font-sans antialiased", fontSans.variable)}>
          <PostHogPageView />
          <UserProvider>
            <ThemeProvider
              attribute="class"
              defaultTheme="system"
              enableSystem
              disableTransitionOnChange
            >
              <div className="flex flex-col justify-between w-full h-full min-h-screen">
                <main className="flex-auto w-full max-w-none mx-auto">{children}</main>
                <Toaster />
              </div>
            </ThemeProvider>
          </UserProvider>
        </body>
      </PHProvider>
    </html>
  )
}
