---
import { getCollection, type CollectionEntry } from "astro:content";
import BlogPostEntry from "@/components/BlogPostEntry.astro";
import Layout from "@/layouts/Layout.astro";
import PageTitle from "@/components/PageTitle.astro";
import EmptyState from "@/components/EmptyState.astro";

export async function getStaticPaths() {
  const posts = await getCollection("blog");
  const tags = new Set<string>();

  posts.forEach((post) => {
    if (post.data.tags && !post.data.draft) {
      post.data.tags.forEach((tag: string) => tags.add(tag));
    }
  });

  return Array.from(tags).map((name) => {
    const filteredPosts = posts.filter(
      (post) => post.data.tags && post.data.tags.includes(name),
    );
    return {
      params: { name },
      props: { filteredPosts },
    };
  });
}

interface Props {
  filteredPosts: CollectionEntry<"blog">[];
}

const { name } = Astro.params;
const { filteredPosts } = Astro.props;
---

<Layout
  title={`Posts tagged with "${name}" | fiatcode`}
  description={`Browse blog posts tagged with "${name}" by fiatcode`}
>
  <PageTitle title={`Posts tagged with "${name}"`} />
  {
    filteredPosts.length > 0 ? (
      <ul class="space-y-4">
        {filteredPosts.map((post) => (
          <li>
            <BlogPostEntry
              id={post.id}
              title={post.data.title}
              date={post.data.date}
              description={post.data.description}
            />
          </li>
        ))}
      </ul>
    ) : (
      <EmptyState message={`No posts found with the tag "${name}".`} />
    )
  }
</Layout>
