import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { Toaster } from "@/components/ui/toaster";
import { Toaster as SonnerToaster } from "sonner";
import { LoadingProvider } from "@/contexts/LoadingContext";
import { LoadingBar } from "@/components/LoadingBar";
import { generateSEOMetadata, generateJsonLd } from "@/lib/seo";
import { db } from "@/lib/db";

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

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

export async function generateMetadata(): Promise<Metadata> {
  try {
    // Fetch SEO settings from database
    const settings = await db.systemSettings.findFirst();
    
    const seoSettings = {
      metaTitle: settings?.metaTitle || undefined,
      metaDescription: settings?.metaDescription || undefined,
      metaKeywords: settings?.metaKeywords || undefined,
      ogImage: settings?.ogImage || undefined,
      siteName: settings?.siteName || undefined,
      siteUrl: settings?.siteUrl || undefined, // This will be undefined for now
    };

    return generateSEOMetadata(seoSettings);
  } catch (error) {
    console.error('Error fetching SEO settings:', error);
    
    // Fallback metadata
    return {
      title: "Polres Wonosobo - Sistem Pelayanan Digital",
      description: "Layanan pengajuan dokumen kepolisian secara online yang mudah, cepat, dan terpercaya",
      keywords: "polres wonosobo, pelayanan polisi, pengajuan dokumen, kepolisian",
    };
  }
}

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  let seoSettings = {};
  let jsonLd = {};

  try {
    // Fetch settings for JSON-LD
    const settings = await db.systemSettings.findFirst();
    
    seoSettings = {
      metaTitle: settings?.metaTitle || undefined,
      metaDescription: settings?.metaDescription || undefined,
      metaKeywords: settings?.metaKeywords || undefined,
      ogImage: settings?.ogImage || undefined,
      siteName: settings?.siteName || undefined,
      siteUrl: settings?.siteUrl || undefined, // This will be undefined for now
    };

    jsonLd = generateJsonLd(seoSettings, 'organization');
  } catch (error) {
    console.error('Error fetching settings for JSON-LD:', error);
  }

  return (
    <html lang="id" suppressHydrationWarning>
      <head>
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
        />
      </head>
      <body
        className={`${geistSans.variable} ${geistMono.variable} antialiased bg-background text-foreground`}
      >
        <LoadingProvider>
          {children}
          <LoadingBar />
          <Toaster />
          <SonnerToaster />
        </LoadingProvider>
      </body>
    </html>
  );
}
