---
import { getCollection } from "astro:content";
import BlogPostItem from "@/components/BlogPostItem.astro";
import BaseLayout from "@/layouts/BaseLayout.astro";
import { getLinks } from "@/lib/collections";

export async function getStaticPaths() {
  const [notes, articles, links, allCategories] = await Promise.all([
    getCollection("notes", ({ data }) => !data.draft),
    getCollection("blog", ({ data }) => !data.draft),
    getLinks(),
    getCollection("categories"),
  ]);

  const categoryTitleMap = new Map(
    allCategories.map((c) => [c.id, c.data.title]),
  );

  const allTags = new Set([
    ...notes.flatMap((n) => n.data.tags),
    ...articles.flatMap((p) => p.data.tags),
    ...links.flatMap((l) => l.data.tags),
  ]);

  return [...allTags].map((tag) => ({
    params: { slug: tag },
    props: {
      tag,
      notes: notes
        .filter((n) => n.data.tags.includes(tag))
        .sort(
          (a, b) => b.data.publishDate.valueOf() - a.data.publishDate.valueOf(),
        ),
      articles: articles
        .filter((p) => p.data.tags.includes(tag))
        .sort(
          (a, b) => b.data.publishDate.valueOf() - a.data.publishDate.valueOf(),
        ),
      links: links
        .filter((l) => l.data.tags.includes(tag))
        .sort(
          (a, b) => b.data.publishDate.valueOf() - a.data.publishDate.valueOf(),
        ),
      categoryTitleMap,
    },
  }));
}

const { tag, notes, articles, links, categoryTitleMap } = Astro.props;

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

function formatDate(date: Date) {
  return date.toLocaleDateString("de-DE", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  });
}

function getDomain(url: string) {
  try {
    return new URL(url).hostname.replace(/^www\./, "");
  } catch {
    return url;
  }
}

const total = notes.length + articles.length + links.length;
---

<BaseLayout
  title={capitalize(tag)}
  description={`All content tagged with "${capitalize(tag)}".`}
>
  <div class="page">
    <main class="main">
      <a href="/tags" class="back">← Tags</a>
      <h1 class="heading"><span class="tag-name">{capitalize(tag)}</span></h1>
      <p class="count">{total} item{total !== 1 ? "s" : ""}</p>

      {notes.length > 0 && (
        <section class="section">
          <h2 class="section__heading">Notes</h2>
          <ul class="list">
            {notes.map((note) => (
              <li class="item">
                <time class="item__date" datetime={note.data.publishDate.toISOString()}>
                  {formatDate(note.data.publishDate)}
                </time>
                <a href={`/notes/${note.id}`} class="item__title">
                  {note.data.title}
                </a>
                {note.data.tags.length > 0 && (
                  <div class="item__tags">
                    {note.data.tags.map((t) => (
                      <a
                        href={`/tags/${t}`}
                        class={`tag${t === tag ? " tag--active" : ""}`}
                      >
                        {capitalize(t)}
                      </a>
                    ))}
                  </div>
                )}
              </li>
            ))}
          </ul>
        </section>
      )}

      {articles.length > 0 && (
        <section class="section">
          <h2 class="section__heading">Blog</h2>
          <ul class="list list--articles">
            {articles.map((post) => (
              <BlogPostItem
                post={post}
                categoryTitleMap={categoryTitleMap}
                activeTagId={tag}
              />
            ))}
          </ul>
        </section>
      )}

      {links.length > 0 && (
        <section class="section">
          <h2 class="section__heading">Links</h2>
          <ul class="list">
            {links.map((link) => (
              <li class="item item--link">
                <div class="item__top">
                  <a href={`/links/${link.id}`} class="item__title">
                    {link.data.title}
                  </a>
                  <time class="item__date" datetime={link.data.publishDate.toISOString()}>
                    {formatDate(link.data.publishDate)}
                  </time>
                </div>
                <a
                  href={link.data.url}
                  class="item__url"
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <svg
                    width="11"
                    height="11"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2.5"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    aria-hidden="true"
                  >
                    <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
                    <polyline points="15 3 21 3 21 9" />
                    <line x1="10" y1="14" x2="21" y2="3" />
                  </svg>
                  {getDomain(link.data.url)}
                </a>
                {link.data.description && (
                  <p class="item__desc">{link.data.description}</p>
                )}
                {link.data.via && (
                  <p class="item__via">via {link.data.via}</p>
                )}
                {link.data.tags.length > 0 && (
                  <div class="item__tags">
                    {link.data.tags.map((t) => (
                      <a
                        href={`/tags/${t}`}
                        class={`tag${t === tag ? " tag--active" : ""}`}
                      >
                        {capitalize(t)}
                      </a>
                    ))}
                  </div>
                )}
              </li>
            ))}
          </ul>
        </section>
      )}
    </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: 0.25rem;
  }

  .tag-name {
    color: var(--accent);
  }

  .count {
    font-size: 0.875rem;
    color: #888;
    margin-bottom: 2.5rem;
  }

  .section {
    margin-bottom: 3rem;
  }

  .section__heading {
    font-size: 0.75rem;
    font-weight: 600;
    letter-spacing: 0.08em;
    text-transform: uppercase;
    color: #888;
    border-top: 2px solid #111;
    padding-top: 0.6rem;
    margin-bottom: 0.5rem;
  }

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

  .list--articles {
    gap: 1.5rem;
  }

  /* Notes + Links items */
  .item {
    display: grid;
    grid-template-columns: 7rem 1fr;
    gap: 0.25rem 1.25rem;
    padding: 1rem 0;
    border-bottom: 1px solid #e0e0de;
    align-items: baseline;
  }

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

  /* Links items override to block layout */
  .item--link {
    display: block;
    padding: 1rem 0;
  }

  .item__date {
    font-size: 0.8rem;
    color: #888;
    white-space: nowrap;
    padding-top: 0.15rem;
  }

  .item__title {
    font-size: 1rem;
    font-weight: 500;
    color: #111;
    text-decoration: none;
  }

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

  /* Link-specific layout */
  .item__top {
    display: flex;
    align-items: baseline;
    justify-content: space-between;
    gap: 1rem;
    flex-wrap: wrap;
  }

  .item__url {
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
    font-size: 0.8rem;
    color: #888;
    text-decoration: none;
    margin-top: 0.2rem;
  }

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

  .item__desc {
    font-size: 0.875rem;
    color: #555;
    margin: 0.4rem 0 0;
    line-height: 1.5;
  }

  .item__via {
    font-size: 0.8rem;
    color: #888;
    margin: 0.25rem 0 0;
  }

  .item__tags {
    display: flex;
    flex-wrap: wrap;
    gap: 0.35rem;
    margin-top: 0.6rem;
    grid-column: 1 / -1;
  }

  .tag {
    font-size: 0.75rem;
    color: #666;
    background: #e8e8e6;
    padding: 0.15em 0.55em;
    border-radius: 3px;
    text-decoration: none;
  }

  .tag:hover {
    background: var(--accent);
    color: #fff;
  }

  .tag--active {
    background: var(--accent);
    color: #fff;
  }


  @media (max-width: 480px) {
    .item {
      grid-template-columns: 1fr;
      gap: 0.2rem;
    }
  }
</style>
