import type { Metadata } from "next";
import { notFound } from "next/navigation";
import Link from "next/link";
import Header from "@/components/Header";
import Footer from "@/components/Footer";
import { getMenu, getHomeContent } from "@/lib/wordpress";
import type { WpPost } from "@/lib/wordpress";
import Image from "@/components/Image";

const WP_URL = process.env.WORDPRESS_URL?.replace(/\/$/, "");

async function getCategoryPosts(slug: string): Promise<{ category: string; posts: WpPost[] } | null> {
  if (!WP_URL) return null;
  try {
    const [catRes, postsRes] = await Promise.all([
      fetch(`${WP_URL}/wp-json/wp/v2/categories?slug=${encodeURIComponent(slug)}&_fields=id,name,slug`, {
        next: { revalidate: 300 },
      }),
      fetch(
        `${WP_URL}/wp-json/wp/v2/posts?categories_slug=${encodeURIComponent(slug)}&per_page=50&_embed=wp:featuredmedia&_fields=id,slug,title,excerpt,date,link,_links,_embedded`,
        { next: { revalidate: 300 } },
      ),
    ]);
    if (!catRes.ok || !postsRes.ok) return null;
    const cats = await catRes.json();
    if (!cats.length) return null;
    const raw = await postsRes.json();
    const posts = (raw as Array<any>).map((p: any) => ({
      id: p.id,
      slug: p.slug,
      title: (p.title?.rendered ?? "").replace(/<[^>]*>/g, ""),
      excerpt: (p.excerpt?.rendered ?? "").replace(/<[^>]*>/g, ""),
      date: p.date,
      link: p.link,
      image: p._embedded?.["wp:featuredmedia"]?.[0]?.source_url ?? null,
    }));
    return { category: cats[0].name, posts };
  } catch {
    return null;
  }
}

export async function generateStaticParams() {
  if (!WP_URL) return [];
  try {
    const res = await fetch(`${WP_URL}/wp-json/wp/v2/categories?per_page=50&_fields=slug`, {
      next: { revalidate: 300 },
    });
    if (!res.ok) return [];
    const cats: Array<{ slug: string }> = await res.json();
    return cats.map((c) => ({ slug: c.slug }));
  } catch {
    return [];
  }
}

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const { slug } = await params;
  const [content, data] = await Promise.all([getHomeContent(), getCategoryPosts(slug)]);
  if (!data) return {};
  return {
    title: `${data.category} — Blog — ${content.siteTitle}`,
    description: content.siteDescription,
    icons: content.siteIcon ? [{ rel: "icon", url: content.siteIcon }] : undefined,
  };
}

export default async function CategoryPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const [content, data, menu] = await Promise.all([getHomeContent(), getCategoryPosts(slug), getMenu()]);
  if (!data) notFound();

  return (
    <main className="v4-bg">
      <Header content={content} menuItems={menu} />
      <section style={{ padding: "72px 0 110px" }}>
        <div className="container">
          <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 32 }}>
            <Link href="/blog" style={{ fontWeight: 700, fontSize: 14, color: "#006568" }}>← Blog</Link>
            <span style={{ color: "#7e6516", fontSize: 12, fontWeight: 700, letterSpacing: ".14em", textTransform: "uppercase" }}>
              {data.category}
            </span>
          </div>
          {data.posts.length === 0 ? (
            <p style={{ fontSize: 17, color: "#515a63" }}>No posts in this category yet.</p>
          ) : (
            <div className="grid-3" style={{ marginTop: 24 }}>
              {data.posts.map((post) => (
                <article key={post.id} className="glass-card card-lift" style={{ padding: 0, overflow: "hidden" }}>
                  <Link href={`/blog/${post.slug}`} style={{ display: "block", textDecoration: "none" }}>
                    {post.image ? (
                      <Image src={post.image} alt="" style={{ width: "100%", height: 190, objectFit: "cover", display: "block" }} />
                    ) : (
                      <div style={{ height: 190, background: "linear-gradient(150deg,#13a3a6,#006568)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                        <Image src="/img/logo.webp" alt="" style={{ height: 34, filter: "brightness(0) invert(1)", opacity: 0.85 }} />
                      </div>
                    )}
                    <div style={{ padding: "24px 26px 28px" }}>
                      <h2 style={{ fontWeight: 900, fontSize: 20, lineHeight: 1.25, letterSpacing: "-.01em", margin: 0, color: "#182233" }}>
                        {post.title}
                      </h2>
                      <p style={{ fontSize: 14, lineHeight: 1.6, color: "#515a63", margin: "10px 0 0" }}>
                        {post.excerpt.length > 160 ? `${post.excerpt.slice(0, 160)}…` : post.excerpt}
                      </p>
                    </div>
                  </Link>
                </article>
              ))}
            </div>
          )}
        </div>
      </section>
      <Footer content={content} />
    </main>
  );
}
