import { onMounted, onUnmounted, watch } from 'vue'

// Shared IntersectionObserver-on-a-sentinel infinite-scroll lifecycle.
// Pass a ref to the sentinel element and a callback to fire when it scrolls
// into view; the callback owns its own guard (e.g. `if (store.hasMore &&
// !store.loading) store.loadMore()`). Re-attaches if the sentinel ref
// changes (e.g. it's behind a v-if) and disconnects on unmount.
export function useInfiniteScroll (sentinelRef, onIntersect, { rootMargin = '600px' } = {}) {
  let observer = null

  function teardown () {
    if (observer) { observer.disconnect(); observer = null }
  }
  function attach () {
    teardown()
    if (!sentinelRef.value) return
    observer = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) onIntersect()
    }, { rootMargin })
    observer.observe(sentinelRef.value)
  }

  onMounted(attach)
  watch(sentinelRef, attach)
  onUnmounted(teardown)

  return { attach, teardown }
}
