export function useScrollReveal() {
  const observer = ref<IntersectionObserver | null>(null)

  function init() {
    if (typeof window === 'undefined') return

    observer.value = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            entry.target.classList.add('is-visible')
            observer.value?.unobserve(entry.target)
          }
        })
      },
      {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px',
      },
    )

    document.querySelectorAll('.scroll-reveal').forEach((el) => {
      observer.value?.observe(el)
    })
  }

  function destroy() {
    observer.value?.disconnect()
  }

  onMounted(() => {
    nextTick(() => init())
  })

  onUnmounted(() => {
    destroy()
  })

  return { init, destroy }
}
