export const dynamic = "force-dynamic";

import { auth } from "@/lib/auth";
import { redirect } from "next/navigation";
import { SidebarNav, BottomNav } from "@/components/nav";
import { BabyProvider } from "@/contexts/baby-context";
import { QuickAddFab } from "@/components/quick-add-fab";
import { prisma } from "@/lib/prisma";
import { AlertTriangle } from "lucide-react";

async function getMaintenanceMode(): Promise<boolean> {
  try {
    const row = await prisma.systemConfig.findUnique({ where: { key: "maintenance_mode" } });
    return row?.value === "true";
  } catch {
    return false;
  }
}

export default async function AppLayout({ children }: { children: React.ReactNode }) {
  const session = await auth();
  if (!session?.user) redirect("/auth/login");

  const maintenance = await getMaintenanceMode();
  const isSuperAdmin = (session.user as { isSuperAdmin?: boolean })?.isSuperAdmin;

  return (
    <BabyProvider>
      <div className="min-h-screen bg-slate-50 dark:bg-slate-900">
        {maintenance && (
          <div className={`fixed top-0 left-0 right-0 z-[100] px-4 py-2.5 flex items-center gap-2 justify-center text-sm font-medium shadow-md ${
            isSuperAdmin
              ? "bg-amber-400/90 text-amber-900 text-xs py-1.5"
              : "bg-amber-500 text-white"
          }`}>
            <AlertTriangle className="w-4 h-4 flex-shrink-0" />
            {isSuperAdmin
              ? "Mode maintenance actif (visible des utilisateurs)"
              : "Maintenance en cours — certaines fonctionnalités peuvent être indisponibles"}
          </div>
        )}
        <SidebarNav />
        <main className={`app-main min-h-screen${maintenance ? " pt-10" : ""}`}>
          {children}
        </main>
        <BottomNav />
        <QuickAddFab />
      </div>
    </BabyProvider>
  );
}
