---
import { getCollection } from "astro:content";
import BaseLayout from "@/layouts/BaseLayout.astro";

const [notes, articles, links] = await Promise.all([
  getCollection("notes", ({ data }) => !data.draft),
  getCollection("blog", ({ data }) => !data.draft),
  getCollection("links_json"),
]);

function capitalize(s: string) {
  return s.charAt(0).toUpperCase() + s.slice(1);
}

const tagCounts = new Map<string, number>();
for (const item of [...notes, ...articles, ...links]) {
  for (const tag of item.data.tags) {
    tagCounts.set(tag, (tagCounts.get(tag) ?? 0) + 1);
  }
}

const tags = [...tagCounts.entries()]
  .sort((a, b) => a[0].localeCompare(b[0]))
  .map(([slug, count]) => ({ slug, title: capitalize(slug), count }));
---

<BaseLayout title="Tags" description="All tags on adrian-altner.com.">
  <div class="page">
    <main class="main">
      <a href="/" class="back">← Home</a>
      <h1 class="heading">Tags</h1>
      {tags.length === 0 ? (
        <p class="empty">No tags yet.</p>
      ) : (
        <ul class="list">
          {tags.map(({ slug, title, count }) => (
            <li class="item">
              <a href={`/tags/${slug}`} class="item__link">
                <span class="item__title">{title}</span>
                <span class="item__count">{count}</span>
              </a>
            </li>
          ))}
        </ul>
      )}
    </main>
  </div>
</BaseLayout>

<style>
  .page {
    display: grid;
    grid-template-rows: auto 1fr auto;
    min-height: 100dvh;
    background: #f5f5f3;
    color: #111;
  }

  .main {
    max-width: var(--width-prose);
    margin: 0 auto;
    padding: 2rem 2rem 4rem;
    width: 100%;
  }

  .back {
    display: inline-block;
    margin-bottom: 1.5rem;
    font-size: 0.9rem;
    color: #555;
    text-decoration: none;
  }

  .back:hover {
    color: var(--accent);
  }

  .heading {
    font-size: 1.75rem;
    font-weight: 400;
    letter-spacing: -0.02em;
    margin-bottom: 2.5rem;
  }

  .empty {
    color: #888;
    font-size: 0.95rem;
  }

  .list {
    list-style: none;
    padding: 0;
    display: flex;
    flex-direction: column;
  }

  .item {
    border-bottom: 1px solid #e0e0de;
  }

  .item:first-child {
    border-top: 1px solid #e0e0de;
  }

  .item__link {
    display: flex;
    justify-content: space-between;
    align-items: baseline;
    padding: 0.75rem 0;
    text-decoration: none;
    color: inherit;
  }

  .item__link:hover .item__title {
    color: var(--accent);
  }

  .item__title {
    font-size: 1rem;
    font-weight: 500;
    transition: color 0.15s;
  }

  .item__count {
    font-size: 0.8rem;
    color: #888;
  }
</style>
