import type { Metadata, Viewport } from "next";
import localFont from "next/font/local";
import "./globals.css";
import { Footer } from "@/components/footer";
import { Header } from "@/components/header";
import { CartProvider } from "@/components/cart-provider";
import { MobileActionBar } from "@/components/mobile-action-bar";
import { siteConfig } from "@/config/site";
import { BookingModalProvider } from "@/components/booking-modal";
import { getWebsiteMenu } from "@/lib/menu-db";
import { isSettingEnabled } from "@/lib/auth";
import { getSiteContactSettings } from "@/lib/site-settings";
import { HideInWebView } from "@/components/hide-in-webview";
import { CookieConsent } from "@/components/cookie-consent";

// Menu data comes from PostgreSQL at runtime; never query the production DB during image build.
export const dynamic = "force-dynamic";

const montserrat = localFont({
  variable: "--font-montserrat",
  display: "swap",
  src: [
    { path: "../../files/Fonts/Montserrat-Regular.ttf", weight: "400", style: "normal" },
    { path: "../../files/Fonts/Montserrat-SemiBold.ttf", weight: "600", style: "normal" },
    { path: "../../files/Fonts/Montserrat-ExtraBold.ttf", weight: "800", style: "normal" }
  ]
});

export const metadata: Metadata = {
  metadataBase: new URL(process.env.NEXT_PUBLIC_SITE_URL || "http://localhost:3000"),
  title: {
    default: "КИЛН - мясо, дым, время и немного магии",
    template: "%s | КИЛН"
  },
  description: "Камерный мясной рестобар и дровяная печь на улице Чайковского в Санкт-Петербурге.",
  alternates: {
    canonical: "/"
  },
  referrer: "no-referrer",
  openGraph: {
    title: "КИЛН - мясо, дым, время и немного магии",
    description: "Камерный мясной рестобар в центре Петербурга.",
    type: "website",
    locale: "ru_RU",
    images: ["/og/kiln-og.webp"]
  },
  manifest: "/manifest.webmanifest",
  icons: {
    icon: [
      { url: "/favicon.svg?v=2", type: "image/svg+xml" },
      { url: "/favicon-v2.png", type: "image/png", sizes: "32x32" }
    ],
    apple: [{ url: "/apple-touch-icon-v2.png", sizes: "180x180", type: "image/png" }]
  }
};

export const viewport: Viewport = {
  width: "device-width",
  initialScale: 1,
  maximumScale: 5,
  themeColor: "#090807"
};

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const metrikaId = process.env.NEXT_PUBLIC_YANDEX_METRIKA_ID;
  const menu = await getWebsiteMenu();
  const ordersEnabled = await isSettingEnabled("orders_enabled");
  const contact = await getSiteContactSettings();

  return (
    <html lang="ru">
      <body className={`${montserrat.variable} mobile-safe-pad`}>
        {metrikaId ? <CookieConsent metrikaId={Number(metrikaId)} /> : null}
        <BookingModalProvider>
          <CartProvider menuItems={menu.items} ordersEnabled={ordersEnabled}>
            <HideInWebView><Header phoneHref={contact.phoneHref} /></HideInWebView>
            <main>{children}</main>
            <HideInWebView><Footer /><MobileActionBar /></HideInWebView>
          </CartProvider>
        </BookingModalProvider>
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{
            __html: JSON.stringify({
              "@context": "https://schema.org",
              "@type": "Restaurant",
              name: siteConfig.name,
              description: siteConfig.description,
              servesCuisine: "Мясная кухня",
              priceRange: siteConfig.priceRange,
              hasMenu: `${process.env.NEXT_PUBLIC_SITE_URL || "http://localhost:3000"}/menu`,
              url: process.env.NEXT_PUBLIC_SITE_URL || "http://localhost:3000",
              geo: {
                "@type": "GeoCoordinates",
                latitude: siteConfig.coordinates.lat,
                longitude: siteConfig.coordinates.lng
              },
              address: {
                "@type": "PostalAddress",
                streetAddress: contact.address,
                addressLocality: "Санкт-Петербург",
                addressCountry: "RU"
              },
              telephone: contact.phone,
              openingHours: "Mo-Su 12:00-23:00"
            })
          }}
        />
      </body>
    </html>
  );
}
