import React, { Suspense } from 'react';
import type { Metadata } from 'next';
import Script from 'next/script';
import './globals.css';
import { APP_CONFIG } from '@/config/app';
import { SHOPIFY_CONFIG } from '@/config/shopify';
import { BrandingProvider } from '@/context/BrandingContext';
import PolarisProvider from '@/components/providers/PolarisProvider';
import ShopifyNavMenu from '@/components/navigation/ShopifyNavMenu';
import ApiUrlInterceptor from '@/components/common/ApiUrlInterceptor';
import { normalizeAssetUrl } from '@/lib/utils/asset';

export const metadata: Metadata = {
  title: `${APP_CONFIG.name} - Multi Facebook Pixels & CAPI`,
  description: APP_CONFIG.description,
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const apiKey = SHOPIFY_CONFIG.apiKey;
  const logoPath = normalizeAssetUrl('/images/logo.png');
  const faviconPath = normalizeAssetUrl('/favicon.ico');

  return (
    <html lang="en">
      <head>
        <meta name="shopify-api-key" content={apiKey} />
        {/* Enable Shopify App Bridge Core Web Vitals real-time metrics monitoring & debug */}
        <meta name="shopify-debug" content="web-vitals" />
        <link rel="icon" type="image/x-icon" href={faviconPath} />
        <link rel="shortcut icon" href={faviconPath} />
        <link rel="apple-touch-icon" href={logoPath} />
        <link rel="preconnect" href="https://cdn.shopify.com" crossOrigin="anonymous" />
        <link rel="dns-prefetch" href="https://cdn.shopify.com" />
        {/* Load official Shopify App Bridge v4 */}
        <script src="https://cdn.shopify.com/shopifycloud/app-bridge.js"></script>
      </head>
      <body className="antialiased bg-slate-50 text-slate-900 font-sans min-h-screen flex flex-col">
        <ApiUrlInterceptor />
        <PolarisProvider>
          <BrandingProvider>
            <Suspense
              fallback={
                <div className="min-h-screen flex items-center justify-center bg-slate-50 text-slate-700">
                  <div className="flex flex-col items-center gap-3">
                    <img
                      src={logoPath}
                      alt="App Logo"
                      width={48}
                      height={48}
                      className="w-12 h-12 object-contain rounded-2xl shadow-sm"
                    />
                    <div className="w-7 h-7 border-3 border-theme border-t-transparent rounded-full animate-spin"></div>
                    <p className="text-xs font-semibold text-slate-600">Loading {APP_CONFIG.name}...</p>
                  </div>
                </div>
              }
            >
              <ShopifyNavMenu />
              {children}
            </Suspense>
          </BrandingProvider>
        </PolarisProvider>
      </body>
    </html>
  );
}
