import Footer from '@/components/Footer';
import Header from '@/components/Header';
import JsonLd from '@/components/JsonLd';
import SkipLink from '@/components/SkipLink';
import CMSConnectivityNotice from '@/components/CMSConnectivityNotice';
import AnalyticsShell from '@/components/analytics/AnalyticsShell';
import { Metadata, Viewport } from 'next';
import { NextIntlClientProvider } from 'next-intl';
import { getMessages } from 'next-intl/server';
import { Suspense } from 'react';
import '../../styles/globals.css';
import { SITE_URL } from '@/lib/schema';
import { config } from '@/lib/config';
import FeedbackClientWrapper from '@/components/FeedbackClientWrapper';
import { setRequestLocale } from 'next-intl/server';
import { Inter } from 'next/font/google';

const inter = Inter({
  subsets: ['latin'],
  display: 'swap',
  variable: '--font-inter',
});

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

  const baseUrl = process.env.CI ? 'http://klz.localhost' : SITE_URL;
  return {
    title: {
      template: '%s | KLZ Cables',
      default: 'KLZ Cables | Ihr Partner für Kabel & Leitungen',
    },
    metadataBase: new URL(baseUrl),
    manifest: '/manifest.webmanifest',
    icons: {
      icon: [
        { url: '/favicon.ico', sizes: 'any' },
        { url: '/logo-blue.svg', type: 'image/svg+xml' },
      ],
      apple: [{ url: '/apple-touch-icon.png', sizes: '180x180', type: 'image/png' }],
    },
  };
}

export const viewport: Viewport = {
  width: 'device-width',
  initialScale: 1,
  maximumScale: 5,
  userScalable: true,
  viewportFit: 'cover',
  themeColor: '#001a4d',
};

export default async function Layout(props: {
  children: React.ReactNode;
  params: Promise<{ locale: string }>;
}) {
  const params = await props.params;
  const { locale } = params;
  const { children } = props;
  const supportedLocales = ['en', 'de'];
  const localeStr = (typeof locale === 'string' ? locale : '').trim();
  const safeLocale = supportedLocales.includes(localeStr) ? localeStr : 'en';

  setRequestLocale(safeLocale);

  let messages: Record<string, any> = {};
  try {
    messages = await getMessages();
  } catch (error) {
    messages = {};
  }

  // Pick only the namespaces required by client components to reduce the hydration payload size
  const clientKeys = [
    'Footer',
    'Navigation',
    'Contact',
    'Products',
    'Team',
    'Home',
    'Error',
    'StandardPage',
  ];
  const clientMessages: Record<string, any> = {};
  for (const key of clientKeys) {
    if (messages[key]) {
      clientMessages[key] = messages[key];
    }
  }

  const { getServerAppServices } = await import('@/lib/services/create-services.server');
  const serverServices = getServerAppServices();

  try {
    const { headers } = await import('next/headers');
    const requestHeaders = await headers();

    // Disable analytics in CI to prevent console noise/score penalties
    if (process.env.NEXT_PUBLIC_CI === 'true') {
      // Skip setting server context for analytics in CI
    } else if ('setServerContext' in serverServices.analytics) {
      (serverServices.analytics as any).setServerContext({
        userAgent: requestHeaders.get('user-agent') || undefined,
        language: requestHeaders.get('accept-language')?.split(',')[0] || undefined,
        referrer: requestHeaders.get('referer') || undefined,
        ip: requestHeaders.get('x-forwarded-for')?.split(',')[0] || undefined,
      });
    }

    // Server-side analytics tracking removed to prevent duplicate/empty events.
    // Client-side AnalyticsProvider handles all pageviews.
  } catch {
    if (process.env.NODE_ENV !== 'production' || !process.env.CI) {
      console.warn(
        '[Layout] Static generation detected or headers unavailable, skipping server-side analytics context',
      );
    }
  }

  // Read directly from process.env — bypasses all abstraction to guarantee correctness
  const feedbackEnabled = process.env.NEXT_PUBLIC_FEEDBACK_ENABLED === 'true';

  return (
    <html lang={safeLocale} className={`overflow-x-hidden ${inter.variable}`}>
      <head>
        <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
        <link rel="preconnect" href="https://img.infra.mintel.me" />
      </head>
      <body className="flex flex-col min-h-screen font-sans selection:bg-accent selection:text-primary-dark antialiased overflow-x-hidden">
        <NextIntlClientProvider messages={clientMessages} locale={safeLocale}>
          <SkipLink />
          <JsonLd />
          <Header />
          <main
            id="main-content"
            className="flex-grow animate-fade-in overflow-visible"
            tabIndex={-1}
          >
            {children}
          </main>
          <Footer />

          <CMSConnectivityNotice />

          <AnalyticsShell />
          <FeedbackClientWrapper feedbackEnabled={feedbackEnabled} />
        </NextIntlClientProvider>
      </body>
    </html>
  );
}
