import type { Metadata, Viewport } from 'next';
import { NextIntlClientProvider } from 'next-intl';
import { getMessages, setRequestLocale } from 'next-intl/server';
import { hasLocale } from 'next-intl';
import { notFound } from 'next/navigation';
import Script from 'next/script';
import { Noto_Sans_Arabic, Vazirmatn } from 'next/font/google';
import '@/styles/globals.css';
import '@/styles/background-web.css';
import { AuthProvider } from '@/lib/hooks/useAuth';
import { THEME_STORAGE_KEY } from '@/lib/theme';
import { routing, isRtlLocale, localeHtmlLang } from '@/i18n/routing';
import { LocaleSync } from '@/components/i18n/LocaleSync';

export const metadata: Metadata = {
  title: 'Nudentic - Dental Clinic & Lab Communication Hub',
  description: 'Connect dental clinics and laboratories seamlessly',
};

export const viewport: Viewport = {
  width: 'device-width',
  initialScale: 1,
};

export function generateStaticParams() {
  return routing.locales.map((locale) => ({ locale }));
}

const vazirmatn = Vazirmatn({
  subsets: ['arabic'],
  variable: '--font-vazirmatn',
  display: 'swap',
});

const notoSansArabic = Noto_Sans_Arabic({
  subsets: ['arabic'],
  variable: '--font-noto-sans-arabic',
  display: 'swap',
});

export default async function LocaleLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;

  if (!hasLocale(routing.locales, locale)) {
    notFound();
  }

  setRequestLocale(locale);
  const messages = await getMessages();

  const themeInit = `(function(){try{var k=${JSON.stringify(THEME_STORAGE_KEY)};var t=localStorage.getItem(k);document.documentElement.setAttribute('data-theme',t==='light'||t==='dark'?t:'light');}catch(e){document.documentElement.setAttribute('data-theme','light');}})();`;
  const dir = isRtlLocale(locale) ? 'rtl' : 'ltr';
  const fontSans = isRtlLocale(locale)
    ? 'var(--font-vazirmatn), var(--font-noto-sans-arabic), system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif'
    : 'system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif';

  return (
    <html
      lang={localeHtmlLang(locale)}
      dir={dir}
      data-locale={locale}
      data-theme="light"
      className={`${vazirmatn.variable} ${notoSansArabic.variable}`}
      style={{ ['--font-sans' as never]: fontSans }}
      suppressHydrationWarning
    >
      <body>
        <Script id="theme-init" strategy="beforeInteractive">
          {themeInit}
        </Script>
        <NextIntlClientProvider messages={messages}>
          <AuthProvider>
            <LocaleSync />
            {children}
          </AuthProvider>
        </NextIntlClientProvider>
      </body>
    </html>
  );
}
