<script setup>
import {
  ref,
  computed,
  onMounted,
  onBeforeUnmount,
} from "vue";
import { useI18n } from "#imports";

const { t } = useI18n();

const scrollTop = ref(0); // 监听滚动事件得到的值
const top = ref(300); // 超过这个值返回图标显示出来

// 返回顶部函数
const backToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: "smooth",
  });
};

// 计算属性，根据scrollTop和top值判断是否显示返回顶部按钮
const fadeShow = computed(() => {
  return scrollTop.value > top.value;
});

// 监听滚动事件
const handleScroll = () => {
  scrollTop.value = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
};

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

onBeforeUnmount(() => {
  window.removeEventListener('scroll', handleScroll);
});
</script>

<template>
  <div>
    <div v-if="fadeShow" class="contact">
      <div class="contact__drift">
        <a class="contact__drift__box" @click="backToTop">
          <img
            src="/static/back-top/back_top.png"
            :title="t('page.back-to-top')"
            :alt="t('page.back-to-top')"
          />
        </a>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.contact {
  position: fixed;
  text-align: center;
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  right: 25px;
  bottom: 105px;

  &__drift {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    cursor: pointer;
    font-size: 13px;
    color: #000;
    line-height: 2.5;

    &__box {
      display: block;
      width: 45px;
      height: 45px;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      color: #fff;
      color: #000;
      background: #ffffff;
      box-shadow: 0px 8px 20px rgba(0, 0, 0, 0.08);
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0px 12px 25px rgba(0, 0, 0, 0.15);
      }

      @media (max-width: 600px) {
        width: 45px;
        height: 45px;
      }

      img {
        width: 22px;
        height: 22px;

        @media (max-width: 600px) {
          width: 22px;
          height: 22px;
        }
      }
    }
  }
}
</style>
