---
import { join, dirname } from "path";
import BaseLayout from "../../layouts/BaseLayout.astro";
import PostList from "../../components/PostList.astro";
import { getCollection } from "astro:content";

export async function getStaticPaths() {
  const posts = await getCollection("posts");
  return posts.flatMap((post) =>
    post.data.tags.map((tag) => ({
      params: { tag },
    })),
  );
}

const { tag } = Astro.params;
const posts = await getCollection("posts");
const taggedPosts = posts.filter((post) => post.data.tags.includes(tag));

const currentUrl = Astro.url;
const root = dirname(dirname(currentUrl.pathname));
---

<BaseLayout>
  <p>Posts tagged with {tag}</p>

  <PostList basePath={join(root, "posts")} filteredPosts={taggedPosts} />
</BaseLayout>
