import GithubSlugger from "github-slugger";

/**
 * Single table-of-contents entry. Defined locally so `lib` does not depend on
 * `components` (the `Toc` component re-exports this same shape for its props).
 */
export type TocItem = { id: string; text: string; level: 2 | 3 };

/**
 * Extract h2/h3 headings from an MDX body, slugging ids the same way
 * rehype-slug does (GithubSlugger) so TOC anchors line up with the rendered
 * heading ids. Skips headings inside fenced code blocks.
 */
export function extractToc(body: string): TocItem[] {
  const slugger = new GithubSlugger();
  const items: TocItem[] = [];
  let inFence = false;

  for (const line of body.split("\n")) {
    // Toggle on either backtick (```) or tilde (~~~) fences so headings
    // inside code blocks of both styles are skipped.
    if (/^\s*(```|~~~)/.test(line)) {
      inFence = !inFence;
      continue;
    }
    if (inFence) continue;
    const m = /^(#{2,3})\s+(.+?)\s*#*\s*$/.exec(line);
    if (!m) continue;
    const level = m[1].length === 2 ? 2 : 3;
    // Strip inline markdown emphasis/code for the visible label.
    const text = m[2].replace(/[*_`]/g, "").trim();
    items.push({ id: slugger.slug(text), text, level });
  }
  return items;
}
