import type { Metadata } from "next";
import Link from "next/link";
import { notFound, permanentRedirect } from "next/navigation";
import { SitePage } from "@/app/(site)/_components/SitePage";
import { SiteHeader } from "@/app/(site)/_components/SiteHeader";
import { SiteFooter } from "@/app/(site)/_components/SiteFooter";
import { BTN_OUTLINE, BTN_PRIMARY } from "@/app/(site)/_components/pages/blocks";
import { ProductCardItem } from "@/app/(site)/_components/products/ProductCardItem";
import { ProductDetail } from "@/app/(site)/_components/products/ProductDetail";
import { getProduct, getProducts } from "@/app/(site)/_lib/cms";
import { productHref } from "@/app/(site)/_lib/products";

type Props = { params: Promise<{ slug: string }> };

const isSlug = (s: string) => /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(s);

/**
 * Products on the website when the site is built; newer ones render on their first visit.
 * Cache Components needs at least one entry: with no product yet, a placeholder that is
 * never a real slug (it renders the not-found page).
 */
export async function generateStaticParams() {
  const slugs: string[] = [];
  for (let page = 1; page <= 20; page++) {
    const list = await getProducts(`limit=48&page=${page}&sort=name`);
    if (!list) break;
    slugs.push(...list.items.map((p) => p.slug));
    if (page >= list.pagination.pages) break;
  }
  return (slugs.length ? slugs : ["_"]).map((slug) => ({ slug }));
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const p = isSlug(slug) ? await getProduct(slug) : null;
  if (!p) return {};
  const title = p.seo?.title || `${p.name} — Unionists Group`;
  const description = p.seo?.description || p.shortDescription || undefined;
  return {
    title,
    description,
    alternates: { canonical: productHref(p.slug) },
    openGraph: { title, description, images: p.thumbnail?.url ? [p.thumbnail.url] : undefined },
  };
}

export default async function Page({ params }: Props) {
  const { slug } = await params;
  const p = isSlug(slug) ? await getProduct(slug) : null;
  if (!p) notFound();
  // An old slug: the API answered for the product's current one (proxy.ts normally redirects first).
  if (p.slug !== slug) permanentRedirect(productHref(p.slug));
  const related = p.related ?? [];

  return (
    <SitePage className="product-details-page">
      <a className="skip-link" href="#main">
        Skip to main content
      </a>{" "}
      <SiteHeader active="/product-services" />
      <main id="main" lang={p.language && p.language !== "en" ? p.language : undefined}>
        <ProductDetail p={p} />
        {related.length > 0 && (
          <section className="bg-white pb-12 md:pb-16" aria-labelledby="related-products-heading">
            <div className="w-full max-w-[1180px] mx-auto px-6" data-reveal="">
              <h2 id="related-products-heading" className="text-[clamp(20px,2.5vw,26px)] font-black text-ink leading-tight mb-6">
                Related Products
              </h2>
              <div className="product-catalog-grid">
                {related.map((r) => (
                  <ProductCardItem key={r.id} p={r} />
                ))}
              </div>
            </div>
          </section>
        )}
        {/* CTA */}
        <section className="contact-cta py-14 md:py-16 text-center">
          <div className="w-full max-w-[960px] mx-auto px-6" data-reveal="">
            <h2 className="text-[clamp(20px,2.5vw,26px)] font-black text-ink leading-tight mb-[14px]">Drive Sales &amp; Business Partnerships</h2>
            <p className="text-[15px] text-[#3c4554] mb-8 leading-[1.65]">
              Figma ipsum component variant main layer. Horizontal horizontal thumbnail rectangle move connection distribute.
            </p>
            <div className="flex flex-col items-stretch gap-[14px] sm:flex-row sm:flex-wrap sm:items-center sm:justify-center">
              <Link href="/contact" className={BTN_PRIMARY}>
                {" "}
                Start A Business Inquiry{" "}
              </Link>{" "}
              <Link href="/contact" className={BTN_OUTLINE}>
                {" "}
                Request A Custom Quote{" "}
              </Link>{" "}
              <Link href="/partner-with-us" className={BTN_OUTLINE}>
                {" "}
                Partner With Unionists Group{" "}
              </Link>
            </div>
          </div>
        </section>
      </main>
      <SiteFooter />
    </SitePage>
  );
}
