// src/app/(auth)/[locale]/layout.tsx
import '@/app/globals.css';
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 MotionProvider from '@/components/frontend/MotionProvider';

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

export default async function AuthLayout({ children, params }: AuthLayoutProps) {
  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;

  // ─── Get messages ──────────────────────────────────────────────────────
  const allMessages = await getMessages();
  // The auth pages only ever read the `Auth` namespace (no header/footer/cart
  // UI lives in this route group), so ship just that to the client instead of
  // the whole ~30-40 KB catalog embedded in every auth page.
  const messages = { Auth: allMessages.Auth };

  // Sits inside the single <html>/<body> shell owned by src/app/layout.tsx —
  // must not render its own html/body. Previously this route group had no
  // layout at all, so login/verify-otp never loaded globals.css (Tailwind)
  // or ran locale validation.
  return (
    <div lang={locale} dir={isRTL ? 'rtl' : 'ltr'}>
      <NextIntlClientProvider messages={messages} locale={locale}>
        <MotionProvider>{children}</MotionProvider>
      </NextIntlClientProvider>
    </div>
  );
}
