import Taro, { usePageScroll } from '@tarojs/taro'
import { computed, ref, watch } from 'vue'

const lockedPickerCount = ref(0)
const lockedRootBaseStyle = 'position: fixed; right: 0; left: 0; width: 100%; height: 100vh; overflow: hidden;'
const isThemePickerPageLocked = computed(() => lockedPickerCount.value > 0)

export function lockThemePickerPageScroll() {
  lockedPickerCount.value += 1
}

export function unlockThemePickerPageScroll() {
  lockedPickerCount.value = Math.max(lockedPickerCount.value - 1, 0)
}

export function useThemePickerLockedRootStyle() {
  const scrollTop = ref(0)
  usePageScroll(event => {
    if (!isThemePickerPageLocked.value) scrollTop.value = event.scrollTop
  })
  watch(isThemePickerPageLocked, isLocked => {
    if (!isLocked) Taro.pageScrollTo({ scrollTop: scrollTop.value, duration: 0 })
  }, { flush: 'post' })
  return computed(() => isThemePickerPageLocked.value ? `${lockedRootBaseStyle} top: -${scrollTop.value}px;` : '')
}
