import { onMounted, onUnmounted, ref, watch, type Ref } from 'vue';

export function useBackToTop(
  scrollEl: Ref<HTMLElement | null>,
  options?: { threshold?: number },
) {
  const visible = ref(false);
  const threshold = options?.threshold ?? 320;

  function onScroll() {
    const el = scrollEl.value;
    visible.value = !!el && el.scrollTop > threshold;
  }

  function scrollToTop() {
    scrollEl.value?.scrollTo({ top: 0, behavior: 'smooth' });
  }

  function bind(el: HTMLElement | null) {
    el?.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
  }

  function unbind(el: HTMLElement | null) {
    el?.removeEventListener('scroll', onScroll);
  }

  onMounted(() => bind(scrollEl.value));

  onUnmounted(() => unbind(scrollEl.value));

  watch(scrollEl, (el, prev) => {
    unbind(prev);
    bind(el);
  });

  return { visible, scrollToTop, onScroll };
}
