---
import TagList from '../../components/TagList.astro';
import Page from '../../layouts/Page.astro';
import {
  absoluteUrl,
  buildBreadcrumbJsonLd,
  buildBreadcrumbTrail,
  getAllTags,
  getPublishedPosts,
  site,
} from '../../lib/site';

const posts = await getPublishedPosts();
const tags = getAllTags(posts);

const tagCounts: Record<string, number> = {};
for (const post of posts) {
  for (const tag of post.data.tags) {
    tagCounts[tag] = (tagCounts[tag] ?? 0) + 1;
  }
}

const collectionJsonLd = {
  '@context': 'https://schema.org',
  '@type': 'CollectionPage',
  name: `${site.name} — Tags`,
  url: absoluteUrl('/tags/'),
  description: 'Every tag used across the articles archive.',
};

const breadcrumbJsonLd = buildBreadcrumbJsonLd(buildBreadcrumbTrail({ tagsIndex: true }));

const jsonLd = [collectionJsonLd, breadcrumbJsonLd];
---

<Page
  title="Tags"
  description="Every tag used across the articles archive."
  jsonLd={jsonLd}
>
  <p class="dek">
    {posts.length} articles across {tags.length} tags.
  </p>
  <TagList tags={tags} counts={tagCounts} />
</Page>
