---
import BlogLayout from "../../../layouts/BlogLayout.astro";
import BlogPostCard from "../../../components/BlogPostCard.astro";
import { readContentCache } from "../../../lib/content/cache";
import {
  wordpressCategories,
  wordpressPostsByCategorySlug,
} from "../../../lib/content/selectors";

export async function getStaticPaths() {
  const cache = await readContentCache();
  return wordpressCategories(cache).map((c) => ({
    params: { slug: c.slug },
  }));
}

const cache = await readContentCache();
const categories = wordpressCategories(cache);

const slug = Astro.params.slug || "";
const activeCategory = categories.find((c) => c.slug === slug);
const posts = wordpressPostsByCategorySlug(cache, slug);

if (!activeCategory) {
  // If the category doesn't exist, there will be no static route generated.
  // But keep runtime behavior explicit.
  return new Response(null, { status: 404 });
}
---

<BlogLayout
  title={`${activeCategory.name} | Blog | SanthoshJ`}
  description={`Posts in category: ${activeCategory.name}`}
  canonicalPath={`/blog/category/${activeCategory.slug}`}
  categories={categories}
  activeCategorySlug={activeCategory.slug}
>
  <section class="section">
    <div class="section-header">
      <h2>{activeCategory.name}</h2>
      <span class="muted">{posts.length} post{posts.length === 1 ? "" : "s"}</span>
    </div>

    {posts.length > 0 ? (
      <div class="blog-grid">
        {posts.map((p) => (
          <BlogPostCard
            post={p}
            placement={`blog.category.${activeCategory.slug}`}
            targetId={`blog.category.${activeCategory.slug}.card.post.${p.slug}`}
          />
        ))}
      </div>
    ) : (
      <div class="empty">No posts in this category yet.</div>
    )}
  </section>
</BlogLayout>
