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

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

export default function RootLayout({ children }: { children: React.ReactNode }) {
  const language = getMarketplaceLanguage()
  const cookieStore = cookies()
  const rawTheme =
    cookieStore.get('rentaldrivego-theme')?.value ??
    cookieStore.get('marketplace-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('marketplace-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>
        <MarketplaceShell initialLanguage={language} initialTheme={theme}>{children}</MarketplaceShell>
      </body>
    </html>
  )
}
