import type { Selectors } from './onFind'

export default function onFindOnce(selectors: Selectors, callback: () => void) {
  if (Array.isArray(selectors)) {
    selectors = selectors.join(',')
  }

  if (document.querySelector(selectors)) {
    callback()
    return
  }

  let called = false

  const observer = new MutationObserver(async () => {
    if (document.querySelector(selectors as string)) {
      observer.disconnect()

      if (!called) {
        called = true
        callback()
      }
    }
  })

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