import onFind, { Selectors, CallbackFunction } from './onFind'

let calledIndex = 0

export default function onVisible<E extends Element>(
  selectors: Selectors,
  callback: CallbackFunction<E>,
) {
  const calledId = `_ovc${calledIndex++}`

  const observer = new IntersectionObserver((changes) => {
    for (const change of changes) {
      if (change.isIntersecting) {
        const element = change.target
        const elementClasses = element.classList

        if (!elementClasses.contains(calledId)) {
          elementClasses.add(calledId)
          observer.unobserve(element)
          callback(element as E)
        }
      }
    }
  })

  onFind(selectors, (element) => {
    observer.observe(element)
  })
}
