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

function freqSort(items: Array<string>): string[] {
  const counts: { [key: string]: number } = items.reduce(
    (obj: { [key: string]: number }, val: string) => {
      obj[val] = (obj[val] || 0) + 1;
      return obj;
    },
    {},
  );
  const sorted: string[] = Object.keys(counts).sort((a: string, b: string) => {
    return counts[b] - counts[a];
  });
  return sorted;
}

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 = blogTags.concat(projectTags);
const allTagsSorted = freqSort(allTags);
---

<Layout title={SITE.TITLE} description="All tags found on articles.">
  <h1 class="animate-reveal text-3xl font-semibold break-words opacity-0">
    Tags
  </h1>
  <ol
    class="text-tertiary animate-reveal flex flex-wrap items-center gap-2 opacity-0 [animation-delay:0.1s]"
  >
    {
      allTagsSorted.map((tag: string) => (
        <li>
          <a
            href={`/tags/${createSlug(tag)}`}
            class="bg-button text-secondary hover:bg-button-active flex w-fit flex-row items-center gap-1 justify-self-center rounded-sm px-2 py-1 text-center font-sans text-sm font-light text-nowrap capitalize no-underline transition-colors duration-300"
          >
            {tag}
          </a>
        </li>
      ))
    }
  </ol>
</Layout>
