---
import { getCollection } from "astro:content";
import ContentLayout from "@/layouts/content.astro";
import { BlogHeader } from "@/components/blog/header";
import { BlogPostList } from "@/components/blog/post-list";
import { getAllViews } from "@/lib/views";

const posts = (await getCollection("blog", ({ data }) => {
  return import.meta.env.DEV || data.isDraft !== true;
})).map(post => ({
  ...post,
  data: {
    ...post.data,
    date: post.data.date.toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric"
    })
  }
}));

// Get view counts and sort by popularity
const views = await getAllViews(posts.map(p => p.id));
const sorted = [...posts].sort((a, b) => (views[b.id] || 0) - (views[a.id] || 0));
---
<ContentLayout
  title="Most Popular | Blog | Timothy Pidashev"
  description="Most popular blog posts by view count."
>
  <BlogHeader client:load />
  <BlogPostList posts={sorted} client:load />
</ContentLayout>
