---
import ArticlesView from "../../../../../components/ArticlesView.astro";
import { getPublishedArticles, getCategoryNames, getCategories, slugToCategory, pageSlice, lastPageOf } from "../../../../../lib/articles";

export async function getStaticPaths() {
  const articles = await getPublishedArticles();
  const categories = getCategories(articles, await getCategoryNames());
  const paths: Array<{ params: { slug: string; page: string }; props: { categoryName: string } }> = [];
  for (const category of categories) {
    for (let page = 2; page <= lastPageOf(category.count); page += 1) {
      paths.push({ params: { slug: category.slug, page: String(page) }, props: { categoryName: category.name } });
    }
  }
  return paths;
}

const all = await getPublishedArticles();
const categories = getCategories(all, await getCategoryNames());
const categoryName = String(Astro.props.categoryName || slugToCategory(Astro.params.slug!, categories.map((item) => item.name)) || "");
const filtered = all.filter((item) => item.data.category === categoryName);
const page = Number(Astro.params.page);
---
<ArticlesView items={pageSlice(filtered, page)} categories={categories} totalCount={all.length} activeSlug={Astro.params.slug!} activeName={categoryName} currentPage={page} lastPage={lastPageOf(filtered.length)} basePath={`/articles/topic/${Astro.params.slug}`} />
