<script setup lang="ts">
import { AIconChevronUp } from "#components";

const isShow = ref(false)
const footerHeight = ref(0)

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

const isViewPort = (el: HTMLElement | null) => {
  const windowHeight = window.innerHeight;
  const rect = el ? el.getBoundingClientRect() : {top: 0, bottom: 0};
  return Math.ceil(
    Math.max(
      0,
      rect.top > 0
        ? Math.min(el.offsetHeight, windowHeight - rect.top)
        : Math.min(rect.bottom, windowHeight)
    )
  )
}

const scrollHandle = () => {
  isShow.value = window.scrollY > window.innerHeight / 2
  if (isShow.value) {
    const footer = document.getElementById('footer')
    footerHeight.value = isViewPort(footer) + 32
  }
}

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

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

<template>
  <div
    class="z-[9999] hidden lg:block fixed right-5 transition"
    :class="[{ 'opacity-0': !isShow }]"
    :style="{ bottom: footerHeight + 'px' }"
  >
    <a-button
      @click="goTop"
      form="icon"
      :icon="AIconChevronUp"
      icon-class="h-6 w-6"
      size="lg"
      variant="gray"
    />
  </div>
</template>

<style scoped></style>
