import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { NextIntlClientProvider } from "next-intl";
import { getMessages } from "next-intl/server";
import { jetbrainsMono, plusJakartaSans } from "@/lib/fonts";
import { locales, localeDir, type Locale } from "@/lib/i18n/config";
import { Header } from "@/components/layout/Header";
import { Footer } from "@/components/layout/Footer";
import { cn } from "@/lib/utils";

interface LocaleLayoutProps {
  children: React.ReactNode;
  params: Promise<{ locale: string }>;
}

export function generateStaticParams() {
  return locales.map((locale) => ({ locale }));
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: string }>;
}): Promise<Metadata> {
  const { locale } = await params;
  const isRtl = locale === "fa";

  return {
    alternates: {
      canonical: `https://biztaghavi.com/${locale}`,
      languages: {
        fa: "https://biztaghavi.com/fa",
        en: "https://biztaghavi.com/en",
      },
    },
    other: {
      "content-language": isRtl ? "fa-IR" : "en-US",
    },
  };
}

export default async function LocaleLayout({
  children,
  params,
}: LocaleLayoutProps) {
  const { locale } = await params;

  if (!locales.includes(locale as Locale)) {
    notFound();
  }

  const messages = await getMessages();
  const dir = localeDir[locale as Locale];

  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "Person",
    name: "Ali Taghavi",
    alternateName: "علی تقوی",
    url: "https://biztaghavi.com",
    jobTitle: "CEO",
    worksFor: { "@type": "Organization", name: "NODE-Group" },
    sameAs: [
      "https://github.com/alitaghavi",
      "https://linkedin.com/in/alitaghavi",
      "https://twitter.com/alitaghavi",
    ],
  };

  return (
    <html
      lang={locale}
      dir={dir}
      className={cn(
        jetbrainsMono.variable,
        plusJakartaSans.variable,
        "h-full antialiased"
      )}
    >
      <head>
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
        />
        <link rel="alternate" type="application/rss+xml" title="علی تقوی — نوشته‌ها" href="/api/rss" />
      </head>
      <body className="relative flex min-h-full flex-col bg-background text-text-primary">
        <a
          href="#main-content"
          className="sr-only focus:not-sr-only focus:fixed focus:left-4 focus:top-4 focus:z-100 focus:rounded-md focus:bg-accent focus:px-4 focus:py-2 focus:text-sm focus:font-medium focus:text-background focus:outline-none"
        >
          {dir === "rtl" ? "رفتن به محتوای اصلی" : "Skip to main content"}
        </a>
        <NextIntlClientProvider messages={messages}>
          <Header />
          <main id="main-content" className="flex-1 relative z-10">{children}</main>
          <Footer />
        </NextIntlClientProvider>
      </body>
    </html>
  );
}
