import { FeatureFlagService } from '@/lib/feature/FeatureFlagService';
import { initializeGlobalErrorHandling } from '@/lib/infrastructure/GlobalErrorHandler';
import { initializeApiLogger } from '@/lib/infrastructure/ApiRequestLogger';
import { Metadata, Viewport } from 'next';
import React from 'react';
import './globals.css';
import { AppWrapper } from '@/components/AppWrapper';
import { RootAppShellTemplate } from '@/templates/layout/RootAppShellTemplate';
import { getWebsiteServerEnv } from '@/lib/config/env';
import { logger } from '@/lib/infrastructure/logging/logger';

export const dynamic = 'force-dynamic';

export const viewport: Viewport = {
  width: 'device-width',
  initialScale: 1,
  maximumScale: 1,
  userScalable: false,
  viewportFit: 'cover',
  themeColor: '#0a0a0a',
};

export const metadata: Metadata = {
  title: 'GridPilot - SimRacing Platform',
  description: 'The dedicated home for serious sim racing leagues. Automatic results, standings, team racing, and professional race control.',
  appleWebApp: {
    capable: true,
    statusBarStyle: 'black-translucent',
  },
  openGraph: {
    title: 'GridPilot - iRacing League Racing Platform',
    description: 'Structure over chaos. The professional platform for iRacing league racing.',
    type: 'website',
  },
  twitter: {
    card: 'summary_large_image',
    title: 'GridPilot - iRacing League Racing Platform',
    description: 'Structure over chaos. The professional platform for iRacing league racing.',
  },
  icons: {
    icon: '/favicon.svg',
  },
};

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  // Initialize debug tools in development
  const env = getWebsiteServerEnv();
  if (env.NODE_ENV === 'development') {
    try {
      initializeGlobalErrorHandling({
        showDevOverlay: true,
        verboseLogging: true,
        captureEnhancedStacks: true,
      });
      initializeApiLogger({
        logToConsole: true,
        logBodies: true,
        logResponses: true,
      });
    } catch (error) {
      logger.warn('Failed to initialize debug tools', { error });
    }
  }

  // Initialize feature flag service from API
  const featureService = await FeatureFlagService.fromAPI();
  const enabledFlags = featureService.getEnabledFlags();

  return (
    <html lang="en" className="scroll-smooth overflow-x-hidden" data-theme="default">
      <head>
        <meta name="mobile-web-app-capable" content="yes" />
      </head>
      <body className="antialiased">
        <AppWrapper enabledFlags={enabledFlags}>
          <RootAppShellTemplate>{children}</RootAppShellTemplate>
        </AppWrapper>
      </body>
    </html>
  );
}