import '@/app/globals.css';
import Header from '@/components/frontend/layout/Header';
import Footer from '@/components/frontend/layout/Footer';
import { fetchMenus } from '@/lib/menu/fetchMenu';
import { notFound } from 'next/navigation';
import { NextIntlClientProvider } from 'next-intl';
import { getMessages } from 'next-intl/server';
import { getLanguages } from '@/lib/db/queries/getlanguages';
import { Language } from '@/types/language';
import { Toaster } from 'react-hot-toast';
import { CartUIProvider } from '@/components/frontend/cart/CartUIContext';
import { getCurrencySettings } from '@/lib/db/queries/getCurrencySettings';
import CurrencyStoreSync from '@/components/frontend/CurrencyStoreSync';
import { getCheckoutSettings } from '@/lib/db/queries/getCheckoutSettings';
import CheckoutSettingsSync from '@/components/frontend/CheckoutSettingsSync';
import LazyQuickViewModal from '@/components/frontend/LazyQuickViewModal';
import ReferralCapture from '@/components/frontend/ReferralCapture';
import StoreMessagesSync from '@/components/frontend/StoreMessagesSync';
import MotionProvider from '@/components/frontend/MotionProvider';
import { getSiteInfo } from '@/lib/db/queries/getSiteInfo';

interface RootLayoutProps {
  children: React.ReactNode;
  params: Promise<{ locale: string }>;
}

export default async function RootLayout({
  children,
  params
}: RootLayoutProps) {
  const { locale } = await params;

  // ─── Get all languages (uses cache) ──────────────────────────────────
  const allLanguages: Language[] = await getLanguages();

  // ─── Validate current locale ──────────────────────────────────────────
  const isValidLocale: boolean = allLanguages.some(
    (lang: Language) => lang.code === locale
  );

  if (!isValidLocale) {
    notFound();
  }

  // ─── Get current language for RTL ─────────────────────────────────────
  const currentLang: Language | undefined = allLanguages.find(
    (lang: Language) => lang.code === locale
  );
  const isRTL: boolean = currentLang?.is_rtl === 1;

  // ─── Everything else the shell needs, fetched in parallel ─────────────
  // These used to be five sequential awaits (messages → menus → currency →
  // checkout settings → site info), so the layout's time-to-first-byte was
  // the *sum* of all of them. They're independent, and each one is cached
  // (unstable_cache / module cache), so the wait is now the slowest one.
  const [messages, menus, currency, checkoutSettings, siteInfo] = await Promise.all([
    getMessages(),
    fetchMenus(['header-complete'], locale),
    getCurrencySettings(),
    getCheckoutSettings(),
    getSiteInfo(),
  ]);
  const mainMenu = menus['header-complete'] || [];
  // `Auth` is only read by the (auth) route group, which has its own provider —
  // no need to embed it in every storefront page.
  const { Auth: _authMessages, ...clientMessages } = messages;
  void _authMessages;

  // This route group's layout sits *inside* the single <html>/<body> shell
  // owned by src/app/layout.tsx — it must not render its own html/body.
  return (
    <div lang={locale} dir={isRTL ? 'rtl' : 'ltr'}>
      <NextIntlClientProvider messages={clientMessages} locale={locale}>
        <MotionProvider>
          <CurrencyStoreSync code={currency.code} symbol={currency.symbol} format={currency.format} />
          <CheckoutSettingsSync {...checkoutSettings} />
          <ReferralCapture />
          <StoreMessagesSync />
          <CartUIProvider>
            <Header
              mainMenu={mainMenu}
              languages={allLanguages}
              currentLocale={locale}
              logoUrl={siteInfo.headerLogoUrl}
              logoAlt={siteInfo.headerLogoAlt}
            />
            <main>{children}</main>
            <Footer />
          </CartUIProvider>
          <LazyQuickViewModal />
          <Toaster
            position="top-right"
            toastOptions={{
              duration: 3000,
              style: {
                background: 'white',
                color: '#1f2937',
                border: '1px solid #e5e7eb',
                borderRadius: '12px',
                padding: '12px 16px',
              },
              success: { iconTheme: { primary: 'var(--primary)', secondary: 'white' } },
              error: { iconTheme: { primary: '#dc2626', secondary: 'white' } },
            }}
          />
        </MotionProvider>
      </NextIntlClientProvider>
    </div>
  );
}
