import type { Metadata } from "next";
import { Inter } from "next/font/google";
import { get } from "lodash";

import Header from "@/components/Header/Header";
import Footer from "@/components/Footer/Footer";
import GoogleAnalytics from "@/components/Analytics/GoogleAnalytics";
import Hotjar from "@/components/Analytics/Hotjar";
import GTMNoscript from "@/components/Analytics/GTMNoscript";
import FacebookPixel from "@/components/Analytics/FacebookPixel";

import { apiEndpoints } from "@/lib/api";
import { getCanonicalUrl } from "@/lib/canonical";

// Import all global styles
import "@/styles/globals.css";
import "@/styles/header.css";
import "@/styles/cakeBake.css";
import "@/styles/cakeBakeSlider.css";
import "@/styles/cakeDesign.css";
import "@/styles/footer.css";
import "@/styles/newProducts.css";
import "@/styles/outlet.css";
import "@/styles/topBanner.css";
import "@/styles/curveTop.css";
import "@/styles/aboutTopContent.css";
import "@/styles/aboutMidContent.css";
import "@/styles/midQuote.css";
import "@/styles/ourValues.css";
import "@/styles/menuTopContent.css";
import "@/styles/menuItems.css";
import "@/styles/categoryList.css";
import "@/styles/imageGallery.css";

const inter = Inter({ subsets: ["latin"] });

export async function generateMetadata(): Promise<Metadata> {
  try {
    const { data: global } = await apiEndpoints.global();
    const logoUrl = get(global, ["Website", "logo", "url"]);

    // Defensive access in case Website is not present on global
    const website =
      global && typeof global === "object" && "Website" in global
        ? (
            global as {
              Website?: {
                title?: string;
                description?: string;
                address?: string;
              };
            }
          ).Website
        : undefined;

    const title =
      website?.title || "La Tarte Patisserie - Crafting Sweet Memories";
    const description =
      website?.description ||
      "La Tarte is here to bring the exotic French pastry experience to the bakery scene in Bangladesh. With quality ingredients, we delicately design trendy pastries, breads and other savory items to give you the taste of celebration.";
    const address = website?.address;

    return {
      title: {
        template: "%s | La Tarte Patisserie",
        default: title || "La Tarte Patisserie - Crafting Sweet Memories",
      },
      icons: {
        icon: "/favicon.ico",
      },
      description,
      alternates: {
        canonical: getCanonicalUrl("/"),
      },
      openGraph: {
        title,
        description,
        images: logoUrl ? [{ url: logoUrl }] : undefined,
        type: "website",
        locale: "en_BD",
        siteName: "La Tarte Patisserie",
        url: getCanonicalUrl("/"),
      },
      other: address
        ? {
            "business:contact_data:street_address": address,
            "business:contact_data:locality": "Dhaka",
            "business:contact_data:country_name": "Bangladesh",
          }
        : undefined,
    };
  } catch (error) {
    console.error("Failed to fetch metadata from API:", error);

    // Fallback metadata
    return {
      title: "La Tarte Patisserie - Crafting Sweet Memories",
      description:
        "La Tarte is here to bring the exotic French pastry experience to the bakery scene in Bangladesh. With quality ingredients, we delicately design trendy pastries, breads and other savory items to give you the taste of celebration.",
      alternates: {
        canonical: getCanonicalUrl("/"),
      },
      openGraph: {
        title: "La Tarte Patisserie - Crafting Sweet Memories",
        description:
          "La Tarte is here to bring the exotic French pastry experience to the bakery scene in Bangladesh. With quality ingredients, we delicately design trendy pastries, breads and other savory items to give you the taste of celebration.",
        url: getCanonicalUrl("/"),
      },
    };
  }
}

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const { data: global } = await apiEndpoints.global();
  const tgmid = get(global, ["config", "googleTagManager"], "G-GZJ4D9YNRJ");
  const hjid = get(global, ["config", "hotjar"], "3830992");
  const facebookPixel = get(global, ["config", "facebookPixel"], "");

  return (
    <html lang="en">
      <head>
        {/* PWA Meta Tags */}
        <meta name="application-name" content="La Tarte Patisserie" />
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="apple-mobile-web-app-status-bar-style" content="default" />
        <meta name="apple-mobile-web-app-title" content="La Tarte" />
        <meta name="mobile-web-app-capable" content="yes" />
        <meta name="msapplication-config" content="/browserconfig.xml" />
        <meta name="msapplication-TileColor" content="#BC955C" />
        <meta name="theme-color" content="#BC955C" />

        {/* Manifest */}
        <link rel="manifest" href="/manifest.json" />

        {/* Apple Touch Icons */}
        <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
        <link
          rel="apple-touch-icon"
          sizes="180x180"
          href="/apple-touch-icon.png"
        />

        {/* Favicons */}
        <link
          rel="icon"
          type="image/png"
          sizes="32x32"
          href="/favicon-32x32.png"
        />
        <link
          rel="icon"
          type="image/png"
          sizes="16x16"
          href="/favicon-16x16.png"
        />
        <link rel="shortcut icon" href="/favicon.ico" />

        <GoogleAnalytics tgmid={tgmid} />
        <Hotjar hjid={hjid} />
        <FacebookPixel facebookPixel={facebookPixel} />
      </head>
      <body className={inter.className}>
        <GTMNoscript tgmid={tgmid} />
        <Header global={global} />
        {children}
        <Footer global={global} />
      </body>
    </html>
  );
}
