import { onUnmounted, nextTick } from 'vue'

export function useScrollAnimation() {
  let observer: IntersectionObserver | null = null

  const initObserver = async () => {
    // Wait for DOM updates
    await nextTick()
    
    // Disconnect existing observer if any
    if (observer) {
      observer.disconnect()
    }

    observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          entry.target.classList.add('visible')
          // Optional: Stop observing once visible
          // observer?.unobserve(entry.target)
        }
      })
    }, { 
      threshold: 0.1,
      rootMargin: '50px' // Pre-load slightly before element comes into view
    })
    
    const elements = document.querySelectorAll('.animate-slide-down, .animate-reveal')
    if (elements.length === 0) {
      // Retry once if no elements found (e.g. data loaded but DOM not quite ready)
      setTimeout(() => {
        document.querySelectorAll('.animate-slide-down, .animate-reveal').forEach(el => {
          observer?.observe(el)
        })
      }, 100)
    } else {
      elements.forEach(el => {
        observer?.observe(el)
      })
    }
  }

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

  return {
    initObserver
  }
}
