// src/app/(superadmin)/layout.tsx — God-Mode shell.
//
// A route group SIBLING of (app): everything under /admin renders here, fully
// separated from the customer app (no AppSidebar, distinct dark/red chrome).
// Gate (defence in depth — server actions re-assert too):
//   1. no session          → redirect("/login")
//   2. not a SYS operator  → notFound() (404, never reveal the surface exists)
//   3. 2FA not enabled     → full-page interstitial (NO redirect — avoid loops)
//   4. otherwise           → the God-Mode shell, nav filtered by permissions.
import { headers } from "next/headers";
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { getTranslations } from "next-intl/server";
import { AdminSidebar } from "@/components/admin/admin-sidebar";
import { SignOutButton } from "@/components/auth/sign-out-button";
import { Button } from "@/components/ui/button";
import { auth } from "@/lib/auth";
import { isSuperAdmin } from "@/lib/auth/super-admin";
import { currentSysPermissions } from "@/lib/auth/sys-permissions";

export default async function SuperAdminLayout({
  children,
}: Readonly<{ children: React.ReactNode }>) {
  const session = await auth.api.getSession({
    headers: await headers(),
    // God Mode must never authenticate off the 5-min cookie cache.
    query: { disableCookieCache: true },
  });
  const t = await getTranslations("SuperAdmin");

  if (!session?.user) redirect("/login");

  const role = (session.user as { role?: string | null }).role;
  const isAdminSys = isSuperAdmin(session.user.email);
  const isOperator = isAdminSys || role === "staff";
  if (!isOperator) notFound();

  // `disableCookieCache` above → fresh user fetch, so a just-enrolled operator's
  // twoFactorEnabled is already true on the redirect back from /staff-2fa.
  const twoFactorEnabled = Boolean(
    (session.user as { twoFactorEnabled?: boolean }).twoFactorEnabled,
  );

  if (!twoFactorEnabled) {
    return (
      <div className="flex min-h-svh flex-col items-center justify-center bg-zinc-950 p-6 text-center text-zinc-200">
        <div className="w-full max-w-md space-y-4">
          <h1 className="font-semibold text-red-400 text-xl">
            {t("twoFaRequiredTitle")}
          </h1>
          <p className="text-sm text-zinc-400">{t("twoFaRequiredBody")}</p>
          <div className="flex justify-center gap-3 pt-2">
            <Button asChild>
              <Link href="/staff-2fa">{t("twoFaSetupCta")}</Link>
            </Button>
            <SignOutButton label={t("signOut")} />
          </div>
        </div>
      </div>
    );
  }

  const permissions = [...(await currentSysPermissions())];

  return (
    <div className="flex min-h-svh bg-zinc-100 dark:bg-zinc-900">
      <AdminSidebar permissions={permissions} />
      <div className="flex min-w-0 flex-1 flex-col">
        <header className="flex items-center justify-between gap-4 border-red-900/40 border-b bg-zinc-950 px-6 py-3 text-zinc-200">
          <span className="font-medium text-red-400 text-sm uppercase tracking-widest">
            {t("godModeBadge")}
          </span>
          <div className="flex items-center gap-4">
            <span className="text-sm text-zinc-400">{session.user.email}</span>
            <SignOutButton label={t("signOut")} variant="ghost" />
          </div>
        </header>
        <main className="min-w-0 flex-1 overflow-auto p-6">{children}</main>
      </div>
    </div>
  );
}
