// Helpers de présentation pour les articles de blog WP (corps HTML éditeur classique).
import { mapImage } from "@/lib/wp/mappers";
import { sanitizeWpHtml } from "@/lib/sanitizeHtml";
import type { WpImage } from "@/lib/wp/types";
import type { WpPostCard } from "@/lib/wp/queries/post";

export interface TocEntry {
  id: string;
  title: string;
}

/** slug d'ancre stable depuis un titre (accents retirés). */
export function slugifyHeading(text: string): string {
  return text
    .normalize("NFD")
    .replace(/[̀-ͯ]/g, "")
    .toLowerCase()
    .replace(/<[^>]+>/g, "")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, 60) || "section";
}

/**
 * Prépare le corps d'article : ajoute des id d'ancre aux <h2>, construit le
 * sommaire (TOC), estime le temps de lecture. Le HTML vient de l'éditeur
 * classique WP (already trusted, généré par notre pipeline).
 */
export function processArticleContent(html: string | null | undefined): {
  html: string;
  toc: TocEntry[];
  readTime: string;
} {
  const source = html ?? "";
  const toc: TocEntry[] = [];
  const used = new Set<string>();

  const withIds = source.replace(/<h2(\s[^>]*)?>([\s\S]*?)<\/h2>/g, (_m, attrs, inner) => {
    const title = inner.replace(/<[^>]+>/g, "").trim();
    let id = slugifyHeading(title);
    let n = 2;
    while (used.has(id)) id = `${slugifyHeading(title)}-${n++}`;
    used.add(id);
    toc.push({ id, title });
    return `<h2 id="${id}"${attrs ?? ""}>${inner}</h2>`;
  });

  const words = source.replace(/<[^>]+>/g, " ").split(/\s+/).filter(Boolean).length;
  const readTime = `${Math.max(1, Math.round(words / 200))} min`;

  return { html: sanitizeWpHtml(withIds), toc, readTime };
}

const FR_DATE = new Intl.DateTimeFormat("fr-FR", { day: "numeric", month: "short", year: "numeric" });

/** Date ISO WP → "28 déc. 2024". */
export function formatFrDate(iso: string | null | undefined): string {
  if (!iso) return "";
  const d = new Date(iso);
  return Number.isNaN(d.getTime()) ? "" : FR_DATE.format(d);
}

export interface BlogCard {
  title: string;
  href: string;
  category: string;
  date: string;
  image: WpImage | null;
}

const FALLBACK_IMAGE: WpImage = {
  sourceUrl: "/images/prime-cee/revetement-reflectif-toiture.jpg",
  altText: "",
  width: null,
  height: null,
};

/** WP post card → props de carte article (liste, home, related). */
export function toBlogCard(p: WpPostCard): BlogCard {
  return {
    title: p.title ?? "",
    href: `/blog/${p.slug}`,
    category: p.categories?.nodes?.[0]?.name ?? "Ressources",
    date: formatFrDate(p.date),
    image: mapImage(p.featuredImage) ?? FALLBACK_IMAGE,
  };
}

export { FALLBACK_IMAGE };
