---
import BaseLayout from "@/layouts/BaseLayout.astro";
import { getCollection } from "astro:content";
import type { CollectionEntry } from "astro:content";
import Headline from "@/components/ui/Headline.astro";
import PostItem from "@/components/blog/PostItem.astro";
import Pagination from "@/components/ui/Pagination.astro";
import { getTaxonomyMap } from "@/utils/taxonomy";
import { buildPaginatedPaths } from "@/utils/paginate";

interface Props {
  page: {
    data: CollectionEntry<"blog">[];
    total: number;
    currentPage: number;
    lastPage: number;
    url: { prev?: string; next?: string };
  };
}

export async function getStaticPaths() {
  const allPosts = await getCollection("blog");
  const posts = allPosts.filter((post) => post.data && post.data.pubDate);

  const tags = new Set<string>();
  posts.forEach((post) => {
    post.data.tags?.forEach((tag) => tags.add(tag));
  });

  return Array.from(tags).flatMap((tag) => {
    const tagPosts = posts
      .filter((post) => post.data.tags?.includes(tag))
      .sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf());

    return buildPaginatedPaths(tagPosts, `/tag/${tag}`).map(
      ({ pageParam, page }) => ({
        params: { tag, page: pageParam },
        props: { page },
      }),
    );
  });
}

const { page } = Astro.props as Props;
const { tag } = Astro.params;

const tagInfo = getTaxonomyMap("tag").get(tag!);
const displayName = tagInfo?.name ?? tag!;
const description = tagInfo?.description;

const metadata = {
  title: displayName,
  description: description ?? `Các bài viết được gắn thẻ ${displayName}.`,
};
---

<BaseLayout metadata={metadata}>
  <section class="relative px-4 py-8 sm:px-6 lg:px-8 md:py-12">
    <div class="relative mx-auto max-w-5xl">
      <Headline
        tagline="Tag"
        title={`#${displayName}`}
        subtitle={description ?? `Hiển thị ${page.total} bài viết.`}
        classes={{
          container: "mb-12 text-center",
          title:
            "font-heading mb-4 text-4xl font-bold tracking-tight text-foreground md:text-6xl capitalized",
          subtitle: "mx-auto max-w-3xl text-xl text-muted-foreground",
        }}
      />

      <div class="mb-8 text-center">
        <a href="/blog" class="text-primary hover:underline">← Quay lại blog</a>
      </div>

      <div class="grid gap-8 md:grid-cols-2 lg:grid-cols-3">
        {page.data.map((post) => <PostItem post={post} />)}
      </div>
      <Pagination page={page} />
    </div>
  </section>
</BaseLayout>
