import type { Metadata } from 'next'
import { cookies } from 'next/headers'
import CarplaceShell from '@/components/CarplaceShell'
import { getCarplaceMessages } from '@/lib/carplace/messages'
import { getCarplaceLanguage } from '@/lib/i18n.server'
import './globals.css'

export async function generateMetadata(): Promise<Metadata> {
  const language = await getCarplaceLanguage()
  const copy = getCarplaceMessages(language)
  return {
    title: `${copy.brand} by RentalDriveGo`,
    description: copy.hero.body,
    alternates: { canonical: '/carplace' },
    openGraph: {
      title: `${copy.brand} by RentalDriveGo`,
      description: copy.hero.body,
      type: 'website',
      locale: language === 'ar' ? 'ar_MA' : language === 'fr' ? 'fr_MA' : 'en_MA',
      siteName: 'RentalDriveGo',
    },
    icons: {
      icon: '/rentaldrivego.png',
      shortcut: '/favicon.ico',
      apple: '/rentaldrivego.png',
    },
  }
}

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const language = await getCarplaceLanguage()
  const cookieStore = await cookies()
  const rawTheme = cookieStore.get('rentaldrivego-theme')?.value
  const theme = rawTheme === 'dark' ? 'dark' : 'light'

  return (
    <html lang={language} dir={language === 'ar' ? 'rtl' : 'ltr'} suppressHydrationWarning>
      <head>
        {/* Runs before hydration to prevent flash of wrong theme */}
        <script
          dangerouslySetInnerHTML={{
            __html:
              "(function(){try{var m=document.cookie.match(/(?:^|; )rentaldrivego-theme=([^;]+)/);var theme=m?decodeURIComponent(m[1]):localStorage.getItem('rentaldrivego-theme');if(theme!=='light'&&theme!=='dark'){theme=window.matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light'}document.documentElement.classList.toggle('dark',theme==='dark');document.documentElement.style.colorScheme=theme;document.body&&document.body.setAttribute('data-theme',theme)}catch(e){}})();",
          }}
        />
      </head>
      <body suppressHydrationWarning>
        <CarplaceShell initialLanguage={language} initialTheme={theme}>{children}</CarplaceShell>
      </body>
    </html>
  )
}
