import {
    ref
} from 'vue'

export function useScrollDirection(options = {}) {
    const {
        threshold = 50, // 滚动偏移阈值，降低以更敏感
        throttleTime = 16, // 节流时间（毫秒），约60fps
        onChange = null, // 滚动方向变化的回调
        hideThreshold = 100, // 隐藏区域的滚动阈值
        enablePerformanceMode = true // 启用性能优化模式
    } = options

    const lastScrollTop = ref(0)
    const accumulatedScroll = ref(0)
    const isScrollingDown = ref(false)
    const shouldHideTop = ref(false) // 控制顶部区域隐藏
    const shouldStickyFilter = ref(false) // 控制筛选区域吸顶
    let lastInvoke = 0

    function handleScroll(e) {
        const now = Date.now()
        if (enablePerformanceMode && now - lastInvoke < throttleTime) return
        lastInvoke = now

        const scrollTop = e.detail.scrollTop
        const delta = scrollTop - lastScrollTop.value
        accumulatedScroll.value += delta

        // 控制顶部区域隐藏
        if (scrollTop > hideThreshold) {
            if (!shouldHideTop.value) {
                shouldHideTop.value = true
            }
        } else {
            if (shouldHideTop.value) {
                shouldHideTop.value = false
            }
        }

        // 控制筛选区域吸顶（当顶部区域隐藏时）
        if (scrollTop > hideThreshold + 50) { // 稍微延迟吸顶
            if (!shouldStickyFilter.value) {
                shouldStickyFilter.value = true
            }
        } else {
            if (shouldStickyFilter.value) {
                shouldStickyFilter.value = false
            }
        }

        // 滚动方向检测（仅在性能模式下使用阈值）
        if (!enablePerformanceMode || Math.abs(accumulatedScroll.value) > threshold) {
            if (accumulatedScroll.value > 0) {
                // 向下滚动
                if (!isScrollingDown.value) {
                    isScrollingDown.value = true
                    onChange?.(true) // 通知变更为向下
                }
            } else {
                // 向上滚动
                if (isScrollingDown.value) {
                    isScrollingDown.value = false
                    onChange?.(false) // 通知变更为向上
                }
            }
            if (enablePerformanceMode) {
                accumulatedScroll.value = 0
            }
        }

        lastScrollTop.value = scrollTop
    }

    return {
        isScrollingDown,
        shouldHideTop,
        shouldStickyFilter,
        handleScroll
    }
}