import prisma from "@/lib/prisma";
import { cache } from "react";
import { notFound } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import type { Metadata } from "next";
import { BlogPostContent } from "./blog-post-content";
import { BlogPostMarkdown } from "./blog-post-markdown";

// Blog bodies rarely change once published — ISR with hourly refresh
// keeps Postgres off the hot path for crawler / share-link traffic.
export const revalidate = 3600;

// R15 C.6: dedupe the per-request lookup. generateMetadata and the page
// body each previously called findUnique; React.cache collapses them to
// a single Postgres roundtrip when both run in the same request.
const getPostBySlug = cache((slug: string) =>
  prisma.blogPost.findUnique({ where: { slug, published: true } }),
);

type Props = {
  params: Promise<{ slug: string }>;
};

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const post = await getPostBySlug(slug);

  if (!post) return { title: "Post Not Found" };

  const baseUrl = process.env.NEXT_PUBLIC_APP_URL || "https://www.adultworld.ai";

  return {
    title: post.meta_title || post.title,
    description: post.meta_description || post.excerpt || undefined,
    openGraph: {
      title: post.meta_title || post.title,
      description: post.meta_description || post.excerpt || undefined,
      type: "article",
      publishedTime: post.published_at?.toISOString(),
      modifiedTime: post.updated_at.toISOString(),
      images: post.og_image ? [{ url: post.og_image, width: 1200, height: 630 }] : undefined,
      url: `${baseUrl}/blog-posts/${post.slug}`,
    },
    twitter: {
      card: "summary_large_image",
      title: post.meta_title || post.title,
      description: post.meta_description || post.excerpt || undefined,
      images: post.og_image ? [post.og_image] : undefined,
    },
    alternates: {
      canonical: `${baseUrl}/blog-posts/${post.slug}`,
    },
  };
}

function formatDate(date: Date | null) {
  if (!date) return "";
  return new Intl.DateTimeFormat(undefined, {
    day: "numeric",
    month: "long",
    year: "numeric",
  }).format(new Date(date));
}

function categoryLabel(value: string | null) {
  if (!value) return null;
  return value.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
}

export default async function BlogPostPage({ params }: Props) {
  const { slug } = await params;

  const post = await getPostBySlug(slug);

  if (!post) notFound();

  const baseUrl = process.env.NEXT_PUBLIC_APP_URL || "https://www.adultworld.ai";
  const postUrl = `${baseUrl}/blog-posts/${post.slug}`;

  // Fetch related posts and prev/next in parallel
  const [relatedPosts, prevPost, nextPost] = await Promise.all([
    prisma.blogPost.findMany({
      where: {
        published: true,
        category: post.category,
        id: { not: post.id },
      },
      orderBy: { published_at: "desc" },
      take: 3,
      select: { id: true, title: true, slug: true, excerpt: true, og_image: true, read_time: true, category: true, published_at: true },
    }),
    prisma.blogPost.findFirst({
      where: {
        published: true,
        published_at: post.published_at ? { lt: post.published_at } : undefined,
      },
      orderBy: { published_at: "desc" },
      select: { title: true, slug: true },
    }),
    prisma.blogPost.findFirst({
      where: {
        published: true,
        published_at: post.published_at ? { gt: post.published_at } : undefined,
      },
      orderBy: { published_at: "asc" },
      select: { title: true, slug: true },
    }),
  ]);

  const tags = post.tags ? post.tags.split(",").map((t) => t.trim()).filter(Boolean) : [];

  // BlogPosting JSON-LD with the full set of fields Google and AI crawlers
  // expect: author, publisher with logo, image with width/height, language,
  // section (category), keywords, and a short excerpt of the body.
  const wordCount = post.content ? post.content.split(/\s+/).length : 0;
  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "BlogPosting",
    headline: post.title,
    description: post.meta_description || post.excerpt || "",
    image: post.og_image
      ? [{ "@type": "ImageObject", url: post.og_image, width: 1200, height: 630 }]
      : undefined,
    datePublished: post.published_at?.toISOString(),
    dateModified: post.updated_at.toISOString(),
    url: postUrl,
    inLanguage: "en",
    articleSection: post.category || undefined,
    keywords: tags.length > 0 ? tags.join(", ") : undefined,
    wordCount,
    articleBody: post.content ? post.content.slice(0, 500) : undefined,
    author: {
      "@type": "Organization",
      name: "AdultWorld Editorial",
      url: baseUrl,
    },
    publisher: {
      "@type": "Organization",
      name: "AdultWorld",
      url: baseUrl,
      logo: {
        "@type": "ImageObject",
        url: `${baseUrl}/logo.png`,
      },
    },
    mainEntityOfPage: {
      "@type": "WebPage",
      "@id": postUrl,
    },
  };

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />

      <article className="max-w-4xl mx-auto">
        {/* Breadcrumb */}
        <nav className="text-sm text-text-muted mb-6">
          <Link href="/blog-posts" className="hover:text-primary transition-colors">
            Blog
          </Link>
          {post.category && (
            <>
              <span className="mx-2">/</span>
              <Link
                href={`/blog-posts/category/${post.category}`}
                className="hover:text-primary transition-colors"
              >
                {categoryLabel(post.category)}
              </Link>
            </>
          )}
          <span className="mx-2">/</span>
          <span className="text-text">{post.title}</span>
        </nav>

        {/* Header */}
        <header className="mb-8">
          {post.category && (
            <Link
              href={`/blog-posts/category/${post.category}`}
              className="inline-block text-xs font-semibold text-primary bg-primary/10 px-3 py-1 rounded-full mb-4 hover:bg-primary/20 transition-colors"
            >
              {categoryLabel(post.category)}
            </Link>
          )}
          <h1 className="text-3xl md:text-4xl font-bold mb-4 leading-tight">{post.title}</h1>
          <div className="flex flex-wrap items-center gap-4 text-sm text-text-muted">
            <time dateTime={post.published_at?.toISOString()}>
              {formatDate(post.published_at)}
            </time>
            <span>{post.read_time} min read</span>
            <span>{post.views.toLocaleString()} views</span>
          </div>
        </header>

        {/* Featured Image */}
        {post.og_image && (
          <div className="mb-8 rounded-lg overflow-hidden">
            <img
              src={post.og_image}
              alt={post.title}
              className="w-full h-auto max-h-96 object-cover"
            />
          </div>
        )}

        {/* Content with TOC */}
        <div className="lg:grid lg:grid-cols-[1fr_220px] lg:gap-8">
          <div className="min-w-0">
            <BlogPostContent slug={post.slug} postUrl={postUrl} />
            <BlogPostMarkdown content={post.content} />
          </div>

          {/* Sidebar with Share + TOC placeholder rendered client-side */}
          <aside className="hidden lg:block">
            <div className="sticky top-24 space-y-6">
              {/* Share Buttons */}
              <div className="bg-surface rounded-lg p-4">
                <h3 className="text-sm font-semibold mb-3 text-text-muted uppercase tracking-wide">
                  Share
                </h3>
                <div className="flex flex-col gap-2">
                  <a
                    href={`https://twitter.com/intent/tweet?url=${encodeURIComponent(postUrl)}&text=${encodeURIComponent(post.title)}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-2 text-sm text-text-muted hover:text-primary transition-colors py-1"
                  >
                    <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
                    </svg>
                    Post on X
                  </a>
                  <a
                    href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(postUrl)}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-2 text-sm text-text-muted hover:text-primary transition-colors py-1"
                  >
                    <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z" />
                    </svg>
                    Share on Facebook
                  </a>
                  <a
                    href={`https://wa.me/?text=${encodeURIComponent(`Check out this article on AdultWorld: ${postUrl}`)}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-2 text-sm text-text-muted hover:text-green-400 transition-colors py-1"
                  >
                    <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
                    </svg>
                    WhatsApp
                  </a>
                  <a
                    href={`https://t.me/share/url?url=${encodeURIComponent(postUrl)}&text=${encodeURIComponent(post.title)}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-2 text-sm text-text-muted hover:text-blue-400 transition-colors py-1"
                  >
                    <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.479.33-.913.492-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z" />
                    </svg>
                    Telegram
                  </a>
                  <a
                    href={`mailto:?subject=${encodeURIComponent(post.title)}&body=${encodeURIComponent(`${post.title}\n\n${postUrl}`)}`}
                    className="flex items-center gap-2 text-sm text-text-muted hover:text-primary transition-colors py-1"
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                    </svg>
                    Email
                  </a>
                </div>
              </div>

              {/* Tags */}
              {tags.length > 0 && (
                <div className="bg-surface rounded-lg p-4">
                  <h3 className="text-sm font-semibold mb-3 text-text-muted uppercase tracking-wide">
                    Tags
                  </h3>
                  <div className="flex flex-wrap gap-2">
                    {tags.map((tag) => (
                      <span
                        key={tag}
                        className="text-xs bg-surface-light text-text-muted px-2 py-1 rounded"
                      >
                        {tag}
                      </span>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </aside>
        </div>

        {/* Mobile Share Buttons */}
        <div className="lg:hidden mt-8 bg-surface rounded-lg p-4">
          <h3 className="text-sm font-semibold mb-3 text-text-muted uppercase tracking-wide">
            Share this article
          </h3>
          <div className="flex gap-3">
            <a
              href={`https://twitter.com/intent/tweet?url=${encodeURIComponent(postUrl)}&text=${encodeURIComponent(post.title)}`}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center gap-2 bg-surface-light hover:bg-primary/20 text-text-muted hover:text-primary px-4 py-2 rounded-lg text-sm transition-colors"
            >
              Post on X
            </a>
            <a
              href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(postUrl)}`}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center gap-2 bg-surface-light hover:bg-primary/20 text-text-muted hover:text-primary px-4 py-2 rounded-lg text-sm transition-colors"
            >
              Facebook
            </a>
          </div>
        </div>

        {/* Tags Mobile */}
        {tags.length > 0 && (
          <div className="lg:hidden mt-4">
            <div className="flex flex-wrap gap-2">
              {tags.map((tag) => (
                <span
                  key={tag}
                  className="text-xs bg-surface-light text-text-muted px-2 py-1 rounded"
                >
                  {tag}
                </span>
              ))}
            </div>
          </div>
        )}

        {/* Previous/Next Navigation */}
        <nav className="mt-12 grid grid-cols-1 md:grid-cols-2 gap-4">
          {prevPost ? (
            <Link
              href={`/blog-posts/${prevPost.slug}`}
              className="bg-surface rounded-lg p-4 hover:ring-1 hover:ring-primary transition-all group"
            >
              <span className="text-xs text-text-muted uppercase tracking-wide">Previous</span>
              <p className="font-medium mt-1 group-hover:text-primary transition-colors line-clamp-2">
                {prevPost.title}
              </p>
            </Link>
          ) : (
            <div />
          )}
          {nextPost && (
            <Link
              href={`/blog-posts/${nextPost.slug}`}
              className="bg-surface rounded-lg p-4 hover:ring-1 hover:ring-primary transition-all group text-right"
            >
              <span className="text-xs text-text-muted uppercase tracking-wide">Next</span>
              <p className="font-medium mt-1 group-hover:text-primary transition-colors line-clamp-2">
                {nextPost.title}
              </p>
            </Link>
          )}
        </nav>

        {/* Related Posts */}
        {relatedPosts.length > 0 && (
          <section className="mt-12">
            <h2 className="text-2xl font-bold mb-6">Related Articles</h2>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              {relatedPosts.map((related) => (
                <Link
                  key={related.id}
                  href={`/blog-posts/${related.slug}`}
                  className="bg-surface rounded-lg overflow-hidden hover:ring-1 hover:ring-primary transition-all group"
                >
                  {related.og_image && (
                    <div className="h-36 overflow-hidden">
                      <img
                        src={related.og_image}
                        alt={related.title}
                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                      />
                    </div>
                  )}
                  <div className="p-4">
                    <h3 className="font-semibold group-hover:text-primary transition-colors line-clamp-2">
                      {related.title}
                    </h3>
                    {related.excerpt && (
                      <p className="text-text-muted text-sm mt-2 line-clamp-2">
                        {related.excerpt}
                      </p>
                    )}
                  </div>
                </Link>
              ))}
            </div>
          </section>
        )}
      </article>
    </>
  );
}
