<script setup lang="ts">
import ArrowUpIcon from "@/components/svg/ArrowUpIcon.vue";

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

const bottomOffset = ref("1rem");
const showArrow = ref(false); 
let observer: IntersectionObserver | null = null;

const handleScroll = () => {
  showArrow.value = window.scrollY > 50; 
};

onMounted(() => {
  const footer = document.querySelector("footer");
  if (footer) {
    observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          bottomOffset.value = entry.isIntersecting
            ? `${footer.clientHeight + 16}px`
            : "1rem";
        });
      },
      { root: null, threshold: 0 },
    );
    observer.observe(footer);
  }

 
  window.addEventListener("scroll", handleScroll);
  handleScroll(); 
});

onBeforeUnmount(() => {
  if (observer) observer.disconnect();
  window.removeEventListener("scroll", handleScroll);
});
</script>

<template>
  <transition name="fade">
    <div
      v-if="showArrow"
      class="fixed right-4 z-50 cursor-pointer transition-all duration-300"
      :style="{ bottom: bottomOffset }"
    >
      <Button
        :aria-label="$t('ariaLabels.scrollToTop')"
        size="wsIcon"
        class="hover:bg-accent/90 !text-primary ws-gradient-border-animated cursor-pointer transition-colors"
        @click="scrollToTop"
      >
        <ArrowUpIcon aria-hidden="true" />
      </Button>
    </div>
  </transition>
</template>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.4s ease, transform 0.4s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(20px);
}
</style>
