import type { Metadata, Viewport } from "next";
import { Lora, Geist_Mono } from "next/font/google";
import { headers } from "next/headers";
import { Providers } from "@/components/providers";
import { auth } from "@/lib/auth/server";
import type { Locale } from "@/lib/i18n/provider";
import { SwRegister } from "@/components/pwa/sw-register";
import { InstallPrompt } from "@/components/pwa/install-prompt";
import { OfflineSyncManager } from "@/components/pwa/offline-sync-manager";
import { getMarketingLocale } from "@/lib/marketing-locale";
import "./globals.css";

const lora = Lora({
  variable: "--font-lora",
  subsets: ["latin"],
  display: "swap",
});

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

export const metadata: Metadata = {
  title: "Epicure",
  description: "Your personal AI-powered recipe book.",
  manifest: "/manifest.webmanifest",
  icons: {
    icon: "/icon.svg",
    apple: "/icon.svg",
  },
  appleWebApp: {
    capable: true,
    statusBarStyle: "default",
    title: "Epicure",
  },
};

export const viewport: Viewport = {
  themeColor: "#18181b",
  viewportFit: "cover",
};

export default async function RootLayout({
  children,
}: Readonly<{ children: React.ReactNode }>) {
  const session = await auth.api.getSession({ headers: await headers() }).catch(() => null);
  // Signed-in users: their saved preference. Anonymous visitors (marketing
  // pages): the marketing-locale cookie instead, since there's no account to
  // read a preference from.
  const initialLocale = ((session?.user as { locale?: string })?.locale ?? await getMarketingLocale()) as Locale;

  return (
    <html
      lang={initialLocale}
      suppressHydrationWarning
      className={`${lora.variable} ${geistMono.variable} h-full antialiased`}
    >
      <body className="min-h-full flex flex-col">
        <Providers initialLocale={initialLocale}>{children}</Providers>
        <SwRegister />
        <InstallPrompt />
        <OfflineSyncManager />
      </body>
    </html>
  );
}
