---
import { Layout } from "virtual:astro-hashnode/components";
import Posts from '../../../components/Posts.astro';
import {getAllPosts} from '../../../hn-gql';
import Taged from '../../../components/Tag.astro';

export const prerender = true

export async function getStaticPaths() {
  const data = await getAllPosts();
  const allPosts = data.publication.posts.edges;

  // biome-ignore lint/complexity/useFlatMap: <explanation>
  const allTags = [...new Set(allPosts.map((post) => post.node.tags).flat())];
  const jsonObject = allTags.map((object) => JSON.stringify(object));
  const uniqueSet = new Set(jsonObject);
  const uniqueTags = Array.from(uniqueSet).map((u) => JSON.parse(u));
 
  return uniqueTags.map((uTag) => {
    const filteredPosts: { node: { author: { name: string; profilePicture: string; }; publishedAt: string; title: string; subtitle: string; brief: string; slug: string; readTimeInMinutes: number; content: { html: string; }; tags: { name: string; slug: string; }[]; coverImage: { url: string; }; }; }[] = [];
    // biome-ignore lint/complexity/noForEach: <explanation>
    allPosts.forEach((post) => {
      const tags = post.node.tags;
      // biome-ignore lint/complexity/noForEach: <explanation>
      tags.forEach((tag) => {
          if(tag.slug === uTag.slug) {
            filteredPosts.push(post)
          }
      })
    })
    
    return {
      params: { tag: uTag.slug },
      props: { posts: filteredPosts, matchedTag: uTag },
    };
  });
}

const { tag } = Astro.params;
const { posts, matchedTag } = Astro.props;
const baseURL = import.meta.env.BASE_URL;
---

<Layout pageTitle={tag}>
  <div class="flex pt-3">
    <p class="text-lg pt-1 px-1 mr-1">{posts.length} post(s) matched the tag</p> 
    <Taged tag={matchedTag} />
    <span class="mx-3 mt-1 block font-bold text-slate-500 text-xl"> | </span>
    <a class="mt-1.5" href={`${baseURL}blog`}>See all posts</a>
  </div>
  <Posts allPosts={posts} />
</Layout>