import type { Metadata } from "next";
import Link from "@/components/Link";
import { notFound } from "next/navigation";
import Breadcrumbs from "@/components/Breadcrumbs";
import { BlogCard, BlogCta, blogLongDate } from "@/components/BlogParts";
import Icon from "@/components/Icon";
import SiteEffects from "@/components/SiteEffects";
import { blogAuthor, blogPosts, postBySlug } from "@/content/blog-posts";
import { absoluteUrl, blogPostingLd, crumbTrail, faqLd, JsonLd, PageJsonLd, pageMeta } from "@/lib/seo";
import { signupHref } from "@/lib/site";

export function generateStaticParams() {
  return blogPosts.map((p) => ({ slug: p.slug }));
}

export async function generateMetadata({ params }: PageProps<"/blog/[slug]">): Promise<Metadata> {
  const { slug } = await params;
  const post = postBySlug[slug];
  // The page itself sends the 404. notFound() here would come too late for crawlers that get streamed metadata:
  // their 200 header is already out, which makes the error page a soft 404.
  if (!post) return {};
  return pageMeta({
    title: post.title,
    description: post.excerpt,
    path: `/blog/${slug}`,
    image: `/blog/${slug}/opengraph-image`,
    imageAlt: post.title,
    published: post.date,
  });
}

const articleFoot = '<div class="an-article-foot"><a class="an-link" href="/blog"><span aria-hidden="true">←</span> Back to all articles</a></div>';

/** Add ids to h2/h3 headings and build the "On this page" list. */
function withToc(html: string) {
  const toc: { id: string; text: string }[] = [];
  const used = new Set<string>();
  const body = html.replace(/<h([23])>([\s\S]*?)<\/h\1>/g, (_, level: string, inner: string) => {
    const text = inner.replace(/<[^>]+>/g, "").trim();
    const base = text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "section";
    let id = base;
    for (let n = 2; used.has(id); n += 1) id = `${base}-${n}`;
    used.add(id);
    // Main sections only: the articles run to 10+ h2s, and the FAQ questions are h3s.
    if (level === "2") toc.push({ id, text });
    return `<h${level} id="${id}">${inner}</h${level}>`;
  });
  // Wide tables scroll inside their own box instead of widening the page on phones.
  return { body: body.replace(/<table[\s\S]*?<\/table>/g, '<div class="an-article-table">$&</div>'), toc };
}

// Every post is prerendered (generateStaticParams), so the navigation may wait for it instead of painting a
// placeholder first; this tells Next's instant-navigation check that blocking here is intended.
export const instant = false;

export default async function BlogPostPage({ params }: PageProps<"/blog/[slug]">) {
  const { slug } = await params;
  const post = postBySlug[slug];
  if (!post) notFound();

  const { body, toc } = withToc(post.body);
  const others = blogPosts.filter((p) => p.slug !== slug).sort((a, b) => b.date.localeCompare(a.date)).slice(0, 3);
  const shareUrl = absoluteUrl(`/blog/${slug}`);
  const url = encodeURIComponent(shareUrl);
  const title = encodeURIComponent(post.title);

  return (
    <>
      <PageJsonLd path={`/blog/${slug}`} />
      <JsonLd data={blogPostingLd(post)} />
      {post.faqs.length ? <JsonLd data={faqLd(post)} /> : null}
      <section className="an-hero an-article-hero">
        <div className="an-wrap">
          <div className="an-hero__copy an-article-hero__copy"><Breadcrumbs items={crumbTrail(`/blog/${slug}`)} />
            <h1 className="an-h1">{post.title}</h1>
            <p className="an-lede">{post.excerpt}</p>
            <div className="an-article-by">
              <span className="an-article-by__av">A</span>
              <span>By <b>{blogAuthor}</b> on <time dateTime={post.date}>{blogLongDate(post)}</time></span>
              <span className="an-article-by__dot">{post.minutes} min read</span>
            </div>
          </div>
        </div>
      </section>
      <div className="an-wrap an-article-cover"><img src={post.image} alt={post.imageAlt} width={1600} height={1000} fetchPriority="high" /></div>

      <section className="an-section an-article-sec">
        <div className="an-wrap an-article-grid">
          {/* The prose styles target direct children, so the body and footer share one element. */}
          <article className="an-prose an-article-body" dangerouslySetInnerHTML={{ __html: body + articleFoot }} />
          <aside className="an-article-side">
            {toc.length > 1 ? (
              <nav className="an-article-toc" aria-label="On this page">
                <p>On this page</p>
                <ol>{toc.map((t) => <li key={t.id}><a href={`#${t.id}`}>{t.text}</a></li>)}</ol>
              </nav>
            ) : null}
            <div className="an-article-share">
              <p>Share</p>
              <div>
                <a href={`https://www.linkedin.com/sharing/share-offsite/?url=${url}`} target="_blank" rel="noopener" aria-label="Share on LinkedIn"><svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true"><path fill="currentColor" d="M20.45 20.45h-3.56v-5.57c0-1.33-.02-3.04-1.85-3.04-1.85 0-2.14 1.45-2.14 2.94v5.67H9.35V9h3.41v1.56h.05c.48-.9 1.64-1.85 3.37-1.85 3.6 0 4.27 2.37 4.27 5.46v6.28ZM5.34 7.43a2.06 2.06 0 1 1 0-4.13 2.06 2.06 0 0 1 0 4.13ZM7.12 20.45H3.56V9h3.56v11.45Z" /></svg></a>
                <a href={`https://twitter.com/intent/tweet?url=${url}&text=${title}`} target="_blank" rel="noopener" aria-label="Share on X"><svg viewBox="0 0 24 24" width="15" height="15" aria-hidden="true"><path fill="currentColor" d="M17.75 3h3.07l-6.7 7.66L22 21h-6.17l-4.83-6.32L5.47 21H2.4l7.17-8.2L2 3h6.33l4.37 5.78L17.75 3Zm-1.08 16.2h1.7L7.4 4.72H5.57L16.67 19.2Z" /></svg></a>
                <a href={`https://www.facebook.com/sharer/sharer.php?u=${url}`} target="_blank" rel="noopener" aria-label="Share on Facebook"><svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true"><path fill="currentColor" d="M14 8.5V6.7c0-.8.5-1 .9-1H17V2.1L14 2c-3.3 0-4 2.5-4 4.1v2.4H8v3.6h2V22h4v-9.9h2.7l.4-3.6H14Z" /></svg></a>
                <a href={`mailto:?subject=${title}&body=${url}`} aria-label="Share by email"><Icon name="mail" size={16} /></a>
                <button type="button" data-copy={shareUrl} aria-label="Copy link"><Icon name="link" size={16} /></button>
              </div>
            </div>
            <div className="an-article-ctacard">
              <b>Reach your next customers</b>
              <p>Plan search, AI discovery, social and video campaigns with one team.</p>
              <a className="an-btn an-btn--white an-btn--sm" href={signupHref} data-track="signup_click" data-track-location="blog_sidebar">Start Advertising</a>
            </div>
          </aside>
        </div>
      </section>

      <section className="an-section an-section--paper">
        <div className="an-wrap">
          <div className="an-head an-reveal"><h2 className="an-h2">Related articles</h2></div>
          <div className="an-blog-grid an-reveal">{others.map((p) => <BlogCard key={p.slug} post={p} showExcerpt={false} />)}</div>
        </div>
      </section>
      <BlogCta />
      <SiteEffects />
    </>
  );
}
