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 {
  formatLegacyDate,
  getLegacyPostBySlug,
  getLegacyPosts,
} from "@/lib/legacy/content";

type Params = { slug: string };

export async function generateStaticParams(): Promise<Params[]> {
  return getLegacyPosts().map((p) => ({ slug: p.slug }));
}

export async function generateMetadata({
  params,
}: {
  params: Promise<Params>;
}): Promise<Metadata> {
  const { slug } = await params;
  const post = getLegacyPostBySlug(slug);
  if (!post) return { title: "Legacy post not found" };
  return {
    title: `${post.title} — legacy`,
    description: post.excerpt || undefined,
    robots: { index: false, follow: false },
  };
}

export default async function LegacyPostPage({
  params,
}: {
  params: Promise<Params>;
}) {
  const { slug } = await params;
  const post = getLegacyPostBySlug(slug);
  if (!post) notFound();

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

  return (
    <>
      <PageHeader
        eyebrow={`Legacy · ${post.type}`}
        title={post.title || post.slug}
        lede={post.excerpt || undefined}
      />
      <Container className="pb-24">
        <div className="mb-6 text-[13px] text-[var(--color-slate)]">
          <Link
            href="/legacy"
            className="font-semibold text-[var(--color-blue)] underline underline-offset-2"
          >
            ← All legacy content
          </Link>
          {post.date && <span className="ml-3">{formatLegacyDate(post.date)}</span>}
        </div>

        <article
          className="legacy-html max-w-3xl text-[17px] leading-[1.7] text-[var(--color-ink)]"
          // Sanitized immediately above via DOMPurify.
          dangerouslySetInnerHTML={{ __html: clean }}
        />
      </Container>
    </>
  );
}
