import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { cormorant, manrope } from "@/lib/fonts";
import { isLocale, locales } from "@alterra/shared";
import Experience from "@/components/Experience";
import Header from "@/components/Header";
import Footer from "@/components/Footer";
import WhatsAppButton from "@/components/WhatsAppButton";
import { CurrencyProvider } from "@/components/Currency";
import ConsentProvider from "@/components/consent/ConsentProvider";
import { getConsentCopy } from "@/lib/consentCopy";
import { localizedPath } from "@alterra/shared";
import { getLayoutCopy, getMenus } from "@/lib/site";
import { noIndex, siteName, siteUrl } from "@/lib/seo";
import { contactInfo } from "@/lib/i18n";
import { locations } from "@/lib/site";
import { locationSlugs } from "@alterra/shared";
import "../globals.css";

export function generateStaticParams() {
  return locales.map((lang) => ({ lang }));
}

export async function generateMetadata({ params }: { params: Promise<{ lang: string }> }): Promise<Metadata> {
  const { lang } = await params;
  if (!isLocale(lang)) return {};
  const copy = getLayoutCopy(lang);
  return {
    metadataBase: new URL(siteUrl),
    title: { default: `${siteName} | ${copy.tagline}`, template: `%s | ${siteName}` },
    description: copy.promise,
    applicationName: siteName,
    icons: { icon: "/icon.svg", apple: "/icon.svg" },
    robots: noIndex ? { index: false, follow: false } : undefined,
    verification: {
      google: process.env.NEXT_PUBLIC_GOOGLE_SITE_VERIFICATION || undefined,
      other: process.env.NEXT_PUBLIC_BING_SITE_VERIFICATION ? { "msvalidate.01": process.env.NEXT_PUBLIC_BING_SITE_VERIFICATION } : undefined,
    },
  };
}

export default async function RootLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ lang: string }>;
}) {
  const { lang } = await params;
  if (!isLocale(lang)) notFound();
  const copy = getLayoutCopy(lang);
  const menus = getMenus(lang);

  // Organization data for search engines; only real contact data is included (placeholders are skipped).
  const real = (value: string) => (value && !value.startsWith("[") ? value : undefined);
  const sameAs = (process.env.NEXT_PUBLIC_SOCIAL_URLS ?? "").split(",").map((u) => u.trim()).filter(Boolean);
  const organization = {
    "@context": "https://schema.org",
    "@type": "RealEstateAgent",
    "@id": `${siteUrl}/#organization`,
    name: siteName,
    url: siteUrl,
    logo: `${siteUrl}/brand/logo-stacked-light.svg`,
    image: `${siteUrl}${localizedPath(lang, "/og-image")}`,
    description: copy.promise,
    slogan: copy.tagline,
    areaServed: locationSlugs.map((slug) => ({ "@type": "Place", name: `${locations[slug].name.en}, Antioquia, Colombia` })),
    knowsLanguage: ["en", "es"],
    email: real(contactInfo.email),
    telephone: real(contactInfo.phoneDisplay),
    address: real(contactInfo.address) ? { "@type": "PostalAddress", streetAddress: contactInfo.address, addressRegion: "Antioquia", addressCountry: "CO" } : undefined,
    sameAs: sameAs.length ? sameAs : undefined,
  };

  return (
    <html lang={lang} className={`${cormorant.variable} ${manrope.variable}`}>
      <body>
        <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(organization).replace(/</g, "\\u003c") }} />
        <ConsentProvider copy={getConsentCopy(lang)} privacyHref={localizedPath(lang, "/privacy-policy")}>
          <CurrencyProvider initial={lang === "es" ? "COP" : "USD"}>
            <Experience>
              <Header lang={lang} copy={copy} menus={menus} />
              {children}
              <Footer lang={lang} copy={copy} menus={menus} />
              <WhatsAppButton label={copy.cta.whatsapp} />
            </Experience>
          </CurrencyProvider>
        </ConsentProvider>
      </body>
    </html>
  );
}
