/*// src/composables/useBodyScrollLock.js*/
import { watch, onUnmounted, onActivated, onDeactivated } from 'vue'

// 全局变量
let lockCount = 0
let scrollTop = 0 // 记录页面滚动到了哪里

export function useBodyScrollLock(visibleRef) {

  const lock = () => {
    lockCount++
    if (lockCount === 1) {
      // 1. 记住当前滚到了哪里
      scrollTop = window.scrollY || document.documentElement.scrollTop

      // 2. 把 body 变成 fixed，强制钉在当前位置
      // 这样浏览器想滚也滚不动了，物理锁死
      document.body.style.position = 'fixed'
      document.body.style.top = `-${scrollTop}px`
      document.body.style.width = '100%'
      document.body.style.overflow = 'hidden'
    }
  }

  const unlock = () => {
    if (lockCount > 0) lockCount--
    if (lockCount === 0) {
      // 3. 恢复原样
      document.body.style.position = ''
      document.body.style.top = ''
      document.body.style.width = ''
      document.body.style.overflow = ''

      // 4. 瞬间滚回刚才的位置（无缝衔接）
      window.scrollTo(0, scrollTop)
    }
  }

  // 监听变化
  watch(visibleRef, (val) => {
    if (val) lock()
    else unlock()
  }, { immediate: true })

  // 清理逻辑
  onUnmounted(() => {
    if (visibleRef.value) unlock()
  })

  onActivated(() => {
    if (visibleRef.value) lock()
  })

  onDeactivated(() => {
    if (visibleRef.value) unlock()
  })
}