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

const articles = (await getCollection("blog", ({ data }) => !data.draft)).sort(
  (a, b) => b.data.publishDate.valueOf() - a.data.publishDate.valueOf(),
);

const allCategories = await getCollection("categories");
const categoryCounts = new Map<string, number>();
for (const post of articles) {
  if (post.data.category) {
    categoryCounts.set(
      post.data.category.id,
      (categoryCounts.get(post.data.category.id) ?? 0) + 1,
    );
  }
}
const categories = allCategories
  .map((cat) => ({ ...cat, count: categoryCounts.get(cat.id) ?? 0 }))
  .sort(
    (a, b) =>
      a.data.order - b.data.order || a.data.title.localeCompare(b.data.title),
  );
const categoryTitleMap = new Map(
  allCategories.map((c) => [c.id, c.data.title]),
);

const seriesCountMap = new Map<string, number>();
for (const post of articles) {
  if (post.data.seriesParent) {
    seriesCountMap.set(
      post.data.seriesParent,
      (seriesCountMap.get(post.data.seriesParent) ?? 1) + 1,
    );
  }
}

// Aggregate tags with counts
function capitalize(s: string) {
  return s.charAt(0).toUpperCase() + s.slice(1);
}

const tagCounts = new Map<string, number>();
for (const post of articles) {
  for (const tag of post.data.tags) {
    tagCounts.set(tag, (tagCounts.get(tag) ?? 0) + 1);
  }
}
const tags = [...tagCounts.entries()]
  .sort((a, b) => b[1] - a[1])
  .map(([id, count]) => ({ id, title: capitalize(id), count }));
---

<BaseLayout title="Blog" description="Blog by Adrian Altner.">
  <div class="page">
    <div class="main">
      <a href="/" class="back">← Home</a>
      <div class="content">
        <main>
          <h1 class="heading">Blog</h1>
          <ul class="list">
            {
              articles.map((post) => (
                <BlogPostItem
                  post={post}
                  categoryTitleMap={categoryTitleMap}
                  seriesCountMap={seriesCountMap}
                />
              ))
            }
          </ul>
        </main>

        <aside class="sidebar">
          {
            categories.length > 0 && (
              <section class="sidebar__section">
                <h2 class="sidebar__heading">Categories</h2>
                <ul class="sidebar__list">
                  {categories.map((cat) => (
                    <li>
                      <a
                        href={`/blog/category/${cat.id}`}
                        class="sidebar__link"
                      >
                        {cat.data.title}
                        <span class="sidebar__tag-count">{cat.count}</span>
                      </a>
                    </li>
                  ))}
                </ul>
              </section>
            )
          }

          {
            tags.length > 0 && (
              <section class="sidebar__section">
                <h2 class="sidebar__heading">Tags</h2>
                <div class="sidebar__tags">
                  {tags.map(({ id, title, count }) => (
                    <a href={`/tags/${id}`} class="sidebar__tag">
                      {title}
                      <span class="sidebar__tag-count">{count}</span>
                    </a>
                  ))}
                </div>
                <a href="/tags" class="sidebar__link-all">
                  View All
                </a>
              </section>
            )
          }
        </aside>
      </div>
    </div>
  </div>
</BaseLayout>

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

  .main {
    max-width: var(--width-content);
    margin: 0 auto;
    padding: 2rem 2rem 4rem;
    width: 100%;
  }

  .content {
    display: grid;
    grid-template-columns: 1fr var(--width-sidebar);
    gap: 4rem;
    align-items: start;
  }

  .back {
    display: inline-block;
    font-size: 0.9rem;
    color: #555;
    text-decoration: none;
    border-bottom: 1px solid #ccc;
    padding-bottom: 1px;
    margin-bottom: 1.5rem;
  }

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

  /* ── Post list ── */
  .heading {
    font-weight: 400;
    letter-spacing: -0.02em;
    margin-bottom: 2.5rem;
  }

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

  /* ── Sidebar ── */
  .sidebar {
    position: sticky;
    top: 2rem;
    display: flex;
    flex-direction: column;
    gap: 2rem;
  }

  .sidebar__section {
    border-top: 2px solid #111;
    padding-top: 0.75rem;
  }

  .sidebar__heading {
    font-size: 0.75rem;
    font-weight: 600;
    letter-spacing: 0.08em;
    text-transform: uppercase;
    color: #888;
    margin-bottom: 0.75rem;
  }

  .sidebar__list {
    list-style: none;
    padding: 0;
    display: flex;
    flex-direction: column;
    gap: 0.4rem;
  }

  .sidebar__link {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 0.9rem;
    color: #333;
    text-decoration: none;
  }

  .sidebar__link-all {
    display: block;
    font-size: 0.9rem;
    color: #333;
    text-decoration: none;
    margin-top: 1rem;
  }

  .sidebar__tags {
    display: flex;
    flex-wrap: wrap;
    gap: 0.4rem;
  }

  .sidebar__tag {
    display: inline-flex;
    align-items: center;
    gap: 0.3rem;
    font-size: 0.8rem;
    color: #444;
    text-decoration: none;
    background: #e8e8e6;
    border-radius: 3px;
    padding: 0.2rem 0.5rem;
    transition:
      background 0.15s,
      color 0.15s;
  }

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

  .sidebar__tag-count {
    font-size: 0.7rem;
    color: #888;
  }

  .sidebar__tag:hover .sidebar__tag-count {
    color: rgba(255, 255, 255, 0.75);
  }

  /* ── Mobile ── */
  @media (max-width: 768px) {
    .content {
      grid-template-columns: 1fr;
    }

    .sidebar {
      position: static;
      flex-direction: row;
      flex-wrap: wrap;
      gap: 1.5rem;
      border-top: 1px solid #e0e0de;
      padding-top: 2rem;
    }

    .sidebar__section {
      flex: 1;
      min-width: 140px;
    }

    .item__link {
      flex-direction: column;
      gap: 0.2rem;
    }
  }
</style>
