import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import { format } from "date-fns";
import { ArrowLeft, ExternalLink, Clock, User, Tag } from "lucide-react";
import { getPostBySlug, getRelatedPosts, getTrendingPosts, getFeaturedImage, postUrl } from "@/lib/wordpress";
import CategoryBadge from "@/components/CategoryBadge";
import PostCard from "@/components/PostCard";
import Sidebar from "@/components/Sidebar";
import CommentSection from "@/components/CommentSection";
import AdSlot from "@/components/AdSlot";
import type { Metadata } from "next";

export const revalidate = 300;

type Params = { continent: string; country: string; category: string; slug: string };

export async function generateMetadata({ params }: { params: Params }): Promise<Metadata> {
  const post = await getPostBySlug(params.slug).catch(() => null);
  if (!post) return {};
  return {
    title:       post.title,
    description: (post.excerpt ?? "").slice(0, 160),
    openGraph: { images: post.featured_image ? [{ url: post.featured_image }] : [] },
  };
}

export default async function PostPage({ params }: { params: Params }) {
  const post = await getPostBySlug(params.slug).catch(() => null);
  if (!post) notFound();

  const [related, trending] = await Promise.all([
    getRelatedPosts(params.slug).catch(() => []),
    getTrendingPosts().catch(() => []),
  ]);

  const image      = getFeaturedImage(post);
  const continent  = post.continent;
  const country    = post.country;
  const sourceUrl  = post.source_url;
  const sourceName = post.source_name;

  return (
    <div className="max-w-screen-xl mx-auto px-4 py-8">
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">

        {/* ── Article + Comments ─────────────────────────── */}
        <div className="lg:col-span-2">
          <article>

            {/* Breadcrumb */}
            <div className="flex items-center gap-2 text-sm text-gray-500 mb-6 flex-wrap">
              <Link href="/" className="hover:text-white transition-colors flex items-center gap-1">
                <ArrowLeft className="w-3.5 h-3.5" /> Home
              </Link>
              {continent && (
                <>
                  <span>/</span>
                  <Link href={`/${continent.slug}`} className="hover:text-white transition-colors">
                    {continent.name}
                  </Link>
                </>
              )}
              {country && (
                <>
                  <span>/</span>
                  <Link href={`/${continent?.slug}/${country.slug}`} className="hover:text-white transition-colors">
                    {country.flag_emoji} {country.name}
                  </Link>
                </>
              )}
              {post.category && (
                <>
                  <span>/</span>
                  <Link href={`/category/${post.category.slug}`} className="hover:text-white transition-colors">
                    {post.category.name}
                  </Link>
                </>
              )}
            </div>

            {/* Category + title */}
            <Link href={`/category/${post.category?.slug}`}>
              <CategoryBadge category={post.category?.name ?? "News"} size="md" />
            </Link>
            <h1 className="text-white text-3xl lg:text-4xl font-display font-bold mt-3 leading-tight">
              {post.title}
            </h1>

            {/* Meta row */}
            <div className="flex flex-wrap items-center gap-4 mt-4 pb-4 border-b border-white/10">
              {post.published_at && (
                <span className="text-gray-400 text-sm">
                  {format(new Date(post.published_at), "MMMM d, yyyy · h:mm a")}
                </span>
              )}
              {post.reading_time && (
                <span className="flex items-center gap-1 text-gray-500 text-sm">
                  <Clock className="w-3.5 h-3.5" /> {post.reading_time} min read
                </span>
              )}
              {post.author && (
                <span className="flex items-center gap-1 text-gray-400 text-sm">
                  <User className="w-3.5 h-3.5" /> {post.author.name}
                </span>
              )}
              {sourceName && sourceUrl && (
                <a href={sourceUrl} target="_blank" rel="noopener noreferrer"
                  className="flex items-center gap-1 text-sm text-brand-500 hover:underline">
                  Source: {sourceName} <ExternalLink className="w-3 h-3" />
                </a>
              )}
            </div>

            {/* Featured image */}
            <div className="relative w-full h-64 lg:h-[420px] rounded-2xl overflow-hidden my-6 bg-white/5">
              <Image src={image} alt={post.title} fill className="object-cover" priority />
            </div>

            {/* Content */}
            <div
              className="wp-content text-gray-300 leading-relaxed text-[15px]"
              dangerouslySetInnerHTML={{ __html: post.content }}
            />

            {/* Category + Tags footer */}
            <div className="mt-8 pt-6 border-t border-white/10 space-y-3">
              {post.category && (
                <div className="flex items-center gap-2 flex-wrap">
                  <span className="text-xs text-gray-500 uppercase tracking-wider">Category:</span>
                  <Link href={`/category/${post.category.slug}`}
                    className="text-xs font-semibold px-3 py-1 rounded-full border border-white/15 hover:border-white/30 text-white bg-white/5 hover:bg-white/10 transition-colors">
                    {post.category.name}
                  </Link>
                </div>
              )}
              {post.tags && post.tags.length > 0 && (
                <div className="flex items-center gap-2 flex-wrap">
                  <span className="flex items-center gap-1 text-xs text-gray-500 uppercase tracking-wider">
                    <Tag className="w-3 h-3" /> Tags:
                  </span>
                  {post.tags.map(tag => (
                    <Link key={tag.id} href={`/?tag=${tag.slug}`}
                      className="text-xs bg-white/5 border border-white/10 text-gray-400 px-3 py-1 rounded-full hover:border-brand-500/50 hover:text-brand-500 transition-colors">
                      #{tag.name}
                    </Link>
                  ))}
                </div>
              )}
            </div>

          </article>

          <AdSlot slot="in_content" className="my-8" />
          <CommentSection slug={params.slug} postId={post.id} />
        </div>

        {/* ── Sidebar ─────────────────────────────────────── */}
        <Sidebar trendingPosts={trending.length ? trending : related} />
      </div>

      {/* ── Related articles ──────────────────────────────── */}
      {related.length > 0 && (
        <section className="mt-12 pt-8 border-t border-white/10">
          <h2 className="text-xl font-bold text-white mb-6">More Articles</h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            {related.slice(0, 4).map(p => <PostCard key={p.id} post={p} />)}
          </div>
        </section>
      )}
    </div>
  );
}
