import type { Metadata, Viewport } from 'next'
import { notFound } from 'next/navigation'
import { ThemeScript } from '@/components/Theme'
import { publicConfig } from '@/lib/config'
import { dir, isLocale } from '@/lib/site'

// Every page reads the CMS on each request, so an edit shows at once.
export const dynamic = 'force-dynamic'

export const metadata: Metadata = {
  metadataBase: new URL(process.env.SITE_URL || 'http://localhost:8890'),
  icons: { icon: [{ url: '/brand/favicon.svg', type: 'image/svg+xml' }, { url: '/brand/favicon.ico' }], apple: '/brand/apple-touch-icon.png' },
}
export const viewport: Viewport = { width: 'device-width', initialScale: 1 }

// The Google Analytics measurement id, from GANALYTICSCODE in .env. Empty (or malformed) means no tag at all;
// every page is rendered per request, so changing it needs a restart, not a rebuild.
const ga = (process.env.GANALYTICSCODE || '').trim()
const gaId = /^[A-Za-z0-9_-]{6,32}$/.test(ga) ? ga : ''

export default async function Layout({ children, params }: { children: React.ReactNode; params: Promise<{ locale: string }> }) {
  const { locale } = await params
  if (!isLocale(locale)) notFound()
  const cfg = publicConfig()
  return (
    <html lang={locale} dir={dir(locale)}>
      <head>
        <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="" />
        <link
          rel="stylesheet"
          href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+Arabic:wght@400;500;600;700&family=Space+Grotesk:wght@500;700&display=swap"
        />
        <link rel="stylesheet" href="/brand/tokens.css?v=20261008" />
        <link rel="stylesheet" href="/assets/css/site.css?v=20261017" />
        {/* Sets data-theme before the first paint, so a visitor who chose dark never sees a white
            frame. It must be here, inline and blocking: React mounts after that paint. */}
        <ThemeScript fallback={cfg.defaultTheme} />
        {gaId ? (
          <>
            <script async src={`https://www.googletagmanager.com/gtag/js?id=${gaId}`} />
            <script
              dangerouslySetInnerHTML={{
                __html: `window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${gaId}');`,
              }}
            />
          </>
        ) : null}
      </head>
      <body>
        <div className="shell">{children}</div>
      </body>
    </html>
  )
}
