import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { GameCard, GameGrid } from "@/components/game/GameCard";
import { Pagination, withQuery } from "@/components/game/Pagination";
import { JsonLd } from "@/components/seo/JsonLd";
import { CategoryChipRow } from "@/components/ui/CategoryChip";
import { EmptyState, SectionHeading } from "@/components/ui/Section";
import { listGames } from "@/lib/games";
import { breadcrumbJsonLd } from "@/lib/seo";
import { categoryBySlug } from "@/lib/site";

interface CategoryPageProps {
  params: Promise<{ slug: string }>;
  searchParams: Promise<{ page?: string }>;
}

export async function generateMetadata({
  params,
}: CategoryPageProps): Promise<Metadata> {
  const { slug } = await params;
  const category = categoryBySlug(slug);
  if (!category) return { title: "Category not found" };
  return {
    title: `${category.name} Games`,
    description: `Browse curated ${category.name.toLowerCase()} browser games. ${category.blurb}`,
    alternates: { canonical: `/category/${category.slug}` },
  };
}

/** Per-category listing: live published games, newest first, paginated. */
export default async function CategoryPage({
  params,
  searchParams,
}: CategoryPageProps) {
  const { slug } = await params;
  const category = categoryBySlug(slug);
  if (!category) notFound();

  const { page: pageParam } = await searchParams;
  const page = Math.max(1, Number.parseInt(pageParam ?? "1", 10) || 1);

  const result = await listGames({
    categorySlug: category.slug,
    sort: "newest",
    page,
  });

  return (
    <div className="shell py-10">
      <JsonLd
        data={breadcrumbJsonLd([
          { name: "Home", path: "/" },
          { name: "Categories", path: "/categories" },
          { name: category.name, path: `/category/${category.slug}` },
        ])}
      />
      <nav aria-label="Breadcrumb" className="mb-4 text-sm text-slate-400">
        <Link href="/categories" className="hover:text-white">
          Categories
        </Link>
        <span aria-hidden="true" className="mx-2">
          /
        </span>
        <span aria-current="page" className="text-slate-200">
          {category.name}
        </span>
      </nav>
      <SectionHeading
        eyebrow="Category"
        title={`${category.name} Games`}
        description={`${category.blurb} ${result.total} ${result.total === 1 ? "game" : "games"} available.`}
      />
      <div className="mb-8">
        <CategoryChipRow activeSlug={category.slug} />
      </div>
      {result.games.length > 0 ? (
        <GameGrid>
          {result.games.map((game) => (
            <GameCard key={game.slug} game={game} />
          ))}
        </GameGrid>
      ) : (
        <EmptyState
          title={`No ${category.name.toLowerCase()} games yet`}
          message="No published games in this category right now. Try another category or browse everything."
          actionHref="/games"
          actionLabel="Explore all games"
        />
      )}
      <Pagination
        page={result.page}
        totalPages={result.totalPages}
        buildHref={(p) =>
          withQuery(`/category/${category.slug}`, {
            page: p > 1 ? String(p) : undefined,
          })
        }
      />
    </div>
  );
}
