---
import Layout from "@layouts/Layout.astro";
import { getCollection } from "astro:content";
import { useTranslatedPath } from "@i18n/utils";
import SmallCard from "@components/SmallCard.astro";
import SmallGrid from "@components/SmallGrid.astro";

const collections = ["blog", "photos", "projects"] as const;

const tp = useTranslatedPath(Astro.url);

export async function getStaticPaths() {
  const collections = ["blog", "photos", "projects"] as const;
  const posts = await Promise.all(
    collections.map((collection) => getCollection(collection)),
  );

  const tags = new Set();

  posts.flat().forEach((post) => {
    if (!post.data?.tags) return;
    post.data.tags.forEach((tag: string) => {
      tags.add(tag.toLowerCase());
    });
  });

  return [...tags.values()].map((tag) => {
    return {
      params: {
        tag,
      },
    };
  });
}

const { tag } = Astro.params;

const allPosts = (
  await Promise.all(
    collections.map((collection) => {
      return getCollection(collection);
    }),
  )
).flat();

const posts = allPosts.filter((post) => {
  return post.data?.tags?.find((t) => t.toLowerCase() === tag);
});
---

<Layout title="Max Richter">
  <article>
    <h1>Tag: {tag}</h1>
    <SmallGrid>
      {
        posts.map((post) => {
          return (
            <SmallCard post={post} />
          );
        })
      }
    </SmallGrid>
  </article>
</Layout>
