import Link from "next/link";
import { notFound } from "next/navigation";
import { getCategories, getProducts } from "@/lib/api";
import ProductCatalog from "@/components/ProductCatalog";

export const revalidate = 300;

export default async function CategoryPage({ params }: { params: Promise<{ category: string }> }) {
  const { category } = await params;
  const cats = await getCategories();

  const cat = cats.find((c) => c.slug === category && Number(c.parent_id) === 0);
  if (!cat) notFound();

  const subs = cats.filter((c) => Number(c.parent_id) === cat.id);
  const products = await getProducts({ category, limit: 300 });
  const blurb = subs.slice(0, 4).map((s) => s.name).join(" · ") || `Wholesale ${cat.name.toLowerCase()} for pharmacies and retailers across the UAE.`;

  return (
    <>
      <section className="pb-cathead pb-tone-cream">
        <div className="pb-shell">
          <nav className="pb-crumbs" aria-label="Breadcrumb">
            <Link href="/portal">Home</Link><span>/</span>
            <span className="pb-crumbs-current">{cat.name}</span>
          </nav>
          <h1 className="pb-cathead-title">{cat.name}</h1>
          <p className="pb-cathead-sub">{blurb}</p>
        </div>
      </section>

      <ProductCatalog
        products={products}
        subFacets={subs.map((s) => ({ name: s.name, slug: s.slug }))}
      />
      <div className="pb-section-spacer" />
    </>
  );
}
