import type { Metadata } from 'next'
import { cookies } from 'next/headers'
import { DashboardI18nProvider } from '@/components/I18nProvider'
import { SHARED_LANGUAGE_COOKIE } from '@/lib/preferences'
import './globals.css'

export const metadata: Metadata = {
  title: 'RentalDriveGo Dashboard',
  description: 'Manage your rental car business',
}

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

export default function RootLayout({ children }: { children: React.ReactNode }) {
  const cookieStore = 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">
        <DashboardI18nProvider initialLanguage={initialLanguage}>{children}</DashboardI18nProvider>
      </body>
    </html>
  )
}
