import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import DOMPurify from "isomorphic-dompurify";

import { Container } from "@/components/Container";
import { PageHeader } from "@/components/PageHeader";
import {
  getProductDetails,
  PRODUCT_DETAILS_SLUGS,
  PRODUCT_DETAILS_TITLES,
  type ProductDetailsSlug,
} from "@/lib/product-details";

type Params = { slug: string };

export function generateStaticParams(): Params[] {
  return PRODUCT_DETAILS_SLUGS.map((slug) => ({ slug }));
}

export async function generateMetadata({
  params,
}: {
  params: Promise<Params>;
}): Promise<Metadata> {
  const { slug } = await params;
  if (!PRODUCT_DETAILS_SLUGS.includes(slug as ProductDetailsSlug)) {
    return { title: "Not found" };
  }
  const title = PRODUCT_DETAILS_TITLES[slug as ProductDetailsSlug];
  return { title };
}

export default async function ProductDetailsPage({
  params,
}: {
  params: Promise<Params>;
}) {
  const { slug } = await params;
  if (!PRODUCT_DETAILS_SLUGS.includes(slug as ProductDetailsSlug)) {
    notFound();
  }
  const typedSlug = slug as ProductDetailsSlug;
  const details = getProductDetails(typedSlug);
  if (!details) notFound();

  const clean = DOMPurify.sanitize(details.html, {
    USE_PROFILES: { html: true },
    FORBID_TAGS: ["script", "style", "iframe", "form"],
    FORBID_ATTR: ["onerror", "onclick", "onload", "onmouseover"],
  });

  const title = PRODUCT_DETAILS_TITLES[typedSlug];

  return (
    <>
      <PageHeader eyebrow="Full details" title={title} />
      <Container className="pb-14 md:pb-16">
        <div className="mx-auto max-w-4xl">
          <div className="mb-8">
            <Link
              href={`/products/${typedSlug}`}
              className="text-[13px] font-semibold text-[var(--color-blue)] underline underline-offset-2"
            >
              ← Back to {typedSlug === "academy" ? "Academy" : typedSlug} landing page
            </Link>
          </div>
          <article
            className="legacy-html text-[17px] leading-[1.75] text-[var(--color-ink)]"
            dangerouslySetInnerHTML={{ __html: clean }}
          />
        </div>
      </Container>
    </>
  );
}
