export interface TocEntry {
  id: string;
  text: string;
  level: number;
}

function stripLeadingNumber(text: string): string {
  return text.replace(/^\d+[\.\)\s]\s*/, "");
}

function slugify(text: string): string {
  return text
    .toLowerCase()
    .replace(/[^a-z0-9\s-]/g, "")
    .replace(/\s+/g, "-")
    .replace(/-+/g, "-")
    .replace(/^-|-$/g, "");
}

export function processContent(html: string): { html: string; toc: TocEntry[] } {
  const toc: TocEntry[] = [];
  const counts: Record<string, number> = {};

  const modified = html.replace(/<h([23])(\s[^>]*)?>([\s\S]*?)<\/h\1>/gi, (match, level, attrs, text) => {
    const raw = text.replace(/<[^>]*>/g, "").trim();
    const clean = stripLeadingNumber(raw);
    let id = slugify(clean);
    if (!id) return match;

    if (counts[id] !== undefined) {
      counts[id]++;
      id = `${id}-${counts[id]}`;
    } else {
      counts[id] = 0;
    }

    toc.push({ id, text: clean, level: Number(level) });
    return `<h${level} id="${id}">${text}</h${level}>`;
  });

  return { html: modified, toc };
}
