import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ARTICLES, getArticle, type ArticleBlock } from "@/lib/articles";
import { SITE, PERSON } from "@/lib/site";
import ArticleShell from "@/components/ArticleShell";

type Params = { params: Promise<{ slug: string }> };

export function generateStaticParams() {
  return ARTICLES.map((a) => ({ slug: a.slug }));
}

export async function generateMetadata({ params }: Params): Promise<Metadata> {
  const { slug } = await params;
  const a = getArticle(slug);
  if (!a) return {};
  return {
    title: a.title,
    description: a.dek,
    alternates: { canonical: `/journal/${a.slug}` },
    openGraph: {
      type: "article",
      title: a.title,
      description: a.dek,
      publishedTime: a.date,
      authors: [SITE.url],
      images: [{ url: a.cover }],
    },
  };
}

function Block({ block }: { block: ArticleBlock }) {
  switch (block.type) {
    case "h2":
      return <h2>{block.text}</h2>;
    case "quote":
      return <blockquote>{block.text}</blockquote>;
    case "ul":
      return (
        <ul>
          {block.items.map((it) => (
            <li key={it}>{it}</li>
          ))}
        </ul>
      );
    default:
      return <p>{block.text}</p>;
  }
}

export default async function ArticlePage({ params }: Params) {
  const { slug } = await params;
  const article = getArticle(slug);
  if (!article) notFound();

  const idx = ARTICLES.findIndex((a) => a.slug === slug);
  const prev = ARTICLES[idx - 1];
  const next = ARTICLES[idx + 1];

  const jsonLd = {
    "@context": "https://schema.org",
    "@graph": [
      {
        "@type": "Article",
        headline: article.title,
        description: article.dek,
        image: `${SITE.url}${article.cover}`,
        datePublished: article.date,
        dateModified: article.date,
        inLanguage: "en-ZA",
        mainEntityOfPage: `${SITE.url}/journal/${article.slug}`,
        author: {
          "@type": "Person",
          "@id": `${SITE.url}/#damian`,
          name: PERSON.name,
          url: SITE.url,
        },
        publisher: { "@id": `${SITE.url}/#damian` },
        articleSection: article.category,
      },
      {
        "@type": "BreadcrumbList",
        itemListElement: [
          { "@type": "ListItem", position: 1, name: "Home", item: SITE.url },
          { "@type": "ListItem", position: 2, name: "The Journal", item: `${SITE.url}/journal` },
          { "@type": "ListItem", position: 3, name: article.title, item: `${SITE.url}/journal/${article.slug}` },
        ],
      },
      {
        "@type": "FAQPage",
        mainEntity: article.faq.map((f) => ({
          "@type": "Question",
          name: f.q,
          acceptedAnswer: { "@type": "Answer", text: f.a },
        })),
      },
    ],
  };

  return (
    <ArticleShell>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />
      <nav className="font-mono text-[0.6rem] uppercase tracking-[0.26em] text-warmgrey" aria-label="Breadcrumb">
        <Link href="/" className="hover:text-gold">Home</Link>
        <span aria-hidden> / </span>
        <Link href="/journal" className="hover:text-gold">The Journal</Link>
      </nav>

      <div className="mt-8 flex flex-wrap items-center gap-3 font-mono text-[0.62rem] uppercase tracking-[0.24em] text-warmgrey">
        <span className="text-gold">{article.category}</span>
        <span aria-hidden>·</span>
        <time dateTime={article.date}>
          {new Date(article.date).toLocaleDateString("en-ZA", {
            year: "numeric",
            month: "long",
            day: "numeric",
          })}
        </time>
        <span aria-hidden>·</span>
        <span>{article.readTime}</span>
      </div>

      <h1
        className="font-display mt-6 text-4xl font-black leading-[1.06] tracking-[-0.02em] md:text-6xl"
        style={{ color: "inherit" }}
      >
        {article.title}
      </h1>

      <p className="font-editorial mt-7 text-2xl italic leading-snug opacity-80">
        {article.dek}
      </p>

      <div className="mt-10 overflow-hidden">
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          src={article.cover}
          alt={article.coverAlt}
          className="aspect-[21/9] w-full object-cover"
          fetchPriority="high"
        />
      </div>

      <div className="prose-dm mt-12">
        {article.blocks.map((b, i) => (
          <Block key={i} block={b} />
        ))}
      </div>

      {/* FAQ — GEO-critical structure */}
      <section className="mt-16 border-t border-current/10 pt-10" aria-label="Frequently asked questions">
        <h2 className="kicker">Questions people ask</h2>
        <dl className="mt-6 space-y-7">
          {article.faq.map((f) => (
            <div key={f.q}>
              <dt className="font-display text-lg font-bold leading-snug">{f.q}</dt>
              <dd className="mt-2 text-[0.95rem] leading-relaxed opacity-75">{f.a}</dd>
            </div>
          ))}
        </dl>
      </section>

      {/* Sources */}
      <section className="mt-14 border-t border-current/10 pt-8">
        <h2 className="kicker">Sources &amp; further reading</h2>
        <ul className="mt-4 space-y-2 text-[0.85rem]">
          {article.sources.map((s) => (
            <li key={s.url}>
              <a
                href={s.url}
                target="_blank"
                rel="noopener noreferrer"
                className="text-gold underline underline-offset-4"
              >
                {s.label}
              </a>
            </li>
          ))}
        </ul>
      </section>

      {/* Byline — entity-first for AI engines */}
      <p className="mt-14 border-l-2 border-gold pl-5 text-[0.85rem] leading-relaxed opacity-70">
        Damian Michael is the Managing Director &amp; CEO of Innovo Networks (Pty)
        Ltd, a Cape Town-headquartered ICT company serving SMEs and government
        across South Africa and Kenya. He writes about connectivity, cloud,
        cybersecurity and practical AI.{" "}
        <Link href="/about" className="text-gold underline underline-offset-4">
          About Damian →
        </Link>
      </p>

      {/* Prev / next */}
      <nav className="mt-16 grid gap-6 border-t border-current/10 pt-10 sm:grid-cols-2" aria-label="More essays">
        {prev ? (
          <Link href={`/journal/${prev.slug}`} className="group">
            <span className="kicker">← Previous</span>
            <span className="font-display mt-2 block text-lg font-bold leading-snug group-hover:text-gold">
              {prev.title}
            </span>
          </Link>
        ) : <span />}
        {next && (
          <Link href={`/journal/${next.slug}`} className="group text-right">
            <span className="kicker">Next →</span>
            <span className="font-display mt-2 block text-lg font-bold leading-snug group-hover:text-gold">
              {next.title}
            </span>
          </Link>
        )}
      </nav>
    </ArticleShell>
  );
}