"use client";
import { useState } from "react";
import Link from "next/link";
import { formatCount } from "@/lib/formatCount";

type Post = {
  slug: string;
  title: string;
  excerpt: string | null;
  featuredImageUrl: string | null;
  viewCount: number;
  publishedAt: string | Date | null;
  categories: { name: string; slug: string }[];
};

function PostCard({ p }: { p: Post }) {
  return (
    <Link href={`/blog/${p.slug}`} className="card overflow-hidden flex flex-col sm:flex-row hover:border-red-800/60 transition-colors group">
      <div className="sm:w-48 aspect-video sm:aspect-square bg-neutral-800 shrink-0 overflow-hidden flex items-center justify-center">
        {p.featuredImageUrl ? (
          <img src={p.featuredImageUrl} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300" />
        ) : (
          <span className="text-4xl opacity-30">📝</span>
        )}
      </div>
      <div className="p-4 flex-1 min-w-0">
        <div className="flex items-start justify-between gap-2 mb-2">
          <h3 className="font-bold text-lg group-hover:text-red-400 transition-colors">{p.title}</h3>
          <span className="text-xs text-neutral-500 shrink-0 whitespace-nowrap">👁 {formatCount(p.viewCount)}</span>
        </div>
        {p.categories.length > 0 && (
          <div className="flex flex-wrap gap-1.5 mb-2">
            {p.categories.map((c) => (
              <span key={c.slug} className="text-xs bg-neutral-800 text-neutral-300 px-2.5 py-1 rounded-full">
                {c.name}
              </span>
            ))}
          </div>
        )}
        {p.excerpt && <p className="text-sm text-neutral-500 line-clamp-3">{p.excerpt}</p>}
      </div>
    </Link>
  );
}

export default function BlogPostGrid({
  initialPosts,
  initialHasMore,
  category,
}: {
  initialPosts: Post[];
  initialHasMore: boolean;
  category?: string;
}) {
  const [posts, setPosts] = useState(initialPosts);
  const [hasMore, setHasMore] = useState(initialHasMore);
  const [loading, setLoading] = useState(false);

  async function loadMore() {
    setLoading(true);
    const params = new URLSearchParams({ offset: String(posts.length) });
    if (category) params.set("category", category);
    const res = await fetch(`/api/blog/list?${params.toString()}`);
    const data = await res.json();
    setLoading(false);
    setPosts((prev) => [...prev, ...data.posts]);
    setHasMore(data.hasMore);
  }

  if (posts.length === 0) {
    return <div className="card p-10 text-center text-neutral-500 text-sm">No posts yet — check back soon.</div>;
  }

  return (
    <div>
      <div className="space-y-4">
        {posts.map((p) => (
          <PostCard key={p.slug} p={p} />
        ))}
      </div>
      {hasMore && (
        <div className="text-center mt-6">
          <button onClick={loadMore} disabled={loading} className="btn-secondary px-6 py-3">
            {loading ? "Loading..." : "See More"}
          </button>
        </div>
      )}
    </div>
  );
}
