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

const description = 'Every tag used across the articles archive.';

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

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

const collectionJsonLd = {
  '@context': 'https://schema.org',
  '@type': 'CollectionPage',
  name: `${site.name}: Tags`,
  url: absoluteUrl('/tags/'),
  description,
};

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

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

<Page title="Tags" description={description} jsonLd={jsonLd}>
  <p class="dek">
    {posts.length}
    {posts.length === 1 ? 'article' : 'articles'} across {tags.length}
    {tags.length === 1 ? 'tag' : 'tags'}.
  </p>
  <TagList tags={tags} counts={tagCounts} />
</Page>
