---
export const prerender = false;
import Base from "../../layouts/Base.astro";
import Topbar from "../../components/Topbar.astro";
import Sidebar from "../../components/Sidebar.astro";
import { getCollection } from 'astro:content';
const allPosts = await getCollection('posts', ({ data }) => data.published === true);
allPosts.sort((a, b) => b.data.date.valueOf() - a.data.date.valueOf());
const selectedTag = Astro.url.searchParams.get('tag');
const posts = selectedTag
  ? allPosts.filter(p => p.data.tags.includes(selectedTag))
  : allPosts;
const allTags = [...new Set(allPosts.flatMap(p => p.data.tags))].sort();
const grouped = posts.reduce((acc, post) => {
  const date = post.data.date.toDateString();
  if (!acc[date]) acc[date] = [];
  acc[date].push(post);
  return acc;
}, {} as Record<string, typeof posts>);
const groupedEntries = Object.entries(grouped);
---
<Base title="blog">
  <Topbar slot="topbar" />
  <Sidebar slot="sidebar" tags={allTags} />
  {selectedTag && (
    <div class="mb-6">
      <h2 class="text-ctp-accent text-xl font-bold mb-1"># {selectedTag.charAt(0).toUpperCase() + selectedTag.slice(1)}</h2>
    </div>
  )}
  {groupedEntries.map(([date, datePosts]) => (
    <div class="mb-6">
      <div class="text-ctp-subtext text-xs uppercase tracking-widest mb-2 border-b border-ctp-surface pb-1">{date}</div>
      {datePosts.map((post) => (
        <div class="p-4 mb-3 rounded-lg bg-ctp-surface">
          <a href={`/blog/${post.id}`} class="text-ctp-accent">{post.data.title}</a>
          <div class="flex flex-wrap gap-1 mt-2">
            {post.data.tags.map((tag) => (
              <a href={`/blog?tag=${tag}`} class="text-xs px-2 py-0.5 rounded-full bg-ctp-mantle text-ctp-subtext hover:text-ctp-accent transition-colors">
                {tag}
              </a>
            ))}
          </div>
        </div>
      ))}
    </div>
  ))}
</Base>
