---
import { getCollection } from "astro:content";
import type { GetStaticPathsOptions } from "astro";
import Layout from "@/layouts/Layout.astro";
import Header from "@/components/Header.astro";
import Main from "@/components/Main.astro";
import Breadcrumb from "@/components/Breadcrumb.astro";
import Card from "@/components/Card.astro";
import Footer from "@/components/Footer.astro";
import Pagination from "@/components/Pagination.astro";
import { getUniqueTags } from "@/utils/getUniqueTags";
import { getSortedPosts } from "@/utils/getSortedPosts";
import { slugifyAll } from "@/utils/slugify";
import { useTranslations } from "@/i18n";
import config from "@/config";

export async function getStaticPaths({ paginate }: GetStaticPathsOptions) {
  const posts = await getCollection("posts", ({ data }) => !data.draft);
  const tags = getUniqueTags(posts);

  return tags.flatMap(({ tag, tagName }) => {
    const tagPosts = getSortedPosts(
      posts.filter(({ data }) => slugifyAll(data.tags).includes(tag))
    );

    return paginate(tagPosts, {
      params: { tag },
      props: { tagName },
      pageSize: config.posts.perPage,
    });
  });
}

const { page, tagName } = Astro.props;

const locale = Astro.currentLocale ?? config.site.lang;
const t = useTranslations(locale);
---

<Layout title={`${t.pages.tagTitle}: ${tagName} | ${config.site.title}`}>
  <Header />

  <Breadcrumb />

  <Main
    pageTitle={`${t.pages.tagTitle}: ${tagName}`}
    pageDesc={`${t.pages.tagDesc} "${tagName}".`}
  >
    <ul>
      {page.data.map(data => <Card {...data} />)}
    </ul>
  </Main>

  <Pagination {page} />

  <Footer noMarginTop={page.lastPage > 1} />
</Layout>
