/**
 * Server-side markdown renderer for article bodies.
 *
 * - GFM enabled (tables, strikethrough, autolinks)
 * - heading IDs added so the table-of-contents component can scroll to anchors
 * - assumes content comes from trusted admin/API sources, so HTML passthrough
 *   is allowed; if you want to harden this, swap in DOMPurify-server or
 *   `marked-purify`.
 */
import { Marked } from "marked";

const marked = new Marked({
  gfm: true,
  breaks: false,
  pedantic: false,
});

// Slugify-ish for heading IDs (Vietnamese-friendly).
function slugifyId(text: string): string {
  return text
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/đ/g, "d")
    .replace(/Đ/g, "D")
    .toLowerCase()
    .replace(/[^a-z0-9\s-]/g, "")
    .trim()
    .replace(/\s+/g, "-")
    .replace(/-+/g, "-");
}

marked.use({
  renderer: {
    heading({ tokens, depth }) {
      const text = this.parser.parseInline(tokens);
      const raw = tokens.map((t) => ("raw" in t ? t.raw : "")).join("");
      const id = slugifyId(raw);
      return `<h${depth} id="${id}">${text}</h${depth}>\n`;
    },
  },
});

export function renderMarkdown(md: string): string {
  if (!md) return "";
  return marked.parse(md, { async: false }) as string;
}
