import { type Locale, useTranslations } from "next-intl";
import Image from "next/image";
import { type ReactNode, Suspense } from "react";

import BlogSubNav from "@/components/blog/BlogSubNav";
import ArrowLink from "@/components/ui/ArrowLink";
import Rule from "@/components/ui/Rule";
import ExploredBadge from "@/components/blog/ExploredBadge";
import HeaderAutoHide from "@/components/header/HeaderAutoHide";
import JrPostCard from "@/components/blog/JrPostCard";
import ReadingProgress from "@/components/blog/ReadingProgress";
import ShareButtons from "@/components/blog/ShareButtons";
import TocScrollspy from "@/components/blog/TocScrollspy";
import { buttonVariants } from "@/components/ui/button";
import { BLOG_AUTHORS } from "@/config/blog/authors";
import { categorySlug } from "@/config/blog/categories";
import { site } from "@/config/site";
import { Link } from "@/i18n/navigation";
import { articlePath, getAllPosts } from "@/lib/blog";
import type { Post, PostMeta } from "@/lib/blog/schema";
import { extractHeadings } from "@/lib/blog/toc";
import { cn } from "@/lib/utils";

export default function PostLayout({
  post,
  related,
  children,
}: {
  post: Post;
  related: PostMeta[];
  children: ReactNode;
}) {
  const t = useTranslations("BlogPage");
  const ta = useTranslations("BlogPage.article");
  const locale = post.locale as Locale;
  const authorId = post.author as keyof typeof BLOG_AUTHORS;
  const author = BLOG_AUTHORS[authorId];
  const categoryLabel = t(`categories.${post.category}`);
  const dateFmt = new Intl.DateTimeFormat(locale, { dateStyle: "long" }).format(
    new Date(post.date),
  );
  const headings = extractHeadings(post.body);
  const shareUrl = `${site.url}${articlePath(locale, post.category, post.slug)}`;
  const topThree = related.slice(0, 3);
  const searchIndex = getAllPosts(locale).map((p) => ({
    title: p.title,
    category: p.category,
    slug: p.slug,
    cover: p.cover,
  }));

  return (
    <>
      <HeaderAutoHide />
      <ReadingProgress />
      {/* Clearance for the fixed site header (75px mobile / 90px desktop). */}
      <div aria-hidden="true" className="h-[75px] lg:h-[90px]" />
      <Suspense>
        <BlogSubNav activeCategory={post.category} searchIndex={searchIndex} />
      </Suspense>

      <article className="bg-background pb-8">
        {/* HERO */}
        <header className="mx-auto max-w-[860px] px-6 pt-12 text-center lg:pt-16">
          <div className="mb-6 flex flex-wrap items-center justify-center gap-3">
            <Link
              href="/blog"
              className="text-[10.5px] font-semibold uppercase tracking-[0.2em] text-brushed-steel transition-colors hover:text-gold-text"
            >
              {t("indexTitle")}
            </Link>
            <span aria-hidden="true" className="text-brushed-steel">
              /
            </span>
            <span className="border border-gold-bright/40 px-2 py-1 text-[9.5px] font-semibold uppercase tracking-[0.16em] text-gold-text">
              {categoryLabel}
            </span>
          </div>
          <p className="text-[11.5px] font-semibold uppercase tracking-[0.18em] text-on-surface-variant">
            {dateFmt} · {ta("minRead", { minutes: String(post.readingMinutes) })}
          </p>
          <h1 className="mt-5 font-display text-[32px] font-normal leading-[1.15] text-foreground lg:text-[clamp(32px,4.2vw,50px)]">
            {post.title}
          </h1>
          <div className="mt-6 inline-flex items-center gap-3">
            <Image
              src={author.avatar}
              alt=""
              width={38}
              height={38}
              className="size-[38px] rounded-full object-cover"
            />
            <span className="text-[13px] text-on-surface-variant">
              {t("byAuthor", { author: author.name })}
            </span>
          </div>
        </header>

        {/* COVER */}
        <div className="mx-auto mt-10 max-w-[1160px] px-6 lg:mt-12 lg:px-0">
          <div className="relative h-[280px] overflow-hidden lg:h-[480px]">
            <Image
              src={post.cover}
              alt={post.coverAlt}
              fill
              priority
              sizes="(min-width:1024px) 1160px, 100vw"
              className="object-cover"
            />
          </div>
        </div>

        {/* THREE-COLUMN LAYOUT */}
        <div className="mx-auto mt-12 max-w-[1340px] px-6 lg:mt-16 lg:grid lg:grid-cols-[250px_minmax(0,1fr)_280px] lg:items-start lg:gap-16 lg:px-16">
          {/* LEFT — TOC + Share (sticky on desktop) */}
          <aside className="mb-12 lg:sticky lg:top-[120px] lg:mb-0">
            {headings.length > 0 && <TocScrollspy headings={headings} label={ta("toc")} />}
            <p className="mt-10 mb-4 text-[11px] font-semibold uppercase tracking-[0.2em] text-gold-text">
              {ta("share")}
            </p>
            <ShareButtons url={shareUrl} title={post.title} />
          </aside>

          {/* CENTER — article body + author box + explored badge */}
          <div className="min-w-0">
            <div id="article-body" className="mx-auto max-w-[680px]">
              {/* `prose` (@tailwindcss/typography) habille le HTML issu du MDX.
                  Il n'enveloppe QUE `children` : l'encart auteur et le badge
                  ci-dessous sont des freres, et heriteraient sinon des styles
                  de flux (p, a, strong…). Les modificateurs alignent le plugin
                  sur la charte (docs/brand.md) : titres en `font-display`
                  (Tenor Sans) sans graisse, liens or sans soulignement
                  permanent, coins vifs, filet de citation en or.
                  `max-w-lead` neutralise le `max-width: 65ch` de `prose`
                  (~520px ici) pour conserver la colonne de 680px du parent.
                  `text-inverse-surface` reprend la main sur la couleur de corps
                  du plugin (gris bleute #374151, hors charte) : posee sur le
                  conteneur, elle descend par heritage sur `p` et `li`. */}
              <div className="prose max-w-lead text-inverse-surface prose-blockquote:text-on-surface-variant prose-headings:font-display prose-headings:font-normal prose-headings:text-foreground prose-a:text-gold-text prose-a:no-underline hover:prose-a:underline prose-strong:text-foreground prose-blockquote:border-gold prose-blockquote:font-normal prose-img:rounded-none prose-hr:border-hairline">
                {children}
              </div>

              <div className="mt-14 flex items-start gap-5 border border-hairline bg-surface-container-low p-7">
                <Image
                  src={author.avatar}
                  alt=""
                  width={52}
                  height={52}
                  className="size-[52px] shrink-0 rounded-full object-cover"
                />
                <div>
                  <p className="font-display text-[19px] text-foreground">{author.name}</p>
                  <p className="mt-0.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-gold-text">
                    {t(`authors.${authorId}.role`)}
                  </p>
                  <p className="mt-2 text-[13.5px] leading-[1.6] text-on-surface-variant">
                    {t(`authors.${authorId}.bio`)}
                  </p>
                </div>
              </div>

              <ExploredBadge />
            </div>
          </div>

          {/* RIGHT — CTA + Related Reading (sticky on desktop) */}
          <aside className="mt-12 lg:sticky lg:top-[120px] lg:mt-0">
            <div className="bg-foreground p-8">
              <Rule size="lg" className="mb-5" />
              <h3 className="font-display text-[22px] text-white">{ta("cta.title")}</h3>
              <p className="mt-3 text-[13.5px] leading-[1.6] text-white/[.72]">{ta("cta.body")}</p>
              <Link
                href="/contact-us"
                className={cn(buttonVariants({ variant: "cta-inverse", size: "cta-sm" }), "mt-6")}
              >
                {ta("cta.button")}
              </Link>
            </div>

            {topThree.length > 0 && (
              <div className="mt-6 border border-hairline bg-surface-container-low p-7">
                <p className="text-[11px] font-semibold uppercase tracking-[0.2em] text-gold-text">
                  {ta("relatedReading")}
                </p>
                <ul className="mt-2">
                  {topThree.map((p) => (
                    <li
                      key={p.postId}
                      className="border-t border-hairline-soft py-2.5 first:border-t-0"
                    >
                      <Link
                        href={{
                          pathname: "/[category]/[slug]",
                          params: { category: categorySlug(p.category, locale), slug: p.slug },
                        }}
                        className="font-display text-[15.5px] leading-snug text-foreground transition-colors hover:text-gold-text"
                      >
                        {p.title}
                      </Link>
                    </li>
                  ))}
                </ul>
              </div>
            )}
          </aside>
        </div>
      </article>

      {/* KEEP READING */}
      {topThree.length > 0 && (
        <section className="border-t border-hairline bg-surface-container-low">
          <div className="mx-auto max-w-[1340px] px-6 py-[76px] lg:px-16 lg:py-[104px]">
            <div className="mb-10 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
              <h2 className="font-display text-[31px] font-normal leading-[1.18] text-foreground lg:text-[38px]">
                {ta("keepReading")}
              </h2>
              <ArrowLink href="/blog">{ta("backToJournal")}</ArrowLink>
            </div>
            <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
              {topThree.map((p) => (
                <JrPostCard
                  key={p.postId}
                  post={p}
                  locale={locale}
                  variant="standard"
                  showExcerpt={false}
                />
              ))}
            </div>
          </div>
        </section>
      )}
    </>
  );
}
