import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import DOMPurify from "isomorphic-dompurify";

import { Container } from "@/components/Container";
import { formatLegacyDate } from "@/lib/legacy/content";
import { processArticle } from "@/lib/blog/process-article";
import { VIDEO_IFRAME_PREFIXES } from "@/lib/blog/video-embed";
import {
  getUnifiedPostBySlug,
  getAdjacentPosts,
  getRelatedPosts,
  listUnifiedPosts,
} from "@/lib/blog/unified";
import { ReadingProgress } from "@/components/blog/ReadingProgress";
import { ArticleTOC } from "@/components/blog/ArticleTOC";
import { ShareBar } from "@/components/blog/ShareBar";
import { HeroReveal, HeroItem } from "@/components/blog/HeroReveal";
import { JsonLd } from "@/components/JsonLd";
import { siteConfig } from "@/lib/site-config";

type Params = { slug: string };

export const dynamic = "force-dynamic";

function stripUntrustedIframes(html: string): string {
  return html.replace(
    /<iframe\b[^>]*>(?:[\s\S]*?<\/iframe>)?/gi,
    (match) => {
      const src = /\bsrc=["']([^"']+)["']/i.exec(match)?.[1] ?? "";
      if (!src) return "";
      return VIDEO_IFRAME_PREFIXES.some((p) => src.startsWith(p)) ? match : "";
    },
  );
}

export async function generateStaticParams(): Promise<Params[]> {
  // DB posts are rendered on demand (dynamic = force-dynamic); legacy posts
  // still prerender so cold starts are fast for the existing archive.
  const all = await listUnifiedPosts();
  return all.filter((p) => p.source === "legacy").map((p) => ({ slug: p.slug }));
}

export async function generateMetadata({
  params,
}: {
  params: Promise<Params>;
}): Promise<Metadata> {
  const { slug } = await params;
  const post = await getUnifiedPostBySlug(slug);
  if (!post) return { title: "Post not found" };
  return {
    title: post.title,
    description: post.excerpt || undefined,
    openGraph: {
      title: post.title,
      description: post.excerpt || undefined,
      type: "article",
      url: `/blog/${post.slug}`,
      images: post.featuredImage ? [post.featuredImage] : undefined,
    },
  };
}

export default async function BlogPostPage({
  params,
}: {
  params: Promise<Params>;
}) {
  const { slug } = await params;
  const post = await getUnifiedPostBySlug(slug);
  if (!post) notFound();

  // Allow <iframe> only when src matches one of the trusted video provider
  // prefixes (YouTube nocookie, Vimeo). Everything else strips as usual.
  const clean = DOMPurify.sanitize(post.html, {
    USE_PROFILES: { html: true },
    FORBID_TAGS: ["script", "style", "form"],
    FORBID_ATTR: ["onerror", "onclick", "onload", "onmouseover"],
    ADD_TAGS: ["iframe"],
    ADD_ATTR: ["allow", "allowfullscreen", "loading", "frameborder"],
  });
  // Secondary pass — strip any iframe whose src isn't on our trusted list.
  // DOMPurify doesn't natively support src prefix allow-lists, so we parse
  // the output and drop unsafe iframes.
  const safe = stripUntrustedIframes(clean);

  const { html, toc, readingMinutes, wordCount } = processArticle(safe);
  const topic = post.topic;
  const { prev, next } = await getAdjacentPosts(slug);
  const related = await getRelatedPosts(slug, topic, 3);

  const articleSchema = {
    "@context": "https://schema.org",
    "@type": "Article",
    headline: post.title,
    description: post.excerpt || undefined,
    image: post.featuredImage
      ? [new URL(post.featuredImage, siteConfig.url).toString()]
      : undefined,
    datePublished: post.date || undefined,
    dateModified: post.modifiedAt || post.date || undefined,
    author: { "@type": "Organization", name: "OrthoGlobe" },
    publisher: {
      "@type": "Organization",
      name: "OrthoGlobe",
      logo: {
        "@type": "ImageObject",
        url: `${siteConfig.url}/brand/orthoglobe-icon-256.webp`,
      },
    },
    mainEntityOfPage: {
      "@type": "WebPage",
      "@id": `${siteConfig.url}/blog/${post.slug}`,
    },
    wordCount,
    articleSection: topic,
  };

  return (
    <article>
      <JsonLd data={articleSchema} />
      <ReadingProgress />

      <section className="relative overflow-hidden border-b border-[var(--color-line)] bg-gradient-to-b from-[var(--color-mist)]/60 to-white pt-10 pb-10 md:pt-14 md:pb-14">
        <div
          aria-hidden
          className="pointer-events-none absolute -left-32 top-0 h-[480px] w-[480px] rounded-full bg-[var(--color-blue)]/10 blur-3xl"
        />
        <div
          aria-hidden
          className="pointer-events-none absolute -right-24 top-16 h-[360px] w-[360px] rounded-full bg-[var(--color-blue)]/5 blur-3xl"
        />
        <Container>
          <div className="relative mx-auto max-w-5xl">
            <HeroReveal>
              <HeroItem>
                <Link
                  href="/blog"
                  className="inline-flex items-center gap-2 text-[13px] font-semibold text-[var(--color-slate)] transition-colors hover:text-[var(--color-blue)]"
                >
                  <span>←</span> All articles
                </Link>
              </HeroItem>
              <HeroItem className="mt-8 flex items-center gap-3">
                <span className="inline-flex items-center rounded-full bg-[var(--color-blue)] px-3 py-1 text-[11px] font-bold uppercase tracking-wider text-white shadow-sm">
                  {topic}
                </span>
                <span className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                  Patient education
                </span>
              </HeroItem>
              <HeroItem>
                <h1 className="mt-6 font-display text-[40px] font-extrabold leading-[1.04] tracking-[-0.025em] text-[var(--color-ink)] md:text-[60px]">
                  {post.title}
                </h1>
              </HeroItem>
              {post.excerpt && (
                <HeroItem>
                  <p className="mt-6 max-w-3xl text-[20px] leading-[1.55] text-[var(--color-slate)]">
                    {post.excerpt}
                  </p>
                </HeroItem>
              )}
              <HeroItem>
                <div className="mt-10 grid grid-cols-2 gap-3 sm:grid-cols-4 sm:gap-4">
                  {post.date && (
                    <div className="rounded-xl border border-[var(--color-line)] bg-white/70 p-4 backdrop-blur-sm">
                      <div className="text-[10px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                        Published
                      </div>
                      <div className="mt-1 text-[14px] font-semibold text-[var(--color-ink)]">
                        {formatLegacyDate(post.date)}
                      </div>
                    </div>
                  )}
                  <div className="rounded-xl border border-[var(--color-line)] bg-white/70 p-4 backdrop-blur-sm">
                    <div className="text-[10px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                      Reading time
                    </div>
                    <div className="mt-1 text-[14px] font-semibold text-[var(--color-ink)]">
                      {readingMinutes} min
                    </div>
                  </div>
                  <div className="rounded-xl border border-[var(--color-line)] bg-white/70 p-4 backdrop-blur-sm">
                    <div className="text-[10px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                      Words
                    </div>
                    <div className="mt-1 text-[14px] font-semibold text-[var(--color-ink)]">
                      {wordCount.toLocaleString()}
                    </div>
                  </div>
                  {toc.length > 0 && (
                    <div className="rounded-xl border border-[var(--color-line)] bg-white/70 p-4 backdrop-blur-sm">
                      <div className="text-[10px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                        Sections
                      </div>
                      <div className="mt-1 text-[14px] font-semibold text-[var(--color-ink)]">
                        {toc.filter((t) => t.level === 2).length}
                      </div>
                    </div>
                  )}
                </div>
              </HeroItem>
            </HeroReveal>
          </div>
        </Container>
      </section>

      {post.featuredImage && (
        <Container className="pt-12">
          <div className="mx-auto max-w-6xl">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src={post.featuredImage}
              alt={post.title}
              className="aspect-[21/9] w-full rounded-2xl object-cover shadow-lg"
            />
          </div>
        </Container>
      )}

      <Container className="py-10 md:py-14">
        <div className="mx-auto grid max-w-7xl gap-16 lg:grid-cols-[minmax(0,1fr)_240px]">
          <div className="min-w-0">
            <div
              className="legacy-html blog-body"
              dangerouslySetInnerHTML={{ __html: html }}
            />

            <ShareBar title={post.title} slug={post.slug} />

            <div className="mt-12 rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)]/40 p-8">
              <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                Reviewed by OrthoGlobe
              </div>
              <p className="mt-3 text-[15px] leading-relaxed text-[var(--color-slate)]">
                Every article on OrthoGlobe is reviewed by practising orthopaedic surgeons for clinical accuracy and
                plain-language clarity. Content is for education only and does not replace advice from your treating clinician.
              </p>
            </div>

            {(prev || next) && (
              <div className="mt-12 grid gap-4 border-t border-[var(--color-line)] pt-10 sm:grid-cols-2">
                {prev ? (
                  <Link
                    href={`/blog/${prev.slug}`}
                    className="group block rounded-xl border border-[var(--color-line)] p-5 transition-all hover:-translate-y-0.5 hover:border-[var(--color-blue)] hover:shadow-md motion-reduce:transform-none"
                  >
                    <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                      ← Previous
                    </div>
                    <div className="mt-2 font-display text-[16px] font-bold leading-snug text-[var(--color-ink)] group-hover:text-[var(--color-blue)]">
                      {prev.title}
                    </div>
                  </Link>
                ) : (
                  <div />
                )}
                {next ? (
                  <Link
                    href={`/blog/${next.slug}`}
                    className="group block rounded-xl border border-[var(--color-line)] p-5 text-right transition-all hover:-translate-y-0.5 hover:border-[var(--color-blue)] hover:shadow-md motion-reduce:transform-none"
                  >
                    <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                      Next →
                    </div>
                    <div className="mt-2 font-display text-[16px] font-bold leading-snug text-[var(--color-ink)] group-hover:text-[var(--color-blue)]">
                      {next.title}
                    </div>
                  </Link>
                ) : (
                  <div />
                )}
              </div>
            )}
          </div>

          {toc.length > 0 && (
            <aside className="hidden lg:block">
              <div className="sticky top-28">
                <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                  On this page
                </div>
                <ArticleTOC toc={toc} />
              </div>
            </aside>
          )}
        </div>
      </Container>

      {related.length > 0 && (
        <section className="border-t border-[var(--color-line)] bg-[var(--color-mist)]/30 py-12 md:py-16">
          <Container>
            <div className="mx-auto max-w-6xl">
              <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                Keep reading
              </div>
              <h2 className="mt-3 font-display text-[28px] font-extrabold tracking-tight text-[var(--color-ink)] md:text-[34px]">
                More from {topic}
              </h2>
              <div className="mt-10 grid gap-6 md:grid-cols-3">
                {related.map((r) => (
                  <Link
                    key={r.id}
                    href={`/blog/${r.slug}`}
                    className="group flex flex-col overflow-hidden rounded-xl border border-[var(--color-line)] bg-white transition-all duration-300 hover:-translate-y-1 hover:border-[var(--color-blue)] hover:shadow-xl motion-reduce:transform-none"
                  >
                    <div className="relative aspect-[16/10] w-full overflow-hidden bg-[var(--color-mist)]">
                      {/* eslint-disable-next-line @next/next/no-img-element */}
                      <img
                        src={r.featuredImage ?? undefined}
                        alt=""
                        className="h-full w-full object-cover transition-transform duration-700 ease-out group-hover:scale-[1.06] motion-reduce:transform-none"
                        loading="lazy"
                      />
                    </div>
                    <div className="flex flex-1 flex-col p-5">
                      {r.date && (
                        <span className="text-[11px] font-semibold uppercase tracking-wider text-[var(--color-slate)]">
                          {formatLegacyDate(r.date)}
                        </span>
                      )}
                      <h3 className="mt-2 font-display text-[17px] font-bold leading-tight text-[var(--color-ink)] group-hover:text-[var(--color-blue)]">
                        {r.title}
                      </h3>
                    </div>
                  </Link>
                ))}
              </div>
            </div>
          </Container>
        </section>
      )}
    </article>
  );
}
