import type { Metadata } from "next";
import { Suspense } from "react";

import { BrowseFilters } from "@/components/browse/browse-filters";
import { BrowseShell } from "@/components/browse/browse-shell";
import { GridSkeleton, PosterGrid } from "@/components/browse/poster-grid";
import { Pagination } from "@/components/browse/pagination";
import {
  ANIME_GENRE_IDS,
  TV_SORT_OPTIONS,
  loadCatalogue,
  loadGenreOptions,
  queryWithoutPage,
} from "@/lib/catalogue";

export const metadata: Metadata = {
  title: "Anime",
  description:
    "Hand-picked anime films and series — Japanese animation filtered by genre, year and rating.",
  alternates: { canonical: "/anime" },
};

/**
 * /anime
 *
 * "Anime" is not a TMDB genre, so the shelf is defined as Animation (16)
 * restricted to Japanese-origin titles. The genre filter is hidden because it is
 * already locked to 16 by the route; sort, year and rating still work.
 */
export default async function AnimePage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const params = await searchParams;

  return (
    <BrowseShell
      title="Anime"
      description="Japanese animation — films and series, from theatrical features to long-running shows."
      hero
    >
      <Suspense fallback={<GridSkeleton />}>
        <AnimeCatalogue params={params} />
      </Suspense>
    </BrowseShell>
  );
}

async function AnimeCatalogue({
  params,
}: {
  params: Record<string, string | string[] | undefined>;
}) {
  const [{ result }, genres] = await Promise.all([
    loadCatalogue("tv", params, {
      lockedGenre: ANIME_GENRE_IDS.tv,
      originalLanguage: "ja",
    }),
    loadGenreOptions("tv"),
  ]);

  return (
    <>
      <BrowseFilters
        genres={genres}
        sortOptions={TV_SORT_OPTIONS}
        showGenre={false}
        resultCount={result.totalResults}
      />
      <PosterGrid
        items={result.items}
        priorityCount={8}
        emptyMessage="No anime match these filters."
      />
      <Pagination
        page={result.page}
        totalPages={result.totalPages}
        basePath="/anime"
        query={queryWithoutPage(params)}
      />
    </>
  );
}
