import type { ReactNode } from "react";
import { unstable_noStore as noStore } from "next/cache";
import { NextIntlClientProvider } from "next-intl";
import { getMessages, setRequestLocale } from "next-intl/server";
import { notFound } from "next/navigation";

import { routing } from "@/i18n/routing";
import { getDirection } from "@/lib/locale";

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

export const dynamic = "force-dynamic";
export const revalidate = 0;

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

export default async function LocaleLayout({
  children,
  params,
}: LocaleLayoutProps) {
  noStore();
  const { locale } = await params;

  if (!routing.locales.includes(locale as (typeof routing.locales)[number])) {
    notFound();
  }

  setRequestLocale(locale);

  const messages = await getMessages();
  const localeClassName = locale === "ar" ? "font-arabic" : "font-latin";

  return (
    <NextIntlClientProvider messages={messages}>
      <div lang={locale} dir={getDirection(locale)} className={localeClassName}>
        {children}
      </div>
    </NextIntlClientProvider>
  );
}
