import type { ReactNode } from "react";
import { unstable_noStore as noStore } from "next/cache";
import { redirect } from "next/navigation";

import { SiteAmbientBackdrop } from "@/components/layout/site-ambient-backdrop";
import { SiteFooter } from "@/components/layout/site-footer";
import { SiteHeader } from "@/components/layout/site-header";
import { isAdminAuthenticated } from "@/lib/admin-auth";
import { getMaintenanceMode, getSiteSettings, getSiteSettingsMediaBindings } from "@/lib/app-config";
import { FALLBACK_LOCALE, getLocalizedPath, resolveLocale } from "@/lib/locale";

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

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

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

  const localeKey = resolveLocale(locale, FALLBACK_LOCALE);
  const [maintenanceEnabled, mediaBindings, siteSettings] = await Promise.all([
    getMaintenanceMode(),
    getSiteSettingsMediaBindings(),
    getSiteSettings(),
  ]);
  const authenticated = await isAdminAuthenticated();

  if (maintenanceEnabled && !authenticated) {
    redirect(getLocalizedPath(localeKey, "/coming-soon", siteSettings.defaultLocale));
  }

  return (
    <div className="relative flex min-h-screen flex-col overflow-hidden">
      <SiteAmbientBackdrop />
      <SiteHeader
        lightLogoUrl={mediaBindings.siteLogoLight?.url}
        darkLogoUrl={mediaBindings.siteLogoDark?.url}
        defaultLocale={siteSettings.defaultLocale}
      />
      <main className="flex-1">{children}</main>
      <SiteFooter defaultLocale={siteSettings.defaultLocale} />
    </div>
  );
}
