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

export function useContainerScroll(containerRef, options = {}) {
  const {
    scrollThreshold = 0,
    showOnScrollDown = true,
    hideOnTop = true,
    useAnimationFrame = true
  } = options

  const isShow = ref(false)
  const lastScrollTop = ref(0)
  const ticking = ref(false)

  const updateShowState = () => {
    const container = containerRef.value
    if (!container) return
    
    const currentScrollTop = container.scrollTop
    
    if (showOnScrollDown && currentScrollTop > lastScrollTop.value && currentScrollTop > scrollThreshold) {
      isShow.value = true
    }
    
    if (hideOnTop && currentScrollTop === 0) {
      isShow.value = false
    }
    
    lastScrollTop.value = currentScrollTop
    ticking.value = false

  }

  const handleScroll = () => {
    if (useAnimationFrame) {
      if (!ticking.value) {
        requestAnimationFrame(updateShowState)
        ticking.value = true
      }
    } else {
      updateShowState()
    }
  }

  onMounted(() => {
    console.log('containerRef', containerRef)
    const container = containerRef.value
    if (container) {
      container.addEventListener('scroll', handleScroll, { passive: true })
    }
  })

  onUnmounted(() => {
    const container = containerRef.value
    if (container) {
      container.removeEventListener('scroll', handleScroll)
    }
  })

  return {
    isShow
  }
}