import '@fontsource-variable/inter/index.css';
import '@fontsource-variable/noto-sans-arabic/index.css';
import '@/styles/tokens.css';
import '@/styles/component-tokens.css';
import '@/styles/globals.css';

import { SiteFooter } from '@/components/app-shell/SiteFooter';
import { DemoDialogHost } from '@/components/integrations/DemoDialogHost';
import { SiteHeader } from '@/components/app-shell/SiteHeader';
import { ThemeController } from '@/components/app-shell/ThemeController';
import { getPublicIntegrationConfig } from '@/lib/integrations/environment';
import { getDirection, isLocale, type Locale } from '@/lib/localization/config';
import { getMessages } from '@/lib/localization/messages';
import { themeBootstrapScript } from '@/lib/theme/bootstrap-script';
import {
  isThemePreference,
  serverResolvedTheme,
  themeCookie,
  type ThemePreference,
} from '@/lib/theme/config';
import { cookies, headers } from 'next/headers';
import { notFound } from 'next/navigation';
import type { ReactNode } from 'react';

export const dynamic = 'force-dynamic';

interface LocaleLayoutProps {
  children: ReactNode;
  params: Promise<{ locale: string }>;
}

export default async function LocaleLayout({ children, params }: LocaleLayoutProps) {
  const { locale: localeValue } = await params;
  if (!isLocale(localeValue)) notFound();
  const locale: Locale = localeValue;
  const messages = getMessages(locale);
  const integrationConfig = getPublicIntegrationConfig();
  const requestHeaders = await headers();
  const nonce = requestHeaders.get('x-nonce') ?? undefined;
  const cookieStore = await cookies();
  const cookiePreference = cookieStore.get(themeCookie)?.value;
  const preference: ThemePreference = isThemePreference(cookiePreference)
    ? cookiePreference
    : 'system';
  const resolvedTheme = serverResolvedTheme(preference);

  return (
    <html
      lang={locale}
      dir={getDirection(locale)}
      data-theme-preference={preference}
      data-theme={resolvedTheme}
      suppressHydrationWarning
    >
      <head>
        <script
          id="theme-bootstrap"
          nonce={nonce}
          suppressHydrationWarning
          dangerouslySetInnerHTML={{ __html: themeBootstrapScript }}
        />
      </head>
      <body>
        <ThemeController />
        <a className="skip-link" href="#main-content">
          {messages.shell.skipToContent}
        </a>
        <SiteHeader
          locale={locale}
          messages={messages.shell}
          themePreference={preference}
          demoEnabled={integrationConfig.demoSubmissionEnabled}
        />
        {children}
        <DemoDialogHost
          locale={locale}
          messages={messages.homepage.form}
          enabled={integrationConfig.demoSubmissionEnabled}
        />
        <SiteFooter
          locale={locale}
          messages={messages.shell}
          demoEnabled={integrationConfig.demoSubmissionEnabled}
        />
      </body>
    </html>
  );
}
