import type { Metadata } from "next";
import Link from "next/link";
import { JsonLd } from "@/components/JsonLd";
import { PageHero } from "@/components/PageHero";
import { RichText, Unavailable } from "@/components/RichText";
import { ShareBar } from "@/components/ShareBar";
import { ApiDown, api, siteUrl } from "@/lib/api";
import type { ArticleDetail } from "@/lib/types";

type Props = { params: Promise<{ slug: string }> };

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  try {
    const { slug } = await params;
    const article = await api<ArticleDetail>(`/articles/${slug}`);
    return { title: { absolute: article.seo.title }, description: article.seo.description ?? article.excerpt };
  } catch {
    return { title: "دانش و تحلیل" };
  }
}

export default async function ArticlePage({ params }: Props) {
  try {
    const { slug } = await params;
    const article = await api<ArticleDetail>(`/articles/${slug}`);
    const url = `${siteUrl()}/insights/${article.slug}`;
    return (
      <>
        <PageHero title={article.title} lead={article.excerpt} />
        <article className="shell section-pad max-w-3xl">
          <p className="text-sm text-muted">
            {article.published_at_jalali} · {article.author_name}
            {article.category ? ` · ${article.category.name}` : ""}
          </p>
          <div className="mt-4"><ShareBar url={url} title={article.title} /></div>
          <div className="mt-8 border-t border-line pt-8"><RichText html={article.body} /></div>
          {article.related.length > 0 && (
            <aside className="mt-12 border-t border-line pt-8">
              <p className="text-[0.72rem] tracking-[0.18em] text-gold-deep">ادامه مطالعه</p>
              <h2 className="mt-3 font-bold text-navy">مطالب مرتبط</h2>
              <ul className="mt-4 space-y-0 border-t border-line">
                {article.related.map((item) => (
                  <li key={item.slug} className="border-b border-line py-4 text-sm">
                    <Link href={`/insights/${item.slug}`} className="text-navy hover:text-teal">{item.title}</Link>
                  </li>
                ))}
              </ul>
            </aside>
          )}
        </article>
        <JsonLd data={{
          "@context": "https://schema.org",
          "@type": "Article",
          headline: article.title,
          datePublished: article.published_at ?? undefined,
          author: { "@type": "Organization", name: article.author_name },
          mainEntityOfPage: url,
        }} />
      </>
    );
  } catch (error) {
    if (error instanceof ApiDown) return <Unavailable />;
    throw error;
  }
}
