import { Toaster } from "@/components/ui/sonner"
import { GlobalState } from "@/components/utility/global-state"
import { Providers } from "@/components/utility/providers"
import TranslationsProvider from "@/components/utility/translations-provider"
import initTranslations from "@/lib/i18n"
import { Database } from "@/supabase/types"
import { createServerClient } from "@supabase/ssr"
import { Metadata, Viewport } from "next"
import { Inter } from "next/font/google"
import { cookies } from "next/headers"
import { ReactNode } from "react"
import "./globals.css"
import { getRuntimeEnv } from "@/lib/ipconfig"  // 新增引入
import Script from "next/script"


const inter = Inter({ subsets: ["latin"] })
const APP_NAME = "ChatDesk UI"
const APP_DEFAULT_TITLE = "ChatDesk UI"
const APP_TITLE_TEMPLATE = "%s - ChatDesk UI"
const APP_DESCRIPTION = "ChatDesk UI PWA!"

interface RootLayoutProps {
  children: ReactNode
  params: {
    locale: string
  }
}

export async function generateMetadata({
  params: { locale }
}: {
  params: { locale: string }
}): Promise<Metadata> {
  const { t } = await initTranslations(locale, ["translation"])

  const appName = t("meta.appName")
  const defaultTitle = t("meta.defaultTitle")
  const description = t("meta.description")
  const titleTemplate = `%s - ${defaultTitle}`

  return {
    applicationName: appName,
    title: {
      default: defaultTitle,
      template: titleTemplate
    },
    description,
    manifest: "/manifest.json",
    appleWebApp: {
      capable: true,
      statusBarStyle: "black",
      title: defaultTitle
    },
    formatDetection: {
      telephone: false
    },
    openGraph: {
      type: "website",
      siteName: appName,
      title: {
        default: defaultTitle,
        template: titleTemplate
      },
      description
    },
    twitter: {
      card: "summary",
      title: {
        default: defaultTitle,
        template: titleTemplate
      },
      description
    }
  }
}

export const viewport: Viewport = {
  themeColor: "#000000"
}

const i18nNamespaces = ["translation"]

export default async function RootLayout({
  children,
  params: { locale }
}: RootLayoutProps) {
  const cookieStore = cookies()


  // 遍历所有 cookies
  for (const cookie of cookieStore.getAll()) {
    console.log(`🍪 Cookie: ${cookie.name} = ${cookie.value}`);
  }

  const supabaseUrl = getRuntimeEnv("SUPABASE_URL");
  console.log("=================>Server's Supabase URL: ", supabaseUrl);
    
  const supabase = createServerClient<Database>(
    getRuntimeEnv("SUPABASE_URL") ?? "http://localhost:8000",
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        get(name: string) {
          return cookieStore.get(name)?.value
        }
      }
    }
  )
  // const session = (await supabase.auth.getSession()).data.session
  const { data, error } = await supabase.auth.getSession();
  if (error) {
    console.log("[layout.tsx]............Session Error: ", error);
  } else {
    console.log("[layout.tsx]............Session Data: ", data.session);
  }

  const { t, resources } = await initTranslations(locale, i18nNamespaces)

  //console.log("[layout.tsx]..............current locale: ", {locale});

  return (
    <html lang="en" suppressHydrationWarning>
    
      <head>
        {/* ✅ 注入客户端运行时环境变量 */}
        <Script src="/env.js" strategy="beforeInteractive" />
      </head>

      <body className={inter.className}>
        <Providers attribute="class" defaultTheme="dark">
          <TranslationsProvider
            namespaces={i18nNamespaces}
            locale={locale}
            resources={resources}
          >
            <Toaster richColors position="top-center" duration={3000} />
            <div className="bg-background text-foreground flex h-dvh flex-col items-center overflow-x-auto">
              {data.session ? <GlobalState>{children}</GlobalState> : children}
            </div>
          </TranslationsProvider>
        </Providers>
      </body>
    </html>
  )
}
