<template>
  <Transition
    enter-active-class="transition-all duration-300 ease-out"
    enter-from-class="translate-y-4 opacity-0"
    leave-active-class="transition-all duration-200 ease-in"
    leave-to-class="translate-y-4 opacity-0"
  >
    <button
      v-if="isVisible"
      class="fixed z-40 w-11 h-11 flex items-center justify-center rounded-full shadow-lg transition-all duration-300 hover:scale-110"
      :class="[positionClasses, variantClasses]"
      :aria-label="label"
      @click="scrollToTop"
    >
      <UIcon :name="icon" class="w-5 h-5" />
    </button>
  </Transition>
</template>

<script setup>
const props = defineProps({
  /** Scroll threshold before showing button */
  threshold: {
    type: Number,
    default: 400,
  },
  /** Button position */
  position: {
    type: String,
    default: 'bottom-right',
    validator: (v) => ['bottom-right', 'bottom-left', 'bottom-center'].includes(v),
  },
  /** Style variant */
  variant: {
    type: String,
    default: 'primary',
    validator: (v) => ['primary', 'neutral', 'glass'].includes(v),
  },
  /** Icon name */
  icon: {
    type: String,
    default: 'i-lucide-arrow-up',
  },
  /** Aria label */
  label: {
    type: String,
    default: 'Back to top',
  },
  /** Smooth scroll behavior */
  smooth: {
    type: Boolean,
    default: true,
  },
});

const isVisible = ref(false);

const positionClasses = computed(() => {
  const positions = {
    'bottom-right': 'bottom-6 right-6',
    'bottom-left': 'bottom-6 left-6',
    'bottom-center': 'bottom-6 left-1/2 -translate-x-1/2',
  };
  return positions[props.position];
});

const variantClasses = computed(() => {
  const variants = {
    primary: 'bg-primary-500 text-white hover:bg-primary-600 hover:shadow-lg hover:shadow-primary-500/30',
    neutral: 'bg-neutral-900 dark:bg-white text-white dark:text-neutral-900 hover:bg-neutral-800 dark:hover:bg-neutral-100',
    glass: 'xGlass text-neutral-900 dark:text-white hover:bg-white/80 dark:hover:bg-black/60',
  };
  return variants[props.variant];
});

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

const handleScroll = () => {
  isVisible.value = window.scrollY > props.threshold;
};

onMounted(() => {
  if (import.meta.client) {
    window.addEventListener('scroll', handleScroll, { passive: true });
    handleScroll();
  }
});

onUnmounted(() => {
  if (import.meta.client) {
    window.removeEventListener('scroll', handleScroll);
  }
});
</script>
