import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import Header from "@/components/Header";
import Footer from "@/components/Footer";
import { getHomeContent, getPost, getPosts } from "@/lib/wordpress";
import { processContent } from "@/lib/blog/toc";
import { ArticleJsonLd } from "@/components/JsonLd";

export async function generateStaticParams() {
  const { posts } = await getPosts(100);
  return posts.map((p) => ({ slug: p.slug }));
}

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

function formatDate(iso: string): string {
  return new Date(iso).toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" });
}

export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const [content, post] = await Promise.all([getHomeContent(), getPost(slug)]);

  if (!post) notFound();

  const { html: processedContent, toc } = processContent(post.content);

  const SITE_URL = "https://sigmataxpro.com";

  return (
    <>
      <ArticleJsonLd
        title={post.title}
        description={post.excerpt.slice(0, 200)}
        url={`${SITE_URL}/blog/${post.slug}/`}
        image={post.image}
        datePublished={post.date}
      />
      <main className="v4-bg">
      <Header content={content} />
      <section style={{ padding: "72px 0 110px" }}>
        <div className="container">
          <Link href="/blog" style={{ display: "inline-flex", alignItems: "center", gap: 6, fontWeight: 700, fontSize: 14, color: "#006568", marginBottom: 24 }}>
            ← Back to blog
          </Link>

          <div className="blog-layout">
            {/* ToC first in DOM — on mobile it appears above the content naturally */}
            {toc.length > 0 && (
              <aside className="blog-toc">
                <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: ".14em", textTransform: "uppercase", color: "#7e6516", marginBottom: 16 }}>
                  On this page
                </div>
                <nav style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                  {toc.map((entry) => (
                    <a
                      key={entry.id}
                      href={`#${entry.id}`}
                      style={{
                        display: "block",
                        fontSize: 13,
                        lineHeight: 1.5,
                        color: "#4a545c",
                        textDecoration: "none",
                        paddingLeft: entry.level === 3 ? 16 : 0,
                        borderLeft: "2px solid transparent",
                        transition: "color .15s, border-color .15s",
                      }}
                    >
                      {entry.text}
                    </a>
                  ))}
                </nav>
              </aside>
            )}

            {/* Main article */}
            <article className="blog-main">
              {post.image && (
                /* eslint-disable-next-line @next/next/no-img-element */
                <img
                  src={post.image}
                  alt=""
                  style={{ width: "100%", height: 320, objectFit: "cover", borderRadius: 16, display: "block" }}
                />
              )}
              <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: ".08em", color: "#7e6516", textTransform: "uppercase", marginTop: post.image ? 28 : 0 }}>
                {formatDate(post.date)}
              </div>
              <h1 style={{ fontWeight: 900, fontSize: 42, lineHeight: 1.08, letterSpacing: "-.025em", margin: "10px 0 0", color: "#182233" }}>
                {post.title}
              </h1>
              <div
                className="post-content"
                style={{ marginTop: 28, fontSize: 17, lineHeight: 1.8, color: "#2c353e" }}
                dangerouslySetInnerHTML={{ __html: processedContent }}
              />
            </article>
          </div>
        </div>
      </section>
        <Footer content={content} />
      </main>
    </>
  );
}
