/**
 * صفحه مقاله مجله: /mag/{اسلاگ}
 * داده ساختاریافته BlogPosting و FAQPage (برای گوگل و موتورهای پاسخ هوش مصنوعی)، فهرست مطالب،
 * کارت‌های محصول درون متن، دکمه دعوت به اقدام و محصولات مرتبط.
 */
import type { Metadata } from "next";
import Link from "next/link";
import { notFound, permanentRedirect } from "next/navigation";
import { Breadcrumbs } from "@/components/ui/Breadcrumbs";
import { ProductCard } from "@/components/product/ProductCard";
import { ProductRail } from "@/components/product/ProductRail";
import { ArticleCard } from "@/components/magazine/ArticleCard";
import { ArticleBody, ArticleImage, Inline, parseArticle, productIdsIn, readingMinutes } from "@/lib/article-markdown";
import { decodeSegment } from "@/lib/route-params";
import { faNumber, formatJalali } from "@/lib/format";
import { imageSrc } from "@/lib/media";
import { seo } from "@/lib/seo";
import { site } from "@/lib/site";
import { getCurrentUser } from "@/server/auth/session";
import { getSummariesByIds } from "@/server/services/catalog";
import { findMovedArticle, getArticle, getRelatedArticles } from "@/server/services/magazine";

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

async function load({ params, searchParams }: Props) {
  const slug = decodeSegment((await params).slug);
  let preview = false;
  if ((await searchParams).preview === "1") {
    const user = await getCurrentUser();
    preview = user?.role === "ADMIN" || user?.role === "STAFF";
  }
  return { article: await getArticle(slug, preview), preview };
}

export async function generateMetadata(props: Props): Promise<Metadata> {
  const { article: a, preview } = await load(props);
  if (!a) return {};
  const meta = seo({
    title: a.seoTitle || a.title,
    description: a.seoDescription || a.excerpt,
    path: `/mag/${a.slug}`,
    image: a.coverUrl ? imageSrc(a.coverUrl, 1600) : undefined,
  });
  return {
    ...meta,
    ...(preview && a.status !== "PUBLISHED" ? { robots: { index: false, follow: false } } : {}),
    openGraph: { ...meta.openGraph, type: "article", publishedTime: a.publishedAt?.toISOString(), modifiedTime: a.updatedAt.toISOString() },
  };
}

export default async function ArticlePage(props: Props) {
  const { article: a, preview } = await load(props);
  if (!a) {
    // آدرس قدیمی مقاله‌ای که آدرسش عوض شده ← ریدایرکت دائمی به آدرس جدید
    const moved = await findMovedArticle(decodeSegment((await props.params).slug));
    if (moved) permanentRedirect(`/mag/${encodeURIComponent(moved)}`);
    notFound();
  }

  const blocks = parseArticle(a.body);
  const inlineIds = productIdsIn(blocks);
  const [inlineProducts, related, more] = await Promise.all([
    getSummariesByIds(inlineIds),
    getSummariesByIds(a.productIds),
    getRelatedArticles(a.slug),
  ]);
  const toc = blocks.filter((b) => b.type === "h2");
  const url = new URL(`/mag/${a.slug}`, site.url).toString();

  const jsonLd = [
    {
      "@context": "https://schema.org",
      "@type": "BlogPosting",
      headline: a.title,
      description: a.seoDescription || a.excerpt,
      mainEntityOfPage: url,
      url,
      datePublished: a.publishedAt?.toISOString(),
      dateModified: a.updatedAt.toISOString(),
      inLanguage: "fa-IR",
      image: a.coverUrl ? [new URL(imageSrc(a.coverUrl, 1600), site.url).toString()] : undefined,
      author: { "@type": a.authorName ? "Person" : "Organization", name: a.authorName || site.name },
      publisher: { "@type": "Organization", name: site.name, logo: { "@type": "ImageObject", url: new URL("/brand/logo-full.png", site.url).toString() } },
      keywords: a.focusKeyword || undefined,
      wordCount: a.body.split(/\s+/).length,
    },
    ...(a.faq.length
      ? [
          {
            "@context": "https://schema.org",
            "@type": "FAQPage",
            mainEntity: a.faq.map((f) => ({ "@type": "Question", name: f.q, acceptedAnswer: { "@type": "Answer", text: f.a } })),
          },
        ]
      : []),
  ];

  return (
    <>
      {preview && a.status !== "PUBLISHED" && <p className="bg-ink py-2 text-center text-xs text-paper">پیش‌نمایش پیش‌نویس؛ این صفحه هنوز منتشر نشده است</p>}
      <article className="container-z py-6 md:py-10">
        <div className="mx-auto max-w-3xl">
          <Breadcrumbs items={[{ name: "مجله", href: "/mag" }, { name: a.title }]} />
          <header className="mt-6">
            <h1 className="text-2xl leading-[1.6] font-extrabold md:text-4xl md:leading-[1.5]">{a.title}</h1>
            <p className="mt-3 text-base leading-8 text-ink-soft">{a.excerpt}</p>
            <p className="mt-4 flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted">
              {a.authorName && <span>{a.authorName}</span>}
              {a.publishedAt && <time dateTime={a.publishedAt.toISOString()}>{formatJalali(a.publishedAt)}</time>}
              <span>{faNumber(readingMinutes(a.body))} دقیقه مطالعه</span>
            </p>
          </header>
          {a.coverUrl && (
            <div className="mt-6">
              <ArticleImage src={a.coverUrl} alt={a.coverAlt ?? a.title} priority />
            </div>
          )}

          {toc.length >= 2 && (
            <nav aria-label="فهرست مطالب" className="mt-8 rounded-2xl bg-mist p-5">
              <p className="text-sm font-bold">در این مقاله</p>
              <ol className="mt-3 list-decimal space-y-1.5 ps-5 text-sm">
                {toc.map((h) => h.type === "h2" && <li key={h.id}><a href={`#${h.id}`} className="hover:underline"><Inline text={h.text} /></a></li>)}
              </ol>
            </nav>
          )}

          <div className="mt-2">
            <ArticleBody
              blocks={blocks}
              renderProduct={(id) => {
                const p = inlineProducts.find((x) => x.id === id);
                return p ? <div className="mx-auto max-w-[240px]"><ProductCard product={p} /></div> : null;
              }}
            />
          </div>

          {a.faq.length > 0 && (
            <section className="mt-12" aria-labelledby="faq-title">
              <h2 id="faq-title" className="text-xl font-extrabold">پرسش‌های متداول</h2>
              <div className="mt-4 divide-y divide-line rounded-2xl border border-line">
                {a.faq.map((f, i) => (
                  <details key={i} className="group p-4" open={i === 0}>
                    <summary className="cursor-pointer list-none text-sm font-bold [&::-webkit-details-marker]:hidden">{f.q}</summary>
                    <p className="mt-2 text-sm leading-7 text-ink-soft">{f.a}</p>
                  </details>
                ))}
              </div>
            </section>
          )}

          {a.ctaLabel && a.ctaHref && (
            <div className="mt-10 rounded-3xl bg-ink p-8 text-center text-paper">
              <p className="text-lg font-bold">{a.title}</p>
              {a.ctaHref.startsWith("/") ? (
                <Link href={a.ctaHref} className="mt-4 inline-flex h-12 items-center rounded-full bg-paper px-8 text-sm font-bold text-ink">{a.ctaLabel}</Link>
              ) : (
                <a href={a.ctaHref} target="_blank" rel="noopener noreferrer nofollow" className="mt-4 inline-flex h-12 items-center rounded-full bg-paper px-8 text-sm font-bold text-ink">{a.ctaLabel}</a>
              )}
            </div>
          )}
        </div>
      </article>

      {related.length > 0 && <ProductRail title="محصولات این مقاله" products={related} />}

      {more.length > 0 && (
        <section className="container-z border-t border-line py-10">
          <h2 className="mb-6 text-lg font-extrabold">مقاله‌های دیگر</h2>
          <div className="grid gap-x-6 gap-y-10 sm:grid-cols-2 lg:grid-cols-3">{more.map((m) => <ArticleCard key={m.slug} a={m} />)}</div>
        </section>
      )}

      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, "\\u003c") }} />
    </>
  );
}
