import prisma from "@/lib/prisma";
import { notFound } from "next/navigation";
import Link from "next/link";
import type { Metadata } from "next";
import { HelpArticleContent } from "./help-article-content";

export const revalidate = 3600;

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

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

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const article = await prisma.helpArticle.findUnique({
    where: { slug, published: true },
  });

  if (!article) return { title: "Article Not Found" };

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

  return {
    title: `${article.title} | Help Center | AdultWorld`,
    description: article.excerpt || article.content.slice(0, 160),
    openGraph: {
      title: `${article.title} | Help Center`,
      description: article.excerpt || article.content.slice(0, 160),
      url: `${baseUrl}/help/${article.slug}`,
    },
    alternates: {
      canonical: `${baseUrl}/help/${article.slug}`,
    },
  };
}

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

  const article = await prisma.helpArticle.findUnique({
    where: { slug, published: true },
  });

  if (!article) notFound();

  // Related articles (same category, excluding current)
  const relatedArticles = await prisma.helpArticle.findMany({
    where: {
      published: true,
      category: article.category,
      id: { not: article.id },
    },
    orderBy: { views: "desc" },
    take: 4,
    select: { id: true, title: true, slug: true, excerpt: true },
  });

  // Category articles for sidebar
  const categoryArticles = await prisma.helpArticle.findMany({
    where: {
      published: true,
      category: article.category,
    },
    orderBy: { sort_order: "asc" },
    select: { id: true, title: true, slug: true },
  });

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

  const baseUrl = process.env.NEXT_PUBLIC_APP_URL || "https://www.adultworld.ai";
  const articleUrl = `${baseUrl}/help/${article.slug}`;

  // HowTo schema when the title is procedural ("How to ..."), Article
  // schema otherwise. HowTo unlocks step-by-step rich snippets on Google
  // and gives AI crawlers a structured walkthrough to cite.
  const isHowTo = /^how\s+to\b/i.test(article.title.trim());
  const stepRegex = /^##\s+(.+?)\s*$([\s\S]*?)(?=^##\s|\Z)/gm;
  const steps = isHowTo
    ? Array.from(article.content.matchAll(stepRegex)).slice(0, 20).map((m, i) => ({
        "@type": "HowToStep",
        position: i + 1,
        name: m[1].trim(),
        text: m[2].trim().slice(0, 400),
      }))
    : [];

  const helpLd = isHowTo && steps.length > 0
    ? {
        "@context": "https://schema.org",
        "@type": "HowTo",
        name: article.title,
        description: article.excerpt || article.content.slice(0, 160),
        totalTime: undefined,
        step: steps,
        url: articleUrl,
        inLanguage: "en",
      }
    : {
        "@context": "https://schema.org",
        "@type": "Article",
        headline: article.title,
        description: article.excerpt || article.content.slice(0, 160),
        articleSection: categoryLabel(article.category),
        keywords: tags.length > 0 ? tags.join(", ") : undefined,
        datePublished: article.created_at?.toISOString(),
        dateModified: article.updated_at?.toISOString(),
        url: articleUrl,
        inLanguage: "en",
        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": articleUrl },
      };

  return (
    <article className="max-w-5xl mx-auto">
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(helpLd) }}
      />
      {/* Breadcrumbs */}
      <nav className="text-sm text-text-muted mb-6">
        <Link href="/help" className="hover:text-primary transition-colors">
          Help Center
        </Link>
        <span className="mx-2">/</span>
        <Link
          href={`/help/category/${article.category}`}
          className="hover:text-primary transition-colors"
        >
          {categoryLabel(article.category)}
        </Link>
        <span className="mx-2">/</span>
        <span className="text-text">{article.title}</span>
      </nav>

      <div className="lg:grid lg:grid-cols-[1fr_260px] lg:gap-8">
        {/* Main Content */}
        <div className="min-w-0">
          {/* Header */}
          <header className="mb-8">
            <Link
              href={`/help/category/${article.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(article.category)}
            </Link>
            <h1 className="text-3xl md:text-4xl font-bold mb-4 leading-tight">
              {article.title}
            </h1>
            {article.excerpt && (
              <p className="text-text-muted text-lg leading-relaxed">
                {article.excerpt}
              </p>
            )}
            <div className="flex flex-wrap items-center gap-4 text-sm text-text-muted mt-4">
              <span>
                Updated{" "}
                {new Date(article.updated_at).toLocaleDateString(undefined, {
                  day: "numeric",
                  month: "long",
                  year: "numeric",
                })}
              </span>
              <span>{article.views.toLocaleString()} views</span>
            </div>
          </header>

          {/* Markdown Content */}
          <HelpArticleContent
            content={article.content}
            slug={article.slug}
          />

          {/* Tags */}
          {tags.length > 0 && (
            <div className="mt-8 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>
          )}

          {/* Related Articles */}
          {relatedArticles.length > 0 && (
            <section className="mt-12">
              <h2 className="text-xl font-bold mb-4">Related Articles</h2>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {relatedArticles.map((related) => (
                  <Link
                    key={related.id}
                    href={`/help/${related.slug}`}
                    className="bg-surface rounded-lg p-4 hover:ring-1 hover:ring-primary transition-all group"
                  >
                    <h3 className="font-semibold text-sm group-hover:text-primary transition-colors">
                      {related.title}
                    </h3>
                    {related.excerpt && (
                      <p className="text-text-muted text-xs mt-2 line-clamp-2">
                        {related.excerpt}
                      </p>
                    )}
                  </Link>
                ))}
              </div>
            </section>
          )}
        </div>

        {/* Sidebar */}
        <aside className="hidden lg:block">
          <div className="sticky top-24 space-y-6">
            {/* Category Navigation */}
            <div className="bg-surface rounded-lg p-4">
              <h3 className="text-sm font-semibold mb-3 text-text-muted uppercase tracking-wide">
                {categoryLabel(article.category)}
              </h3>
              <ul className="space-y-1">
                {categoryArticles.map((a) => (
                  <li key={a.id}>
                    <Link
                      href={`/help/${a.slug}`}
                      className={`block text-sm py-1.5 px-2 rounded transition-colors ${
                        a.slug === slug
                          ? "text-primary bg-primary/10 font-medium"
                          : "text-text-muted hover:text-primary hover:bg-surface-light"
                      }`}
                    >
                      {a.title}
                    </Link>
                  </li>
                ))}
              </ul>
            </div>

            {/* Back to Help Center */}
            <Link
              href="/help"
              className="flex items-center gap-2 text-sm text-text-muted hover:text-primary transition-colors"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
              </svg>
              Back to Help Center
            </Link>
          </div>
        </aside>
      </div>

      {/* Mobile sidebar navigation */}
      <div className="lg:hidden mt-8">
        <details className="bg-surface rounded-lg">
          <summary className="px-4 py-3 cursor-pointer text-text font-semibold text-sm flex items-center justify-between">
            More in {categoryLabel(article.category)}
            <span className="text-text-muted">&#9660;</span>
          </summary>
          <div className="px-4 pb-4 space-y-1">
            {categoryArticles.map((a) => (
              <Link
                key={a.id}
                href={`/help/${a.slug}`}
                className={`block text-sm py-1.5 px-2 rounded transition-colors ${
                  a.slug === slug
                    ? "text-primary bg-primary/10 font-medium"
                    : "text-text-muted hover:text-primary"
                }`}
              >
                {a.title}
              </Link>
            ))}
          </div>
        </details>
      </div>
    </article>
  );
}
