import { ref, onMounted, onUnmounted } from 'vue'
import { throttle } from 'throttle-debounce'

export function useScrollThreshold(threshold = 250, delay = 150) {
    const isThresholdReached = ref(false)
    
    // 创建节流处理函数 (使用箭头函数保持this指向)
    const throttledHandler = throttle(delay, (scrollTop: number) => {
        const newState = scrollTop > threshold
        // 仅当状态变化时更新
        if (isThresholdReached.value !== newState) {
            isThresholdReached.value = newState
            console.log("阈值状态更新:", newState, "| 滚动位置:", scrollTop)
        }
    })

    const handleScroll = (e: any) => {
        // 传递滚动位置给节流函数
        throttledHandler(e.scrollTop)
    }

    onMounted(() => {
        uni.$on('page-scroll', handleScroll)
    })

    onUnmounted(() => {
        uni.$off('page-scroll', handleScroll)
        throttledHandler.cancel() // 清除节流函数残留任务
    })

    return isThresholdReached
}