<script setup>
import { onBeforeUnmount, onMounted, ref } from "vue";
import { Icon } from "@iconify/vue";

const visible = ref(false);
let onScroll = null;

function scrollToTop() {
  window.scrollTo({ top: 0, behavior: "smooth" });
}

onMounted(() => {
  if (typeof window === "undefined") return;
  onScroll = () => {
    visible.value = window.scrollY > 460;
  };
  window.addEventListener("scroll", onScroll, { passive: true });
  onScroll();
});

onBeforeUnmount(() => {
  if (!onScroll) return;
  window.removeEventListener("scroll", onScroll);
});
</script>

<template>
  <button
    v-show="visible"
    class="backTop"
    type="button"
    aria-label="返回顶部"
    @click="scrollToTop"
  >
    <!-- <Icon icon="mdi-light:home" style="color: #0951ad" /> -->
    <Icon icon="lucide:chevron-up" width="24" height="24" />
  </button>
</template>

<style scoped>
.backTop {
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  z-index: 60;
  right: 10px;
  bottom: 30%;
  width: 53px;
  height: 50px;
  border: none;
  background-color: #fff;
  box-shadow: var(--back-top);
  cursor: pointer;
  font-weight: 900;
  color: var(--slate-700);
  transition: 160ms ease;
}

.backTop:hover {
  transform: translateY(-2px);
  color: var(--brand-700);
}
</style>
