---
import BaseLayout from '../../layouts/BaseLayout.astro';
import EntryList from '../../components/EntryList.astro';
import { getAllEntries } from '../../lib/entries';
import {
  buildOgImage,
  buildBreadcrumbs,
  buildItemList,
  absoluteUrl,
} from '../../lib/seo';

export async function getStaticPaths() {
  const entries = await getAllEntries();
  const tags = [...new Set(entries.flatMap((e) => e.tags))];
  return tags.map((tag) => ({
    params: { tag },
    props: {
      tag,
      entries: entries.filter((e) => e.tags.includes(tag)),
    },
  }));
}

const { tag, entries } = Astro.props;
const lastUpdated = entries[0]?.date;
const count = entries.length;
const topNames = entries.slice(0, 3).map((e) => e.primary).join(', ');
const description =
  topNames.length > 0
    ? `All ${count} entries tagged #${tag}: ${topNames}${count > 3 ? '…' : '.'}`
    : `All entries tagged #${tag}.`;

const ogImage = buildOgImage(undefined, 'site', `#${tag} on Unique`);

const itemList = buildItemList(
  entries.map((e) => ({ url: e.href, name: e.primary })),
  `#${tag} on Unique`
);

const collectionPage: Record<string, unknown> = {
  '@context': 'https://schema.org',
  '@type': 'CollectionPage',
  '@id': absoluteUrl(`/tags/${tag}/#collection`),
  name: `#${tag} — Unique`,
  description,
  url: absoluteUrl(`/tags/${tag}/`),
  inLanguage: 'en-US',
};

const breadcrumbs = buildBreadcrumbs([
  { name: 'Home', url: '/' },
  { name: `#${tag}`, url: `/tags/${tag}/` },
]);
---

<BaseLayout
  title={`#${tag} (${count})`}
  description={description}
  subheader={`Tagged: ${tag}.`}
  lastUpdated={lastUpdated}
  ogImage={ogImage}
  jsonLd={[collectionPage, itemList, breadcrumbs]}
>
  <EntryList entries={entries} />
  <p class="back"><a href="/">← back</a></p>

  <style>
    .back { margin-top: 2rem; font-size: 0.9rem; }
  </style>
</BaseLayout>
