import { notFound } from 'next/navigation';
import { NextIntlClientProvider } from 'next-intl';
import { getMessages } from 'next-intl/server';
import { themeApi } from '@/lib/api';
import { tokensToCss, googleFontHref, isRtl } from '@/lib/theme';
import { locales, type Locale } from '@/i18n';
import { Header } from '@/components/layout/Header';
import { Footer } from '@/components/layout/Footer';
import { BottomNav } from '@/components/layout/BottomNav';
import { SkipToContent } from '@/components/layout/SkipToContent';
import { AuthProvider } from '@/components/auth/AuthProvider';
import { FloatingCartSummary } from '@/components/ui/floating-cart-summary';
import { ToastProvider } from '@/components/ui/Toaster';
import { QueryProvider } from '@/components/providers/query-provider';
import type { Branding } from '@/types/api';
import '../globals.css';

const DEFAULT_BRANDING: Branding = {
  public_id: 'default',
  site_name: 'InstaParty',
  tagline: null,
  address_line: null,
  support_email: null,
  support_phone: null,
  whatsapp_number: null,
  social: {},
  assets: { logo_light: null, logo_dark: null, favicon: null, og_image: null, app_store_badge: null, play_store_badge: null },
  updated_at: null,
};

export async function generateMetadata({ params }: { params: Promise<{ locale: string }> }) {
  const { locale } = await params;
  if (!locales.includes(locale as Locale)) return {};

  try {
    const branding = await themeApi.getBranding(locale);
    return {
      title: { default: branding.site_name, template: `%s — ${branding.site_name}` },
      description: branding.tagline ?? undefined,
      icons: branding.assets.favicon
        ? [{ url: branding.assets.favicon }]
        : [{ url: '/favicon.svg', type: 'image/svg+xml' }],
      openGraph: branding.assets.og_image ? { images: [branding.assets.og_image] } : undefined,
    };
  } catch {
    return { title: 'InstaParty' };
  }
}

export default async function LocaleLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;
  if (!locales.includes(locale as Locale)) notFound();

  const [tokensResult, brandingResult, headerMenu, footerPrimary, footerSecondary, mobileDrawer] = await Promise.all([
    themeApi.getTokens(locale).catch(() => null),
    themeApi.getBranding(locale).catch(() => null),
    themeApi.getMenu('header', locale).catch(() => ({ slot: 'header', name: 'Header', items: [] })),
    themeApi.getMenu('footer_primary', locale).catch(() => ({ slot: 'footer_primary', name: 'Footer', items: [] })),
    themeApi.getMenu('footer_secondary', locale).catch(() => ({ slot: 'footer_secondary', name: 'Footer 2', items: [] })),
    themeApi.getMenu('mobile_drawer', locale).catch(() => ({ slot: 'mobile_drawer', name: 'Mobile', items: [] })),
  ]);

  const branding = brandingResult ?? DEFAULT_BRANDING;
  const messages = await getMessages();
  const css = tokensResult ? tokensToCss(tokensResult.tokens) : '';
  const fontHref = tokensResult ? googleFontHref(tokensResult.tokens) : null;
  const dir = isRtl(locale) ? 'rtl' : 'ltr';

  return (
    <html lang={locale} dir={dir}>
      <head>
        {fontHref ? <link rel="stylesheet" href={fontHref} /> : null}
        <style dangerouslySetInnerHTML={{ __html: css }} />
      </head>
      <body>
        <NextIntlClientProvider messages={messages} locale={locale}>
          <QueryProvider>
          <ToastProvider>
          <AuthProvider>
            <SkipToContent />
            <Header branding={branding} menu={headerMenu} mobileDrawer={mobileDrawer} locale={locale} />
            <main id="main" className="min-h-[60vh] pb-16 md:pb-0">
              {children}
            </main>
            <Footer branding={branding} primary={footerPrimary} secondary={footerSecondary} locale={locale} />
            <BottomNav locale={locale} />
            <FloatingCartSummary locale={locale} />
          </AuthProvider>
          </ToastProvider>
          </QueryProvider>
        </NextIntlClientProvider>
      </body>
    </html>
  );
}
