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

export function extractHeadings(content: string): TocItem[] {
  const headings: TocItem[] = [];
  // Match ## Heading 2 or ### Heading 3
  const matches = content.matchAll(/^(#{2,3})\s+(.+)$/gm);

  for (const match of matches) {
    const level = match[1].length;
    // Remove markdown formatting from the heading text
    const text = match[2].replace(/[*_`[\]]/g, "").trim();
    // Generate an ID consistent with the one generated in mdx-components.tsx
    const id = text
      .toLowerCase()
      .replace(/[^a-z0-9\s-]/g, "")
      .replace(/\s+/g, "-")
      .replace(/-+/g, "-")
      .trim();

    headings.push({ id, text, level });
  }

  return headings;
}
