---
import PhotosSubNav from "@/components/PhotosSubNav.astro";
import BaseLayout from "@/layouts/BaseLayout.astro";
import type { PhotoSidecar } from "@/lib/collections";

function tagToSlug(tag: string): string {
  return tag
    .toLowerCase()
    .replace(/\s+/g, "-")
    .replace(/[^a-z0-9-]/g, "");
}

const sidecars = import.meta.glob<PhotoSidecar>(
  "/src/content/photos/collections/**/*.json",
  { eager: true },
);

const tagMap = new Map<string, { label: string; count: number }>();
for (const sidecar of Object.values(sidecars)) {
  for (const tag of sidecar.tags) {
    const slug = tagToSlug(tag);
    const entry = tagMap.get(slug);
    if (entry) {
      entry.count++;
    } else {
      tagMap.set(slug, { label: tag, count: 1 });
    }
  }
}

const tags = [...tagMap.entries()]
  .map(([slug, { label, count }]) => ({ slug, label, count }))
  .sort((a, b) => a.label.localeCompare(b.label));
---

<BaseLayout
  title="Tags"
  description="Browse photos by tag — travel and street photography by Adrian Altner."
  navDesktopHidden={true}
  footerDark={true}
>
  <div class="page">
    <main class="main">
      <PhotosSubNav />

      <header class="page-header">
        <h1 class="page-title">Tags</h1>
        <p class="page-meta">{tags.length} tags</p>
      </header>

      <ul class="tag-list" role="list">
        {
          tags.map(({ slug, label, count }) => (
            <li>
              <a href={`/photos/tags/${slug}`} class="tag-pill">
                {label}
                <span class="tag-count">{count}</span>
              </a>
            </li>
          ))
        }
      </ul>
    </main>
  </div>
</BaseLayout>

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

  .main {
    max-width: var(--width-wide);
    margin: 0 auto;
    padding: 1.5rem;
    width: 100%;
  }

  .page-header {
    margin-bottom: 1.5rem;
  }

  .page-title {
    font-size: 1.5rem;
    font-weight: 500;
    margin-bottom: 0.25rem;
  }

  .page-meta {
    font-size: 0.85rem;
    color: #888;
    margin: 0;
  }

  .tag-list {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    list-style: none;
    padding: 0;
    margin: 0;
  }

  .tag-pill {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    font-size: 0.85rem;
    color: #aaa;
    border: 1px solid #333;
    border-radius: 3px;
    padding: 0.3rem 0.65rem;
    text-decoration: none;
    transition:
      color 0.2s,
      border-color 0.2s;
  }

  .tag-pill:hover {
    color: #f5f5f3;
    border-color: #555;
  }

  .tag-count {
    font-size: 0.75rem;
    color: #555;
  }

  .page :global(.footer a) {
    color: #f5f5f3;
  }

  @media (max-width: 640px) {
    .main {
      padding: 0.75rem;
    }
  }
</style>
