"use client";

import { use, useEffect, useState } from "react";
import { notFound } from "next/navigation";
import { ProductCard } from "@/components/product/ProductCard";
import { PageShell } from "@/components/layout/PageShell";
import { Stagger, StaggerItem } from "@/components/motion/Stagger";
import type { Category, Product } from "@/data/types";

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

export default function CategoryDetailPage({ params }: Props) {
  const { slug } = use(params);
  const [category, setCategory] = useState<Category | null>(null);
  const [list, setList] = useState<Product[]>([]);
  const [missing, setMissing] = useState(false);
  const [ready, setReady] = useState(false);

  useEffect(() => {
    void Promise.all([
      fetch("/api/categories").then((res) => res.json()),
      fetch(`/api/products?category=${slug}`).then((res) => res.json()),
    ])
      .then(([catData, prodData]: [{ categories?: Category[] }, { products?: Product[] }]) => {
        const found = catData.categories?.find((c) => c.slug === slug);
        if (!found) {
          setMissing(true);
          return;
        }
        setCategory(found);
        setList(prodData.products ?? []);
      })
      .catch(() => setMissing(true))
      .finally(() => setReady(true));
  }, [slug]);

  if (missing) notFound();
  if (!ready || !category) {
    return (
      <div className="flex min-h-[40vh] items-center justify-center text-sm text-muted">
        Loading collection…
      </div>
    );
  }

  return (
    <PageShell
      crumbs={[
        { label: "Home", href: "/" },
        { label: "Categories", href: "/categories" },
        { label: category.name },
      ]}
      eyebrow="Collection"
      title={category.name}
      description={category.description}
    >
      {list.length === 0 ? (
        <p className="text-sm text-muted">No products in this collection yet.</p>
      ) : (
        <Stagger className="product-grid">
          {list.map((product, index) => (
            <StaggerItem key={product.id}>
              <ProductCard product={product} index={index} compact />
            </StaggerItem>
          ))}
        </Stagger>
      )}
    </PageShell>
  );
}
