<script setup>
import { ref, computed, onMounted, onBeforeUnmount, shallowRef } from "vue";
import { useNamespace, useZIndex, useLocale } from "@yh-ui/hooks";
import { useComponentTheme } from "@yh-ui/theme";
import { backTopProps, backTopEmits } from "./back-top";
defineOptions({
  name: "YhBackTop"
});
const props = defineProps(backTopProps);
const emit = defineEmits(backTopEmits);
const ns = useNamespace("back-top");
const { t } = useLocale();
const { nextZIndex } = useZIndex();
const { themeStyle } = useComponentTheme(
  "back-top",
  computed(() => props.themeOverrides)
);
const visible = ref(false);
const progress = ref(0);
const scrollContainer = shallowRef();
const elRef = ref();
const containerStyle = computed(() => ({
  ...themeStyle.value,
  right: `${props.right}px`,
  bottom: `${props.bottom}px`,
  zIndex: nextZIndex()
}));
const progressStyle = computed(() => ({
  strokeDashoffset: (1 - progress.value / 100) * 100,
  color: props.progressColor || "var(--yh-color-primary)"
}));
const getScrollInfo = (el) => {
  if (el instanceof Window) {
    const top = window.scrollY;
    const totalHeight = document.documentElement.scrollHeight - window.innerHeight;
    return { top, totalHeight };
  } else {
    const top = el.scrollTop;
    const totalHeight = el.scrollHeight - el.clientHeight;
    return { top, totalHeight };
  }
};
let scheduled = false;
const handleScroll = () => {
  if (!scheduled) {
    scheduled = true;
    requestAnimationFrame(() => {
      if (!scrollContainer.value) return;
      const { top, totalHeight } = getScrollInfo(scrollContainer.value);
      visible.value = top >= props.visibilityHeight;
      progress.value = totalHeight > 0 ? Math.min(top / totalHeight * 100, 100) : 0;
      scheduled = false;
    });
  }
};
const scrollToTop = () => {
  const container = scrollContainer.value;
  if (!container) return;
  const beginTime = Date.now();
  const { top: beginValue } = getScrollInfo(container);
  const rAF = window.requestAnimationFrame;
  const frameFunc = () => {
    const progress2 = (Date.now() - beginTime) / props.duration;
    if (progress2 < 1) {
      const el = container instanceof Window ? document.documentElement : container;
      el.scrollTo(0, beginValue * (1 - easeInOutCubic(progress2)));
      rAF(frameFunc);
    } else {
      const el = container instanceof Window ? document.documentElement : container;
      el.scrollTo(0, 0);
    }
  };
  rAF(frameFunc);
};
const easeInOutCubic = (t2) => t2 < 0.5 ? 4 * t2 * t2 * t2 : (t2 - 1) * (2 * t2 - 2) * (2 * t2 - 2) + 1;
const handleClick = (event) => {
  scrollToTop();
  emit("click", event);
};
onMounted(() => {
  if (props.target) {
    scrollContainer.value = document.querySelector(props.target);
  } else {
    scrollContainer.value = window;
  }
  if (scrollContainer.value) {
    scrollContainer.value.addEventListener("scroll", handleScroll, { passive: true });
    handleScroll();
  }
});
onBeforeUnmount(() => {
  if (scrollContainer.value) {
    scrollContainer.value.removeEventListener("scroll", handleScroll);
  }
});
</script>

<template>
  <Transition :name="`${ns.namespace.value}-fade-in`">
    <div
      v-if="visible"
      ref="elRef"
      :class="ns.b()"
      :style="containerStyle"
      :aria-label="t('backtop.text')"
      @click.stop="handleClick"
    >
      <slot>
        <div :class="ns.e('content')">
          <svg viewBox="0 0 1024 1024" width="20" height="20">
            <path fill="currentColor" d="M512 320L192 640h640z" />
          </svg>
        </div>
      </slot>

      <!-- 进度环 -->
      <svg v-if="showProgress" :class="ns.e('progress')" viewBox="0 0 36 36">
        <circle :class="ns.e('progress-bg')" cx="18" cy="18" r="16" />
        <circle :class="ns.e('progress-bar')" cx="18" cy="18" r="16" :style="progressStyle" />
      </svg>
    </div>
  </Transition>
</template>

<style>
@charset "UTF-8";
/**
 * YH-UI Sass Variables
 * 原具体的 CSS 变量输出规则 (:root, html.dark 等) 已移至 root.scss，以防止各组件样式编译时产生重复的全局变量 CSS 冗余。
 */
.yh-back-top {
  position: fixed;
  width: 44px;
  height: 44px;
  border-radius: 50%;
  background-color: var(--yh-bg-color-overlay);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08), 0 2px 6px rgba(0, 0, 0, 0.04);
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  color: var(--yh-color-primary);
  user-select: none;
}
.yh-back-top:hover {
  background-color: var(--yh-fill-color-light);
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}
.yh-back-top__content {
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1;
}

.yh-back-top__progress {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transform: rotate(-90deg);
  pointer-events: none;
}
.yh-back-top__progress circle {
  fill: none;
  stroke-width: 2.5;
  stroke-linecap: round;
}
.yh-back-top__progress-bg {
  stroke: var(--yh-border-color-lighter);
  opacity: 0.3;
}

.yh-back-top__progress-bar {
  stroke: currentColor;
  stroke-dasharray: 100;
  stroke-dashoffset: 100;
  transition: stroke-dashoffset 0.1s linear;
}

/* 动画效果适配命名空间 */
.yh-fade-in-enter-active,
.yh-fade-in-leave-active {
  transition: opacity 0.3s, transform 0.3s cubic-bezier(0.23, 1, 0.32, 1);
}

.yh-fade-in-enter-from,
.yh-fade-in-leave-to {
  opacity: 0;
  transform: scale(0.5) translateY(20px);
}
</style>
