import { computed, isRef, watchEffect, ref } from 'vue'
import { throttle, isVisible } from '@/shared'
import type { Ref } from 'vue'

export type VisibleEl = Ref<HTMLElement | undefined | null> | HTMLElement

const getEl = (target: VisibleEl) => (isRef(target) ? target.value : target)

export type UseVisibleProps = {
  target: VisibleEl
  parent?: VisibleEl
  bound?: number
}
export const useVisible = ({ target, parent, bound = 0 }: UseVisibleProps) => {
  const visible = ref(true)
  const targetComputed = computed(() => getEl(target))
  const parentComputed = computed(() =>
    parent ? getEl(parent) : targetComputed.value?.parentElement
  )

  watchEffect(onCleanup => {
    if (!targetComputed.value || !parentComputed.value) {
      return
    }
    const parent = parentComputed.value
    const target = targetComputed.value
    const scrollHandler = throttle(() => {
      visible.value = isVisible({ parent, target, bound })
    }, 500)

    scrollHandler()
    parent.addEventListener('scroll', scrollHandler)

    onCleanup(() => {
      console.log('清除清除')
      parent.removeEventListener('scroll', scrollHandler)
    })
  })
  return visible
}
