import { visit } from 'unist-util-visit'
import type { Element, Node, Parent } from 'hast'

function isElement(node: Node): node is Element {
  return node.type === 'element' && 'tagName' in node && typeof node.tagName === 'string'
}

export default function rehypeReferenceFormat() {
  return (tree: Node) => {
    visit(
      tree,
      (node: Node, index: number | undefined, parent: Parent | undefined) => {
        if (isElement(node) && node.tagName.toLowerCase() === 'reference') {
          if (parent && typeof index === 'number') {
            parent.children.splice(index, 1)
          }
        }
      },
    )
  }
}
