import type { Metadata, Viewport } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import Script from "next/script";
import "../globals.css"; // Adjusted path
import { NextIntlClientProvider } from 'next-intl';
import { getMessages } from 'next-intl/server';
import { notFound } from 'next/navigation';
import { headers } from 'next/headers';

import { config } from "@/lib/config";
import { generateBaseMetadata } from "@/lib/metadata";
import InstallPrompt from "@/components/InstallPrompt";
import AppFooter from "@/components/AppFooter";
import PoliticalStatementBanner from "@/components/PoliticalStatementBanner";

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

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

export async function generateMetadata({ params }: { params: Promise<{ locale: string }> }): Promise<Metadata> {
    const { locale } = await params;
    return await generateBaseMetadata(locale);
}

export const viewport: Viewport = {
    themeColor: config.colors.themeColor,
    width: "device-width",
    initialScale: 1,
    maximumScale: 1,
};

export default async function LocaleLayout({
    children,
    params
}: {
    children: React.ReactNode;
    params: Promise<{ locale: string }>;
}) {
    const { locale } = await params;

    console.log('[app/[locale]/layout] params locale:', locale);

    // Ensure that the incoming `locale` is valid
    if (!['en', 'de'].includes(locale)) {
        console.log('[app/[locale]/layout] invalid locale, triggering notFound()');
        notFound();
    }

    // Providing all messages to the client
    const messages = await getMessages();

    // Get current domain from request headers for dynamic Plausible tracking
    // This automatically tracks the correct domain (hoerdle.de or hördle.de)
    const headersList = await headers();
    const host = headersList.get('host') || headersList.get('x-forwarded-host') || '';
    
    // Automatically detect which domain to track in Plausible based on the request
    let plausibleDomain = 'hoerdle.de'; // Default fallback
    
    if (host) {
        // Extract domain from host (remove port if present)
        const domain = host.split(':')[0].toLowerCase();
        
        // Map domains: automatically track the current domain
        if (domain === 'hoerdle.de') {
            plausibleDomain = 'hoerdle.de';
        } else if (domain === 'hördle.de' || domain === 'xn--hrdle-jua.de') {
            plausibleDomain = 'hördle.de';
        }
    }

    return (
        <html lang={locale}>
            <head>
                <Script
                    defer
                    data-domain={plausibleDomain}
                    src={config.plausibleScriptSrc}
                    strategy="beforeInteractive"
                />
            </head>
            <body className={`${geistSans.variable} ${geistMono.variable}`}>
                <NextIntlClientProvider messages={messages}>
                    {children}
                    <InstallPrompt />
                    <AppFooter />
                    <PoliticalStatementBanner />
                </NextIntlClientProvider>
            </body>
        </html>
    );
}
