import { shallowRef, ref, onMounted, watch, computed } from 'vue';
import { useThrottleFn, useEventListener } from '@vueuse/core';
import PopupManager from '../_util/popupManager';
import { noop } from '../_util/utils';

const useBackTop = (props, emit) => {
  const container = shallowRef(null);
  const visible = ref(false);
  let clearScrollListener = noop;
  const handleScroll = () => {
    if (container.value) {
      visible.value = container.value.scrollTop >= props.visibilityHeight;
    }
  };
  const handleClick = event => {
    var _container$value;
    (_container$value = container.value) === null || _container$value === void 0 || _container$value.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
    emit('click', event);
  };
  const handleScrollThrottled = useThrottleFn(handleScroll, 300, true);
  function init() {
    container.value = document.documentElement;
    if (props.target instanceof HTMLElement) {
      container.value = props.target;
    }
    clearScrollListener();
    if (container.value === document.documentElement) {
      clearScrollListener = useEventListener(document, 'scroll', handleScrollThrottled);
    } else {
      clearScrollListener = useEventListener(container.value, 'scroll', handleScrollThrottled);
    }

    // Give visible an initial value
    handleScroll();
  }
  onMounted(() => {
    init();
  });
  watch(() => props.target, () => {
    init();
  });
  const zIndex = ref(PopupManager.nextZIndex());
  watch(visible, () => {
    if (visible) {
      zIndex.value = PopupManager.nextZIndex();
    }
  });
  const backTopStyle = computed(() => ({
    right: `${props.right}px`,
    bottom: `${props.bottom}px`,
    zIndex: zIndex.value
  }));
  return {
    visible,
    handleClick,
    backTopStyle
  };
};

export { useBackTop };
