<template>
  <transition name="fade">
    <div v-show="visible"
         class="back-to-top"
         @click="scrollToTop"
         :style="{ bottom: offset + 'px', right: offset + 'px' }">
      <i class="fas fa-arrow-up"></i>
    </div>
  </transition>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'

export default {
  name: 'BackToTop',
  props: {
    visibilityHeight: {
      type: Number,
      default: 400
    },
    offset: {
      type: Number,
      default: 30
    }
  },

  setup(props) {
    const visible = ref(false)
    
    const checkScroll = () => {
      visible.value = window.pageYOffset > props.visibilityHeight
    }

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

    // 添加滚动监听
    onMounted(() => {
      window.addEventListener('scroll', checkScroll)
    })

    // 移除滚动监听
    onUnmounted(() => {
      window.removeEventListener('scroll', checkScroll)
    })

    return {
      visible,
      scrollToTop
    }
  }
}
</script>

<style scoped>
.back-to-top {
  position: fixed;
  background-color: #fff;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  cursor: pointer;
  transition: all 0.3s;
  z-index: 1000;
}

.back-to-top:hover {
  background-color: #f5f5f5;
  transform: translateY(-2px);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
