import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import PublicShell from "@/components/layout/PublicShell";
import Providers from "@/components/layout/Providers";
import SandboxBannerLoader from "@/components/shared/SandboxBannerLoader";
import ComingSoonGate from "@/components/shared/ComingSoonGate";
import { cookies, headers } from "next/headers";
import { db } from "@/lib/db";
import { unstable_cache } from "next/cache";

const geistSans = Geist({
  variable: "--font-geist-sans",
  subsets: ["latin"],
});

const geistMono = Geist_Mono({
  variable: "--font-geist-mono",
  subsets: ["latin"],
});

export const metadata: Metadata = {
  title: {
    default: "KC Systems Limited",
    template: "%s | KC Systems Limited",
  },
  description:
    "KC Systems Limited — e-commerce, career portal, knowledge journals, and international scholarships in one platform.",
  keywords: ["KC Systems", "jobs Malaysia", "scholarships", "e-commerce", "journals"],
  openGraph: {
    siteName: "KC Systems Limited",
    locale: "en_MY",
    type: "website",
  },
};

const getTesterSettings = unstable_cache(
  async () => {
    const [modeSetting, tokenSetting] = await Promise.all([
      db.siteSetting.findFirst({ where: { key: "tester_mode" } }),
      db.siteSetting.findFirst({ where: { key: "tester_token" } }),
    ]);
    return { mode: modeSetting?.value ?? null, token: tokenSetting?.value ?? null };
  },
  ["tester-settings"],
  { revalidate: 60 }
);

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  // ── Tester gate ────────────────────────────────────────────────────
  const headersList = await headers();
  const pathname = headersList.get("x-pathname") ?? "/";
  const isAdminOrApi = pathname.startsWith("/admin") || pathname.startsWith("/api");

  let showComingSoon = false;
  if (!isAdminOrApi) {
    const { mode, token } = await getTesterSettings();
    if (mode === "true" && token) {
      const cookieStore = await cookies();
      const cookieToken = cookieStore.get("kc_tester")?.value;
      showComingSoon = cookieToken !== token;
    }
  }

  return (
    <html lang="en" className={`${geistSans.variable} ${geistMono.variable} h-full`}>
      <body className="min-h-full flex flex-col antialiased">
        {showComingSoon ? (
          <ComingSoonGate />
        ) : (
          <>
            <SandboxBannerLoader />
            <Providers>
              <PublicShell>{children}</PublicShell>
            </Providers>
          </>
        )}
      </body>
    </html>
  );
}
