import { notFound } from "next/navigation";
import { getCategoryMeta } from "@/lib/continents";
import { getCategoryPosts, getTrendingPosts } from "@/lib/wordpress";
import PostCard from "@/components/PostCard";
import Sidebar from "@/components/Sidebar";
import Pagination from "@/components/Pagination";
import CategoryBadge from "@/components/CategoryBadge";
import type { Metadata } from "next";

export const revalidate = 60;

export async function generateMetadata({ params }: { params: { slug: string } }): Promise<Metadata> {
  const catMeta = getCategoryMeta(params.slug);
  return { title: `${catMeta?.name ?? params.slug} News` };
}

export default async function CategoryPage({
  params,
  searchParams,
}: {
  params:       { slug: string };
  searchParams: { page?: string };
}) {
  const catMeta = getCategoryMeta(params.slug);
  if (!catMeta) notFound();

  const page = Math.max(1, Number(searchParams.page ?? 1));

  const [catData, trending] = await Promise.all([
    getCategoryPosts(params.slug, page).catch(() => ({ data: [], total: 0, current_page: 1, last_page: 1, per_page: 12 })),
    getTrendingPosts().catch(() => []),
  ]);

  const posts    = catData.data ?? [];
  const lastPage = catData.last_page ?? 1;

  return (
    <div className="max-w-screen-xl mx-auto px-4 py-8">

      {/* Header */}
      <div className="flex items-center gap-4 mb-8 pb-6 border-b border-white/10">
        <div className={`w-2 h-16 rounded-full ${catMeta.bg}`} />
        <div>
          <CategoryBadge category={catMeta.name} size="md" />
          <h1 className="text-white text-4xl font-display font-bold mt-2">{catMeta.name}</h1>
          <p className="text-gray-400 text-sm mt-1">
            {catData.total ?? posts.length} articles · Global coverage
          </p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div className="lg:col-span-2">
          {posts.length === 0 ? (
            <div className="text-center py-20 text-gray-500">
              <p className="text-lg">No {catMeta.name} posts yet.</p>
              <p className="text-sm mt-2">Run the crawler to fetch articles.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {posts.map(post => <PostCard key={post.id} post={post} />)}
            </div>
          )}
          <Pagination currentPage={page} lastPage={lastPage} baseUrl={`/category/${params.slug}`} />
        </div>
        <Sidebar trendingPosts={trending.length ? trending : posts.slice(0, 6)} />
      </div>
    </div>
  );
}
