---
import { getCollection } from "astro:content";
import { SITE } from "@consts";
import Layout from "@layouts/Layout.astro";
import ShowcasePost from "@components/ShowcasePost.astro";
import { createSlug } from "@lib/utils";

export async function getStaticPaths() {
  const allBlogPosts = (await getCollection("posts")).filter(
    (post) => !post.data.draft,
  );
  const allProjects = (await getCollection("projects")).filter(
    (post) => !post.data.draft,
  );

  const blogTags = allBlogPosts.flatMap((post) => post.data.tags);
  const projectTags = allProjects.flatMap((project) => project.data.tags);

  const allTags = new Set([...blogTags, ...projectTags]);

  return Array.from(allTags).map((tag) => {
    const slug = createSlug(tag);
    return {
      params: { tag: slug },
      props: { originalTag: tag },
    };
  });
}

const { originalTag } = Astro.props;

const allBlogPosts = await getCollection("posts");
const allProjects = await getCollection("projects");

const blogPostsWithTag = allBlogPosts.filter((post) =>
  post.data.tags.includes(originalTag),
);
const projectsWithTag = allProjects.filter((project) =>
  project.data.tags.includes(originalTag),
);

const allArticlesWithTag = [...blogPostsWithTag, ...projectsWithTag]
  .filter((post) => !post.data.draft)
  .sort((a, b) => b.data.date.valueOf() - a.data.date.valueOf());
---

<Layout title={SITE.TITLE} description={`Articles tagged with ${originalTag}.`}>
  <h1 class="animate-reveal text-3xl font-semibold break-words opacity-0">
    <span class="capitalize">{originalTag}</span> is tagged on {
      allArticlesWithTag.length
    }
    {
      allArticlesWithTag.length > 1 ? (
        <span>articles</span>
      ) : (
        <span>article</span>
      )
    }
  </h1>
  <ul
    class="animate-reveal grid grid-cols-1 gap-6 opacity-0 [animation-delay:0.1s]"
  >
    {allArticlesWithTag.map((article) => <ShowcasePost collection={article} />)}
  </ul>
  <div class="animate-reveal flex justify-end opacity-0 [animation-delay:0.2s]">
    <a
      href="/tags"
      class="text-tertiary hover:text-secondary text-xs transition-colors duration-300"
      >See all tags</a
    >
  </div>
</Layout>
