import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { Header } from "@/components/Header";
import { Footer } from "@/components/Footer";
import { PageTransition } from "@/components/PageTransition";
import { NotificationBanner } from "@/components/NotificationBanner";
import { SanityLive } from "@/sanity/live";
import { loadSiteSettings } from "@/lib/settings";

const inter = Inter({
  subsets: ["latin"],
  display: "swap",
  variable: "--font-inter",
  weight: ["400", "500", "600", "700", "800"],
});

export async function generateMetadata(): Promise<Metadata> {
  let settings;
  try {
    settings = await loadSiteSettings();
  } catch {
    // During build without DB, fall back to sensible defaults so layout still
    // statically renders.
    settings = null;
  }
  const defaultTitle =
    settings?.seoDefaultTitle ||
    "OrthoGlobe — International Orthopaedic Charity Collaboration";
  const titleTemplate = settings?.seoTitleTemplate || "%s · OrthoGlobe";
  const description =
    settings?.seoDefaultDescription ||
    "OrthoGlobe is an international orthopaedic charity collaboration — a non-profit coalition of surgeons building open tools, atlases, and education for the global orthopaedic community.";
  const ogImage = settings?.seoOgImage || "/brand/orthoglobe-og.png";
  const robots = settings?.seoRobots || "index,follow";
  const twitterHandle = settings?.seoTwitterHandle || undefined;

  const robotIndex = robots.toLowerCase().includes("noindex") ? false : true;
  const robotFollow = robots.toLowerCase().includes("nofollow") ? false : true;

  const keywords = (settings?.seoKeywords || "")
    .split(",")
    .map((k) => k.trim())
    .filter(Boolean);

  return {
    title: { default: defaultTitle, template: titleTemplate },
    description,
    metadataBase: new URL("https://orthoglobe.org"),
    keywords: keywords.length > 0 ? keywords : undefined,
    openGraph: {
      title: settings?.siteName || "OrthoGlobe",
      description,
      type: "website",
      siteName: settings?.siteName || "OrthoGlobe",
      images: ogImage ? [{ url: ogImage }] : undefined,
    },
    twitter: twitterHandle
      ? {
          card: "summary_large_image",
          site: twitterHandle,
          creator: twitterHandle,
          images: ogImage ? [ogImage] : undefined,
        }
      : undefined,
    robots: { index: robotIndex, follow: robotFollow },
  };
}

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" className={inter.variable}>
      <body className="min-h-screen flex flex-col">
        <NotificationBanner />
        <Header />
        <main className="flex-1">
          <PageTransition>{children}</PageTransition>
        </main>
        <Footer />
        <SanityLive />
      </body>
    </html>
  );
}
