<template>
  <div
    v-show="showBackToTop"
    @click="scrollToTop"
    class="fixed right-5 bottom-5 bg-stone-800 hover:bg-stone-700 text-white w-10 h-10 rounded-full flex items-center justify-center cursor-pointer transition-all duration-300 z-50 shadow-lg"
    :aria-label="t('common.backToTop')"
  >
    <svg
      xmlns="http://www.w3.org/2000/svg"
      class="h-5 w-5"
      viewBox="0 0 20 20"
      fill="currentColor"
    >
      <path
        fill-rule="evenodd"
        d="M14.707 12.707a1 1 0 01-1.414 0L10 9.414l-3.293 3.293a1 1 0 01-1.414-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 010 1.414z"
        clip-rule="evenodd"
      />
    </svg>
  </div>
</template>

<script setup lang="ts">
/**
 * 返回顶部按钮组件
 * 当页面滚动超过一定距离时显示，点击后平滑滚动回顶部
 */
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
const showBackToTop = ref(false);
const scrollThreshold = 300; // 显示按钮的滚动阈值

/**
 * 监听滚动事件，控制按钮显示
 */
function checkScroll() {
  showBackToTop.value = window.scrollY > scrollThreshold;
}

/**
 * 滚动到页面顶部
 */
function scrollToTop() {
  window.scrollTo({
    top: 0,
    behavior: "smooth",
  });
}

// 生命周期钩子
onMounted(() => {
  window.addEventListener("scroll", checkScroll);
  checkScroll(); // 初始检查
});

onUnmounted(() => {
  window.removeEventListener("scroll", checkScroll);
});
</script>
