<template>
  <transition name="fade">
    <div class="back-to-top" @click="handleClick" v-show="showHandle">
      <div class="handler"></div>
    </div>
  </transition>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from '@vue/composition-api';
import { throttle } from 'lodash-es';
export default {
  name: 'BackToTop',
  setup() {
    const scrollTop = ref(0);
    const showHandle = computed(() => {
      return scrollTop.value >= 500;
    });
    const handleScroll = throttle(() => {
      scrollTop.value = document.documentElement.scrollTop;
    }, 100);

    const handleClick = () => {
      window.scrollTo({
        left: 0,
        top: 0,
        behavior: 'smooth',
      });
    };

    onMounted(() => {
      document.addEventListener('scroll', handleScroll);
    });

    onUnmounted(() => {
      document.removeEventListener('scroll', handleScroll);
    });

    return {
      showHandle,
      handleClick,
    };
  },
};
</script>

<style lang="stylus" scoped>
@import '~@theme/styles/_mixins.styl';

.back-to-top {
  position: fixed;
  left: 0;
  top: 0;
  z-index: 99;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  padding: space(2) 0;
  cursor: pointer;
}

.handler {
  width: 32px;
  height: 4px;
  backdrop-filter: blur(20px) saturate(125%);
  border-radius: 4px;
  background: rgba(#737f8c, 0.6);
}

.fade-enter, .fade-leave-to {
  opacity: 0;
  transition: opacity duration(3);
}
</style>
