import { onMounted, onBeforeUnmount } from 'vue'

/**
 * Watch for DOM changes on a target element and run a callback.
 *
 * @param {HTMLElement | null} targetElement - Element to monitor
 * @param {Function} callback - Function to run on mutations
 */
export function useMutationObserver(targetElement, callback) {
  let observer = null

  onMounted(() => {
    if (!targetElement) return

    observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.type === 'childList') {
          callback()
        }
      })
    })

    observer.observe(targetElement, { childList: true, subtree: true })
  })

  onBeforeUnmount(() => {
    if (observer) observer.disconnect()
  })
}
