<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";
import Icon from "./Icon.vue";

const isVisible = ref(false);
let ticking = false;

const updateScroll = () => {
    isVisible.value = window.scrollY > 50;
    ticking = false;
};

const onScroll = () => {
    if (!ticking) {
        window.requestAnimationFrame(updateScroll);
        ticking = true;
    }
};

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

onMounted(() => {
    updateScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
});

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

<template>
    <button
        @click="scrollToTop"
        class="fixed bottom-4 right-4 z-20 btn btn-secondary hover:btn-primary btn-circle transition-all duration-300"
        :class="
            isVisible
                ? 'opacity-100 translate-y-0'
                : 'opacity-0 translate-y-10 pointer-events-none'
        "
        aria-label="Scroll to top"
    >
        <Icon name="arrow-up" class="text-lg" />
    </button>
</template>
