import type { Metadata } from 'next'
import { cookies } from 'next/headers'
import StorefrontShell from '@/components/StorefrontShell'
import { getStorefrontLanguage } from '@/lib/i18n.server'
import './globals.css'

export const metadata: Metadata = {
  title: 'RentalDriveGo Storefront',
  description: 'Discover vehicles from trusted rental companies.',
  icons: {
    icon: '/rentaldrivego.png',
    shortcut: '/favicon.ico',
    apple: '/rentaldrivego.png',
  },
}

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const language = await getStorefrontLanguage()
  const cookieStore = await cookies()
  const rawTheme =
    cookieStore.get('rentaldrivego-theme')?.value ??
    cookieStore.get('storefront-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')||localStorage.getItem('storefront-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>
        <StorefrontShell initialLanguage={language} initialTheme={theme}>{children}</StorefrontShell>
      </body>
    </html>
  )
}
