import { notFound } from "next/navigation";
import Link from "next/link";
import type { Metadata } from "next";
import { getCategory } from "@/lib/categories";
import { getProducts } from "@/lib/db";
import { CategoryBrowser } from "@/components/CategoryBrowser";
import { siteConfig } from "@/lib/siteConfig";

// Product data can change at runtime, see app/page.tsx for why this
// page always renders fresh instead of using a cached build snapshot.
export const dynamic = "force-dynamic";

export async function generateMetadata({
  params,
}: {
  params: { slug: string };
}): Promise<Metadata> {
  const category = getCategory(params.slug);
  if (!category) return {};
  const title = `${category.name} | ${siteConfig.name}`;
  return {
    title,
    description: `${category.description} Shop ${category.name.toLowerCase()} at ${siteConfig.name} with delivery across ${siteConfig.deliveryArea}.`,
    alternates: { canonical: `/category/${category.slug}` },
  };
}

export default function CategoryPage({ params }: { params: { slug: string } }) {
  const category = getCategory(params.slug);
  if (!category) notFound();

  const products = getProducts().filter((p) => p.category === category.slug);

  const breadcrumbJsonLd = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: [
      { "@type": "ListItem", position: 1, name: "Home", item: siteConfig.url },
      {
        "@type": "ListItem",
        position: 2,
        name: category.name,
        item: `${siteConfig.url}/category/${category.slug}`,
      },
    ],
  };

  return (
    <div className="mx-auto max-w-7xl px-4 py-8 sm:px-6 lg:px-8">
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbJsonLd) }}
      />
      <nav aria-label="Breadcrumb" className="mb-4 text-sm text-black/50">
        <Link href="/" className="hover:text-brand-ink">Home</Link>
        <span className="mx-1.5">/</span>
        <span className="text-brand-ink">{category.name}</span>
      </nav>

      <h1 className="font-display text-2xl font-bold text-brand-ink sm:text-3xl">
        {category.name}
      </h1>
      <p className="mt-1.5 max-w-xl text-sm text-black/55">{category.description}</p>

      <div className="mt-7">
        <CategoryBrowser products={products} />
      </div>
    </div>
  );
}
