import { CookieConsent } from '@/components/cookies';
import { Footer } from '@/components/layout/footer';
import Navbar from '@/components/layout/navbar';
import { ReduxProvider } from '@/lib/redux/provider';
import { cn } from '@/lib/utils';
import { CartProvider } from 'components/cart/cart-context';
import { getCart } from 'lib/shopify';
import { ensureStartsWith } from 'lib/utils';
import type { Metadata } from 'next';
import { cookies } from 'next/headers';
import { ReactNode } from 'react';
import { Toaster } from 'sonner';
import './globals.css';

// Add font loading check
if (typeof window !== 'undefined') {
  document.fonts.ready.then(() => {
    console.log('Fonts have loaded.');
    document.fonts.forEach(font => {
      console.log(`Font family: ${font.family}, Status: ${font.status}`);
    });
  });
}

const { TWITTER_CREATOR, TWITTER_SITE, SITE_NAME } = process.env;
const baseUrl = process.env.NEXT_PUBLIC_VERCEL_URL
  ? `https://${process.env.NEXT_PUBLIC_VERCEL_URL}`
  : 'http://localhost:3000';
const twitterCreator = TWITTER_CREATOR ? ensureStartsWith(TWITTER_CREATOR, '@') : undefined;
const twitterSite = TWITTER_SITE ? ensureStartsWith(TWITTER_SITE, 'https://') : undefined;

export const metadata: Metadata = {
  metadataBase: new URL(baseUrl),
  title: {
    default: SITE_NAME!,
    template: `%s | ${SITE_NAME}`
  },
  robots: {
    follow: true,
    index: true
  },
  ...(twitterCreator &&
    twitterSite && {
      twitter: {
        card: 'summary_large_image',
        creator: twitterCreator,
        site: twitterSite
      }
    })
};

export default async function RootLayout({ children }: { children: ReactNode }) {
  const allCookies = await cookies();
  const cartId = allCookies.get('cartId')?.value;
  // Don't await the fetch, pass the Promise to the context provider
  const cart = getCart(cartId);
  
  // Get locale from cookie
  const localeCookie = allCookies.get('NEXT_LOCALE')?.value;
  const locale = localeCookie || 'hr';

  return (
    <html lang={locale}>
      <head>
        <meta name="theme-color" content="#ffffff" />
        <link
          rel="stylesheet"
          href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"
          integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g=="
          crossOrigin="anonymous"
          referrerPolicy="no-referrer"
        />
      </head>
      <body className={cn("min-h-screen bg-white antialiased")}>
        <ReduxProvider>
          <CartProvider cartPromise={cart}>
            <CookieConsent>
              <div className="flex flex-col min-h-screen">
                <Navbar />
                <main className="flex-grow">
                  {children}
                  <Toaster closeButton />
                </main>
                <Footer />
              </div>
            </CookieConsent>
          </CartProvider>
        </ReduxProvider>
      </body>
    </html>
  );
}
