import { notFound } from "next/navigation";
import Link from "next/link";
import { getContinentBySlug, CATEGORIES } from "@/lib/continents";
import { getContinentPosts, getTrendingPosts } from "@/lib/wordpress";
import PostCard from "@/components/PostCard";
import Sidebar from "@/components/Sidebar";
import Pagination from "@/components/Pagination";
import type { Metadata } from "next";

export const revalidate = 60;

export async function generateMetadata({ params }: { params: { continent: string } }): Promise<Metadata> {
  const continent = getContinentBySlug(params.continent);
  if (!continent) return {};
  return {
    title:       `${continent.emoji} ${continent.name} News`,
    description: `Latest news from ${continent.name} — sports, entertainment, technology, politics and breaking news.`,
  };
}

export default async function ContinentPage({
  params,
  searchParams,
}: {
  params:       { continent: string };
  searchParams: { page?: string };
}) {
  const continent = getContinentBySlug(params.continent);
  if (!continent) notFound();

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

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

  const posts    = postsData.data;
  const lastPage = postsData.last_page ?? 1;

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

      {/* Header banner */}
      <div className={`relative rounded-2xl overflow-hidden bg-gradient-to-r ${continent.color} p-8 mb-8`}>
        <div className="text-6xl mb-2">{continent.emoji}</div>
        <h1 className="text-white text-4xl font-display font-bold">{continent.name}</h1>
        <p className="text-white/80 mt-1">{continent.countries.length} countries · {postsData.total ?? 0} articles</p>
        <div className="flex flex-wrap gap-2 mt-4">
          {continent.countries.map(c => (
            <Link key={c.slug} href={`/${continent.slug}/${c.slug}`}
              className="bg-white/20 hover:bg-white/30 text-white text-sm px-3 py-1 rounded-full transition-colors">
              {c.flag} {c.name}
            </Link>
          ))}
        </div>
      </div>

      {/* Category tabs */}
      <div className="flex items-center gap-2 mb-6 overflow-x-auto pb-2">
        <span className="shrink-0 text-sm px-4 py-2 rounded-full bg-brand-500 text-white font-medium">All</span>
        {CATEGORIES.map(cat => (
          <Link key={cat.slug} href={`/${continent.slug}?cat=${cat.slug}`}
            className={`shrink-0 text-sm px-4 py-2 rounded-full bg-white/5 border border-white/10 hover:bg-white/10 transition-colors ${cat.color}`}>
            {cat.name}
          </Link>
        ))}
      </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">
              <div className="text-5xl mb-4">{continent.emoji}</div>
              <p className="text-lg">No posts yet for {continent.name}.</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={`/${params.continent}`} />
        </div>
        <Sidebar trendingPosts={trending.length ? trending : posts.slice(0, 6)} />
      </div>
    </div>
  );
}
