import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { Header } from "@/components/Header";
import { Footer } from "@/components/footer/Footer";
import { BASE_URL } from "@/lib/metadata";
import { getSiteInfo } from "@/lib/data";
import { getLanguage } from "@/lib/language";
import { getTheme } from "@/lib/theme";
import { getTranslations } from "@/lib/translations";
import { DEFAULT_LANGUAGE } from "@/types/language";
import { getColorTheme, hexToRgba } from "@/lib/color-theme";

// Optimize font loading with preload and subset optimization
const geistSans = Geist({
  variable: "--font-geist-sans",
  subsets: ["latin"],
  display: "swap",
  preload: true,
  fallback: ["system-ui", "arial"],
});

const geistMono = Geist_Mono({
  variable: "--font-geist-mono",
  subsets: ["latin"],
  display: "swap",
  preload: false, // Only preload primary font
  fallback: ["monospace"],
});

const langMap: Record<string, string> = {
  en: "en",
  pt: "pt",
  dk: "da",
  fr: "fr",
  nl: "nl",
  sv: "sv",
  es: "es",
};

// Force dynamic rendering to ensure siteInfo is always read fresh from the file
// This prevents Next.js from caching the layout with stale data
export const dynamic = 'force-dynamic';
export const revalidate = 0;

export async function generateMetadata(): Promise<Metadata> {
  const siteInfo = getSiteInfo();
  const language = await getLanguage();
  const htmlLang = langMap[language] || "pt";
  
  return {
    metadataBase: new URL(BASE_URL),
    title: {
      default: siteInfo.browserTitle || `${siteInfo.siteName} | Revisões de Parceiros de Apostas Confiáveis`,
      template: `%s | ${siteInfo.siteName}`,
    },
    description:
      "Compare parceiros do Reino Unido curados, explore bónus de boas-vindas verificados e reclame ofertas que atendem aos padrões de qualidade.",
    icons: {
      icon: siteInfo.favicon || "/favicon.ico",
      shortcut: siteInfo.favicon || "/favicon.ico",
      apple: "/apple-icon.png",
    },
  };
}

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  // Read siteInfo, language, and theme at runtime for layout
  const siteInfo = getSiteInfo();
  const language = await getLanguage();
  const theme = await getTheme();
  const translations = getTranslations(language);
  const htmlLang = langMap[language] || "pt";
  const colorTheme = getColorTheme(theme);
  
  // Create theme-based background gradients
  const backgroundGradients = `
    radial-gradient(circle at 20% 50%, ${hexToRgba(colorTheme.buttonBadge, 0.08)} 0%, transparent 60%),
    radial-gradient(circle at 80% 80%, ${hexToRgba(colorTheme.welcomeBonus, 0.06)} 0%, transparent 60%),
    radial-gradient(circle at 40% 20%, ${hexToRgba(colorTheme.buttonBadge, 0.04)} 0%, transparent 70%),
    radial-gradient(circle at 60% 70%, ${hexToRgba(colorTheme.welcomeBonus, 0.03)} 0%, transparent 70%),
    linear-gradient(135deg, ${colorTheme.cardBackground} 0%, ${hexToRgba(colorTheme.cardBackground, 0.95)} 25%, ${colorTheme.cardBackground} 50%, ${hexToRgba(colorTheme.cardBackground, 0.95)} 75%, ${colorTheme.cardBackground} 100%)
  `;
  
  const backgroundAfterGradients = `
    radial-gradient(circle at 30% 30%, ${hexToRgba(colorTheme.buttonBadge, 0.12)} 0%, transparent 50%),
    radial-gradient(circle at 70% 70%, ${hexToRgba(colorTheme.welcomeBonus, 0.1)} 0%, transparent 50%),
    radial-gradient(circle at 50% 50%, ${hexToRgba(colorTheme.buttonBadge, 0.06)} 0%, transparent 60%)
  `;
  
  const gridPatternColor = hexToRgba(colorTheme.buttonBadge, 0.02);
  
  return (
    <html lang={htmlLang} className={`${geistSans.variable} ${geistMono.variable}`}>
      <body 
        className="min-h-screen text-slate-100 antialiased relative"
        style={{
          background: backgroundGradients,
          backgroundColor: colorTheme.cardBackground,
          // Set CSS custom properties for scrollbar theming
          ['--theme-button-badge' as string]: colorTheme.buttonBadge,
          ['--theme-card-background' as string]: colorTheme.cardBackground,
        }}
      >
        {/* Theme-based scrollbar styles */}
        <style dangerouslySetInnerHTML={{
          __html: `
            ::-webkit-scrollbar-thumb {
              background: linear-gradient(to bottom, ${hexToRgba(colorTheme.buttonBadge, 0.5)}, ${hexToRgba(colorTheme.buttonBadge, 0.3)});
            }
            ::-webkit-scrollbar-thumb:hover {
              background: linear-gradient(to bottom, ${hexToRgba(colorTheme.buttonBadge, 0.7)}, ${hexToRgba(colorTheme.buttonBadge, 0.5)});
            }
            ::-webkit-scrollbar-track {
              background: ${hexToRgba(colorTheme.cardBackground, 0.8)};
              border-left: 1px solid ${hexToRgba(colorTheme.buttonBadge, 0.1)};
            }
          `
        }} />
        {/* Theme-based grid pattern overlay */}
        <div 
          className="fixed inset-0 pointer-events-none"
          style={{
            backgroundImage: `
              repeating-linear-gradient(0deg, transparent, transparent 2px, ${gridPatternColor} 2px, ${gridPatternColor} 4px),
              repeating-linear-gradient(90deg, transparent, transparent 2px, ${gridPatternColor} 2px, ${gridPatternColor} 4px)
            `,
            backgroundSize: '50px 50px',
            opacity: 0.4,
            zIndex: 0,
          }}
        />
        
        {/* Theme-based animated gradient overlay */}
        <div 
          className="fixed inset-0 pointer-events-none"
          style={{
            background: backgroundAfterGradients,
            animation: 'pulse 10s ease-in-out infinite',
            zIndex: 0,
          }}
        />
        
        {/* Content wrapper with proper z-index */}
        <div className="relative z-10">
        <Header siteInfo={siteInfo} translations={translations} language={language} theme={theme} />
        <main className="mx-auto w-full max-w-6xl flex-1 px-4 py-2 sm:px-6 sm:py-4 lg:py-6">{children}</main>
        <Footer siteInfo={siteInfo} language={language} theme={theme} />
        </div>
      </body>
    </html>
  );
}
