import type { Metadata } from 'next';
import { Fraunces, Inter, JetBrains_Mono, Caveat } from 'next/font/google';
import { headers } from 'next/headers';
import './globals.css';
import Header from '@/components/Header';
import Footer from '@/components/Footer';
import PromotionBanner from '@/components/PromotionBanner';
import MaintenancePage from '@/components/MaintenancePage';
import LogoutOnUnload from '@/components/LogoutOnUnload';
import { CurrencyProvider } from '@/lib/CurrencyContext';
import { getSiteSettings } from '@/lib/settings';
import { isAdminAuthenticated } from '@/lib/adminAuth';

const fraunces = Fraunces({
  subsets: ['latin'],
  variable: '--font-fraunces',
  axes: ['opsz', 'SOFT', 'WONK'],
});

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

const mono = JetBrains_Mono({ subsets: ['latin'], variable: '--font-mono' });

const caveat = Caveat({ subsets: ['latin'], variable: '--font-script', weight: ['500', '700'] });

export const metadata: Metadata = {
  title: 'Craft2Prints — Ink it. Print it. Love it.',
  description:
    'Design your own apparel, drinkware, and phone cases. Personalize a template, we print and ship it.',
};

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const { maintenanceMode, maintenanceMessage } = await getSiteSettings();
  const pathname = headers().get('x-pathname') ?? '';
  // Admins bypass maintenance (they can keep working); /admin/* is always
  // reachable so the owner can log in and toggle it back off.
  // Also allow /checkout/* pages so customers can complete purchases and see results.
  const showMaintenance =
    maintenanceMode &&
    !pathname.startsWith('/admin') &&
    !pathname.startsWith('/checkout') &&
    !(await isAdminAuthenticated());

  return (
    <html lang="en" suppressHydrationWarning className={`${fraunces.variable} ${inter.variable} ${mono.variable} ${caveat.variable}`}>
      <head>
        {/* Extra fonts available in the design tool's text options (loaded by real
            family name so the canvas can reference them directly). */}
        <link
          href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@600&family=Oswald:wght@500&family=Bebas+Neue&family=Pacifico&family=Permanent+Marker&family=Caveat:wght@600&display=swap"
          rel="stylesheet"
        />
        {/* Runs before paint so there's no flash of the wrong theme on load. */}
        <script
          dangerouslySetInnerHTML={{
            __html: `
              (function() {
                var stored = localStorage.getItem('theme');
                var prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
                var isDark = stored ? stored === 'dark' : prefersDark;
                if (isDark) document.documentElement.classList.add('dark');
              })();
            `,
          }}
        />
      </head>
      <body suppressHydrationWarning className="flex min-h-screen flex-col">
        <LogoutOnUnload />
        <CurrencyProvider>
          {showMaintenance ? (
            <MaintenancePage message={maintenanceMessage} />
          ) : (
            <>
              <PromotionBanner />
              <Header />
              <main className="flex-1">{children}</main>
              <Footer />
            </>
          )}
        </CurrencyProvider>
      </body>
    </html>
  );
}
