import type { Metadata } from 'next'
import { cookies } from 'next/headers'
import { JetBrains_Mono } from 'next/font/google'
import '@fontsource-variable/inter/index.css'
import '@fontsource-variable/noto-sans-arabic/index.css'
import { DashboardI18nProvider } from '@/components/I18nProvider'
import { SHARED_LANGUAGE_COOKIE } from '@/lib/preferences'
import './globals.css'

const jetbrainsMono = JetBrains_Mono({
  subsets: ['latin'],
  variable: '--font-mono',
  display: 'swap',
})

export const metadata: Metadata = {
  title: 'RentalDriveGo Dashboard',
  description: 'Manage your rental car business',
  icons: {
    icon: '/icon.svg',
    shortcut: '/icon.svg',
  },

}

function resolveInitialLanguage(value: string | undefined): 'en' | 'fr' | 'ar' {
  return value === 'fr' || value === 'ar' || value === 'en' ? value : 'en'
}

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const cookieStore = await cookies()
  const initialLanguage = resolveInitialLanguage(
    cookieStore.get(SHARED_LANGUAGE_COOKIE)?.value ?? cookieStore.get('dashboard-language')?.value,
  )
  const dir = initialLanguage === 'ar' ? 'rtl' : 'ltr'

  return (
    <html lang={initialLanguage} dir={dir} className="light" suppressHydrationWarning>
      <head>
        <script
          dangerouslySetInnerHTML={{
            __html:
              "(function(){try{var m=document.cookie.match(/(?:^|; )rentaldrivego-theme=([^;]+)/);var theme=m?decodeURIComponent(m[1]):(localStorage.getItem('rentaldrivego-theme')||localStorage.getItem('dashboard-theme'));if(theme!=='light'&&theme!=='dark'){theme=window.matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light'}var rootTheme=theme==='light'?'light':'dark';document.documentElement.classList.remove('light','dark');document.documentElement.classList.add(rootTheme);document.documentElement.style.colorScheme=rootTheme;document.body&&document.body.setAttribute('data-theme',theme)}catch(e){}})();",
          }}
        />
      </head>
      <body className={`font-sans ${jetbrainsMono.variable}`}>
        <DashboardI18nProvider initialLanguage={initialLanguage}>{children}</DashboardI18nProvider>
      </body>
    </html>
  )
}
