import type { Metadata, Viewport } from "next";
import localFont from "next/font/local";
import Script from "next/script";
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";

// 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: "/"
  },
  openGraph: {
    title: "КИЛН - мясо, дым, время и немного магии",
    description: "Камерный мясной рестобар в центре Петербурга.",
    type: "website",
    locale: "ru_RU",
    images: ["/og/kiln-og.webp"]
  },
  manifest: "/manifest.webmanifest",
  icons: {
    icon: [{ url: "/favicon.ico" }, { url: "/favicon.svg", type: "image/svg+xml" }],
    apple: "/apple-touch-icon.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 ? (
          <>
            <Script id="yandex-metrika" strategy="afterInteractive">
              {`(function(m,e,t,r,i,k,a){m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)};
              m[i].l=1*new Date();
              for (var j = 0; j < document.scripts.length; j++) {if (document.scripts[j].src === r) { return; }}
              k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)})
              (window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym");
              ym(${metrikaId}, "init", {clickmap:true, trackLinks:true, accurateTrackBounce:true, ecommerce:"dataLayer"});`}
            </Script>
            <noscript>
              <div>
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={`https://mc.yandex.ru/watch/${metrikaId}`} style={{ position: "absolute", left: "-9999px" }} alt="" />
              </div>
            </noscript>
          </>
        ) : null}
        <BookingModalProvider>
          <CartProvider menuItems={menu.items} ordersEnabled={ordersEnabled}>
            <Header phoneHref={contact.phoneHref} />
            <main>{children}</main>
            <Footer />
            <MobileActionBar />
          </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>
  );
}
