/**
 * The article page (/articles/<slug>), also used by the admin preview. The design has
 * no article page, so it is built from the site's existing parts: the page hero, the
 * article cards and the text styles of the inner pages.
 *
 * The body is a list of blocks (paragraph, heading, list, quote, image), rendered one by
 * one; unknown block types are skipped. Paragraph text is plain: a blank line starts a
 * new paragraph.
 */
import Link from "next/link";
import { Fragment } from "react";
import { BTN_OUTLINE, PageHero } from "@/app/(site)/_components/pages/blocks";
import { paragraphs } from "@/app/(site)/_components/pages/parts";
import { ARTICLES_PAGE, articleDate, categoryHref, type ArticleBlock, type ArticlePageData } from "@/app/(site)/_lib/articles";
import { ArticleCardItem } from "./ArticleCardItem";

const P = "text-[15px] leading-[1.8] text-[#2E2E2E] whitespace-pre-line";

function Block({ b }: { b: ArticleBlock }) {
  switch (b.type) {
    case "paragraph":
      return (
        <>
          {paragraphs(b.text).map((p, i) => (
            <p key={i} className={`mt-5 ${P}`}>
              {p}
            </p>
          ))}
        </>
      );
    case "heading":
      return b.level === 3 ? (
        <h3 className="mt-8 text-[18px] font-bold text-ink leading-snug">{b.text}</h3>
      ) : (
        <h2 className="mt-10 text-[clamp(20px,2.4vw,26px)] font-black text-ink leading-tight tracking-[-0.01em]">{b.text}</h2>
      );
    case "list": {
      const items = (b.items ?? []).map((it, i) => (
        <li key={i} className="pl-1">
          {it}
        </li>
      ));
      const cls = "mt-5 pl-6 space-y-2 text-[15px] leading-[1.75] text-[#2E2E2E] marker:text-[#0056D2]";
      return b.style === "numbered" ? <ol className={`list-decimal ${cls}`}>{items}</ol> : <ul className={`list-disc ${cls}`}>{items}</ul>;
    }
    case "quote":
      return (
        <figure className="mt-8 border-l-4 border-[#0056D2] bg-[#F4F6F8] rounded-r-[6px] px-6 py-5">
          <blockquote className="text-[17px] leading-[1.6] font-semibold text-ink whitespace-pre-line">{`“${b.text}”`}</blockquote>
          {b.source && <figcaption className="mt-2 text-[13px] text-[#4A4A4A]">{`— ${b.source}`}</figcaption>}
        </figure>
      );
    case "image":
      return b.url ? (
        <figure className="mt-8">
          <img src={b.url} alt={b.alt ?? ""} className="w-full h-auto block rounded-[6px]" loading="lazy" />
          {b.caption && <figcaption className="mt-2 text-[13px] leading-[1.5] text-[#4A4A4A] text-center">{b.caption}</figcaption>}
        </figure>
      ) : null;
    default:
      return null;
  }
}

export function ArticleView({ a }: { a: ArticlePageData }) {
  const date = articleDate(a.publishedAt);
  const related = a.related ?? [];
  const meta = [
    date && (
      <time key="d" dateTime={a.publishedAt ?? undefined}>
        {date}
      </time>
    ),
    a.readingMinutes > 0 && <span key="r">{`${a.readingMinutes} min read`}</span>,
  ].filter(Boolean);
  return (
    <>
      <PageHero c={{ title: a.title, breadcrumb: a.title }} parents={[{ label: "Thought Leadership & Articles", href: ARTICLES_PAGE }]} wrap />
      <article className="bg-white py-12 md:py-16">
        <div className="w-full max-w-[820px] mx-auto px-6">
          <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[13px] text-[#4A4A4A]">
            <Link href={categoryHref(a.category.slug)} className="article-card-category !mb-0">
              {a.category.name}
            </Link>
            {meta.map((m, i) => (
              <Fragment key={i}>
                <span aria-hidden="true" className="text-[#c3cad5]">
                  •
                </span>
                {m}
              </Fragment>
            ))}
          </div>
          {a.author?.name && (
            <p className="mt-2 text-[14px] text-[#2E2E2E]">
              By <b className="font-semibold text-ink">{a.author.name}</b>
              {a.author.role && <span className="text-[#4A4A4A]">{`, ${a.author.role}`}</span>}
            </p>
          )}
          <p className="mt-5 text-[17px] leading-[1.7] font-medium text-ink">{a.excerpt}</p>
          {a.coverImage?.url && (
            <figure className="mt-8 rounded-[12px] overflow-hidden">
              <img src={a.coverImage.url} alt={a.coverImage.alt ?? ""} className="w-full aspect-[16/9] h-auto block object-cover" width="1280" height="720" />
            </figure>
          )}
          <div className="mt-3">
            {(a.body ?? []).map((b, i) => (
              <Block key={i} b={b} />
            ))}
          </div>
          <div className="mt-12 pt-8 border-t border-[#e2e8f0]">
            <Link href={ARTICLES_PAGE} className={BTN_OUTLINE}>
              All Articles
            </Link>
          </div>
        </div>
      </article>
      {related.length > 0 && (
        <section className="articles-section !pt-4" aria-labelledby="related-articles-heading">
          <div className="w-full max-w-[1180px] mx-auto px-6">
            <h2 id="related-articles-heading" className="text-[clamp(20px,2.5vw,26px)] font-black text-ink leading-tight mb-6">
              Related Articles
            </h2>
            <div className="articles-grid">
              {related.map((r) => (
                <ArticleCardItem key={r.slug} a={r} />
              ))}
            </div>
          </div>
        </section>
      )}
    </>
  );
}
