<script setup>
import { ref, watch, computed, useSlots, useId } from "vue";
import { useNamespace, useLocale } from "@yh-ui/hooks";
import { useComponentTheme } from "@yh-ui/theme";
import { spinProps, spinEmits } from "./spin";
defineOptions({
  name: "YhSpin",
  inheritAttrs: false
});
const props = defineProps(spinProps);
const ns = useNamespace("spin");
const { t } = useLocale();
const gradientId = useId();
const { themeStyle } = useComponentTheme(
  "spin",
  computed(() => props.themeOverrides)
);
const emit = defineEmits(spinEmits);
const internalVisible = ref(false);
const visible = computed(() => props.delay === 0 ? props.show : internalVisible.value);
let timer = null;
const handleShow = () => {
  if (props.delay > 0) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      internalVisible.value = true;
      emit("show");
    }, props.delay);
  } else {
    internalVisible.value = true;
    emit("show");
  }
};
const handleHide = () => {
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }
  internalVisible.value = false;
  emit("hide");
};
const sizePx = computed(() => {
  if (typeof props.size === "number") return props.size;
  const map = { small: 20, default: 32, large: 48 };
  return map[props.size] || 32;
});
const isGradient = computed(() => {
  if (typeof props.color === "string") {
    return props.color.includes("gradient");
  }
  return typeof props.color === "object" && props.color !== null || Array.isArray(props.color);
});
const gradientStops = computed(() => {
  const { color } = props;
  if (!isGradient.value || !color) return [];
  if (typeof color === "string") {
    const colorRegex = /(?:#[a-fA-F0-9]{3,8}|rgba?\s*\([^)]+\)|hsla?\s*\([^)]+\)|(?:\b[a-z]{3,}\b))/gi;
    const matchedColors = color.match(colorRegex)?.filter((c) => !/gradient|deg|to|top|bottom|left|right/i.test(c));
    if (matchedColors && matchedColors.length > 0) {
      const len = matchedColors.length;
      return matchedColors.map((c, i) => ({
        color: c.trim(),
        offset: `${i / (len - 1 || 1) * 100}%`
      }));
    }
    return [];
  }
  if (Array.isArray(color)) {
    const len = color.length;
    return color.map((c, i) => ({
      color: c,
      offset: `${i / (len - 1 || 1) * 100}%`
    }));
  }
  return Object.entries(color).map(([offset, c]) => ({
    offset,
    color: c
  }));
});
const spinStyle = computed(() => {
  const style = {};
  if (!props.color) return style;
  if (isGradient.value) {
    style["--yh-spin-color-is-gradient"] = "true";
    if (typeof props.color === "string") {
      style["--yh-spin-gradient"] = props.color;
    } else {
      const stops = gradientStops.value.map((s) => `${s.color} ${s.offset}`).join(", ");
      style["--yh-spin-gradient"] = `linear-gradient(135deg, ${stops})`;
    }
  } else {
    style.color = props.color;
  }
  return {
    ...themeStyle.value,
    ...style
  };
});
watch(
  () => props.show,
  (val) => {
    if (val) handleShow();
    else handleHide();
  },
  { immediate: true }
);
const spinClasses = computed(() => [
  ns.b(),
  ns.m(typeof props.size === "string" ? props.size : "custom"),
  ns.is("vertical", props.vertical),
  ns.is("glass", props.glass || !!useSlots().default),
  ns.is("dot", props.dot),
  ns.is("gradient", isGradient.value)
]);
defineExpose({
  /** 是否可见 */
  visible
});
</script>

<template>
  <svg
    v-if="visible && isGradient"
    style="width: 0; height: 0; position: absolute; visibility: hidden; pointer-events: none"
  >
    <defs>
      <linearGradient :id="gradientId" x1="0%" y1="0%" x2="100%" y2="100%">
        <stop
          v-for="(stop, i) in gradientStops"
          :key="i"
          :offset="stop.offset"
          :stop-color="stop.color"
        />
      </linearGradient>
    </defs>
  </svg>

  <div v-if="$slots.default" :class="ns.b('wrapper')" v-bind="$attrs">
    <slot />
    <Transition name="yh-spin-fade">
      <div v-if="visible" :class="spinClasses" :style="spinStyle">
        <div v-if="glass" :class="ns.e('mask')" />
        <div :class="ns.e('container')">
          <!-- Dot 模式 (兼容旧版) -->
          <div v-if="dot" :class="ns.e('dots')">
            <i v-for="i in 4" :key="i" />
          </div>

          <!-- Chaser 模式 (追逐点) -->
          <div
            v-else-if="type === 'chaser'"
            :class="ns.e('chaser')"
            :style="{
  width: sizePx + 'px',
  height: sizePx + 'px'
}"
          >
            <i v-for="i in 8" :key="i" />
          </div>

          <!-- Gear 模式 (齿轮线) -->
          <div
            v-else-if="type === 'gear'"
            :class="ns.e('gear')"
            :style="{
  width: sizePx + 'px',
  height: sizePx + 'px'
}"
          >
            <i v-for="i in 12" :key="i" />
          </div>

          <!-- Dual Ring 模式 -->
          <div
            v-else-if="type === 'dual-ring'"
            :class="ns.e('dual-ring')"
            :style="{
  width: sizePx + 'px',
  height: sizePx + 'px'
}"
          />

          <!-- Rect 模式 (矩阵块) -->
          <div
            v-else-if="type === 'rect'"
            :class="ns.e('rect')"
            :style="{
  width: sizePx + 'px',
  height: sizePx + 'px'
}"
          >
            <i v-for="i in 9" :key="i" />
          </div>

          <!-- 默认 Circle 模式 (SVG) -->
          <svg
            v-else
            :class="ns.e('svg')"
            viewBox="0 0 50 50"
            :style="{
  width: sizePx + 'px',
  height: sizePx + 'px'
}"
          >
            <circle
              :class="ns.e('circle')"
              cx="25"
              cy="25"
              r="20"
              fill="none"
              stroke-width="5"
              :style="{
  stroke: isGradient ? `url(#${gradientId})` : 'currentColor'
}"
            ></circle>
          </svg>

          <div v-if="tip || $slots.tip" :class="ns.e('tip')">
            <slot name="tip">{{ tip || t("spin.text") }}</slot>
          </div>
        </div>
      </div>
    </Transition>
  </div>

  <Transition v-else name="yh-spin-fade">
    <div v-if="visible" v-bind="$attrs" :class="spinClasses" :style="spinStyle">
      <div v-if="glass" :class="ns.e('mask')" />
      <div :class="ns.e('container')">
        <!-- Dot 模式 (兼容旧版) -->
        <div v-if="dot" :class="ns.e('dots')">
          <i v-for="i in 4" :key="i" />
        </div>

        <!-- Chaser 模式 -->
        <div
          v-else-if="type === 'chaser'"
          :class="ns.e('chaser')"
          :style="{
  width: sizePx + 'px',
  height: sizePx + 'px'
}"
        >
          <i v-for="i in 8" :key="i" />
        </div>

        <!-- Gear 模式 -->
        <div
          v-else-if="type === 'gear'"
          :class="ns.e('gear')"
          :style="{
  width: sizePx + 'px',
  height: sizePx + 'px'
}"
        >
          <i v-for="i in 12" :key="i" />
        </div>

        <!-- Dual Ring 模式 -->
        <div
          v-else-if="type === 'dual-ring'"
          :class="ns.e('dual-ring')"
          :style="{
  width: sizePx + 'px',
  height: sizePx + 'px'
}"
        />

        <!-- Rect 模式 -->
        <div
          v-else-if="type === 'rect'"
          :class="ns.e('rect')"
          :style="{
  width: sizePx + 'px',
  height: sizePx + 'px'
}"
        >
          <i v-for="i in 9" :key="i" />
        </div>

        <!-- 默认 Circle 模式 -->
        <svg
          v-else
          :class="ns.e('svg')"
          viewBox="0 0 50 50"
          :style="{
  width: sizePx + 'px',
  height: sizePx + 'px'
}"
        >
          <circle
            :class="ns.e('circle')"
            cx="25"
            cy="25"
            r="20"
            fill="none"
            stroke-width="5"
            :style="{
  stroke: isGradient ? `url(#${gradientId})` : 'currentColor'
}"
          ></circle>
        </svg>

        <div v-if="tip || $slots.default || $slots.tip" :class="ns.e('tip')">
          <slot name="tip">
            <slot>{{ tip || t("spin.text") }}</slot>
          </slot>
        </div>
      </div>
    </div>
  </Transition>
</template>

<style>
@charset "UTF-8";
/**
 * YH-UI Sass Variables
 * 原具体的 CSS 变量输出规则 (:root, html.dark 等) 已移至 root.scss，以防止各组件样式编译时产生重复的全局变量 CSS 冗余。
 */
.yh-spin-wrapper {
  position: relative;
  display: inline-block;
  width: 100%;
}

.yh-spin {
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--yh-color-primary, #409eff);
}
.yh-spin--small {
  font-size: 12px;
}

.yh-spin--default {
  font-size: 14px;
}

.yh-spin--large {
  font-size: 16px;
}

.yh-spin.is-vertical {
  flex-direction: column;
}
.yh-spin.is-vertical .yh-spin__tip {
  margin-left: 0;
  margin-top: 8px;
}

.yh-spin.is-glass {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: inherit;
  /* 核心：模糊与背景必须连带应用，且避开 3D transform 冲突 */
  background: var(--yh-spin-mask-bg, rgba(255, 255, 255, 0.65));
  backdrop-filter: blur(var(--yh-spin-blur-radius, 4px));
  -webkit-backdrop-filter: blur(var(--yh-spin-blur-radius, 4px));
}
@media (prefers-color-scheme: dark) {
  .yh-spin.is-glass {
    background: var(--yh-spin-mask-bg-dark, rgba(0, 0, 0, 0.5));
  }
}

.yh-spin {
  /* 独立增强层：仅处理噪点纹理，确保不干扰模糊捕获 */
}
.yh-spin__mask {
  position: absolute;
  inset: 0;
  z-index: -1;
  pointer-events: none;
}
.yh-spin__mask::before {
  content: "";
  position: absolute;
  inset: 0;
  opacity: 0.04;
  background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.65' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)'/%3E%3C/svg%3E");
}

.yh-spin__container {
  display: flex;
  flex-direction: inherit;
  align-items: center;
  justify-content: center;
  /* 容器独立加速，确保旋转图标在滤镜上方丝滑运行 */
  transform: translateZ(0);
  will-change: transform;
  z-index: 1;
}

.yh-spin__svg {
  animation: yh-spin-rotate 2s linear infinite;
  shape-rendering: geometricPrecision;
  will-change: transform;
}

.yh-spin__circle {
  stroke: currentColor;
  stroke-linecap: round;
  animation: yh-spin-dash 1.5s ease-in-out infinite;
}

.yh-spin__tip {
  margin-left: 10px;
  color: inherit;
  font-weight: 500;
  transition: all 0.3s;
}

.yh-spin {
  /* 渐变状态下的特殊处理 */
}
.yh-spin.is-gradient .yh-spin__tip {
  background: var(--yh-spin-gradient);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  display: inline-block;
}

.yh-spin.is-gradient .yh-spin__dots i {
  background: var(--yh-spin-gradient);
  background-color: transparent;
}

.yh-spin {
  /* Dot 模式样式 */
}
.yh-spin__dots {
  width: 1em;
  height: 1em;
  position: relative;
  display: inline-block;
  transform: rotate(45deg);
  animation: yh-spin-rotate 1.2s infinite linear;
}
.yh-spin__dots i {
  width: 0.45em;
  height: 0.45em;
  position: absolute;
  display: block;
  background-color: currentColor;
  border-radius: 100%;
  transform: scale(0.75);
  transform-origin: 50% 50%;
  opacity: 0.3;
  animation: yh-spin-move 1s infinite linear alternate;
}
.yh-spin__dots i:nth-child(1) {
  top: 0;
  left: 0;
}
.yh-spin__dots i:nth-child(2) {
  top: 0;
  right: 0;
  animation-delay: 0.4s;
}
.yh-spin__dots i:nth-child(3) {
  right: 0;
  bottom: 0;
  animation-delay: 0.8s;
}
.yh-spin__dots i:nth-child(4) {
  left: 0;
  bottom: 0;
  animation-delay: 1.2s;
}

.yh-spin {
  /* Chaser 模式 (追逐点) - 模拟彗星拖尾效果 */
}
.yh-spin__chaser {
  position: relative;
}
.yh-spin__chaser i {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}
.yh-spin__chaser i::after {
  content: "";
  display: block;
  margin: 0 auto;
  width: 18%;
  height: 18%;
  background-color: currentColor;
  border-radius: 100%;
  animation: yh-spin-chaser 1.2s infinite ease-in-out both;
}
.yh-spin__chaser i:nth-child(1) {
  transform: rotate(0deg);
}
.yh-spin__chaser i:nth-child(1)::after {
  animation-delay: -1.05s;
}
.yh-spin__chaser i:nth-child(2) {
  transform: rotate(45deg);
}
.yh-spin__chaser i:nth-child(2)::after {
  animation-delay: -0.9s;
}
.yh-spin__chaser i:nth-child(3) {
  transform: rotate(90deg);
}
.yh-spin__chaser i:nth-child(3)::after {
  animation-delay: -0.75s;
}
.yh-spin__chaser i:nth-child(4) {
  transform: rotate(135deg);
}
.yh-spin__chaser i:nth-child(4)::after {
  animation-delay: -0.6s;
}
.yh-spin__chaser i:nth-child(5) {
  transform: rotate(180deg);
}
.yh-spin__chaser i:nth-child(5)::after {
  animation-delay: -0.45s;
}
.yh-spin__chaser i:nth-child(6) {
  transform: rotate(225deg);
}
.yh-spin__chaser i:nth-child(6)::after {
  animation-delay: -0.3s;
}
.yh-spin__chaser i:nth-child(7) {
  transform: rotate(270deg);
}
.yh-spin__chaser i:nth-child(7)::after {
  animation-delay: -0.15s;
}
.yh-spin__chaser i:nth-child(8) {
  transform: rotate(315deg);
}
.yh-spin__chaser i:nth-child(8)::after {
  animation-delay: 0s;
}

.yh-spin {
  /* Gear 模式 (齿轮线) - 经典 Spinner */
}
.yh-spin__gear {
  position: relative;
}
.yh-spin__gear i {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}
.yh-spin__gear i::after {
  content: "";
  display: block;
  margin: 0 auto;
  width: 8%;
  height: 25%;
  background-color: currentColor;
  border-radius: 5px;
  animation: yh-spin-fade 1.1s infinite ease-in-out both;
}
.yh-spin__gear i:nth-child(1) {
  transform: rotate(0deg);
}
.yh-spin__gear i:nth-child(1)::after {
  animation-delay: -1.001s;
}
.yh-spin__gear i:nth-child(2) {
  transform: rotate(30deg);
}
.yh-spin__gear i:nth-child(2)::after {
  animation-delay: -0.91s;
}
.yh-spin__gear i:nth-child(3) {
  transform: rotate(60deg);
}
.yh-spin__gear i:nth-child(3)::after {
  animation-delay: -0.819s;
}
.yh-spin__gear i:nth-child(4) {
  transform: rotate(90deg);
}
.yh-spin__gear i:nth-child(4)::after {
  animation-delay: -0.728s;
}
.yh-spin__gear i:nth-child(5) {
  transform: rotate(120deg);
}
.yh-spin__gear i:nth-child(5)::after {
  animation-delay: -0.637s;
}
.yh-spin__gear i:nth-child(6) {
  transform: rotate(150deg);
}
.yh-spin__gear i:nth-child(6)::after {
  animation-delay: -0.546s;
}
.yh-spin__gear i:nth-child(7) {
  transform: rotate(180deg);
}
.yh-spin__gear i:nth-child(7)::after {
  animation-delay: -0.455s;
}
.yh-spin__gear i:nth-child(8) {
  transform: rotate(210deg);
}
.yh-spin__gear i:nth-child(8)::after {
  animation-delay: -0.364s;
}
.yh-spin__gear i:nth-child(9) {
  transform: rotate(240deg);
}
.yh-spin__gear i:nth-child(9)::after {
  animation-delay: -0.273s;
}
.yh-spin__gear i:nth-child(10) {
  transform: rotate(270deg);
}
.yh-spin__gear i:nth-child(10)::after {
  animation-delay: -0.182s;
}
.yh-spin__gear i:nth-child(11) {
  transform: rotate(300deg);
}
.yh-spin__gear i:nth-child(11)::after {
  animation-delay: -0.091s;
}
.yh-spin__gear i:nth-child(12) {
  transform: rotate(330deg);
}
.yh-spin__gear i:nth-child(12)::after {
  animation-delay: 0s;
}

.yh-spin {
  /* Dual Ring 模式 - 极简之美 */
}
.yh-spin__dual-ring {
  display: inline-block;
}
.yh-spin__dual-ring::after {
  content: " ";
  display: block;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 2px solid currentColor;
  border-color: currentColor transparent currentColor transparent;
  animation: yh-spin-rotate 1s linear infinite;
}

.yh-spin {
  /* Rect 模式 (矩阵块) - 灵动跳跃 */
}
.yh-spin__rect {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  gap: 12%;
}
.yh-spin__rect i {
  width: 100%;
  height: 100%;
  background: currentColor;
  border-radius: 15%;
  animation: yh-spin-rect 1.2s infinite ease-in-out;
}
.yh-spin__rect i:nth-child(1) {
  animation-delay: 0s;
}
.yh-spin__rect i:nth-child(2) {
  animation-delay: 0.15s;
}
.yh-spin__rect i:nth-child(3) {
  animation-delay: 0.3s;
}
.yh-spin__rect i:nth-child(4) {
  animation-delay: 0.15s;
}
.yh-spin__rect i:nth-child(5) {
  animation-delay: 0.3s;
}
.yh-spin__rect i:nth-child(6) {
  animation-delay: 0.45s;
}
.yh-spin__rect i:nth-child(7) {
  animation-delay: 0.3s;
}
.yh-spin__rect i:nth-child(8) {
  animation-delay: 0.45s;
}
.yh-spin__rect i:nth-child(9) {
  animation-delay: 0.6s;
}

.yh-spin {
  /* 渐变支持增强 - 修复: 仅应用到可见元素，不应用到定位容器 i 上 */
}
.yh-spin.is-gradient .yh-spin__chaser i::after, .yh-spin.is-gradient .yh-spin__gear i::after {
  background: var(--yh-spin-gradient);
}

.yh-spin.is-gradient .yh-spin__rect i {
  background: var(--yh-spin-gradient);
}

.yh-spin.is-gradient .yh-spin__dual-ring::after {
  /* 这里的技巧：即使是渐变，我们也取第一个颜色作为边框回退，
     或者通过 mask 增强，但基础修复是确保它不是全圆 */
  border-color: var(--yh-color-primary, #00d2ff) transparent;
}

@keyframes yh-spin-chaser {
  0%, 80%, 100% {
    transform: scale(0);
    opacity: 0.1;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}
@keyframes yh-spin-rect {
  0%, 70%, 100% {
    transform: scale3D(1, 1, 1);
    opacity: 1;
  }
  35% {
    transform: scale3D(0.4, 0.4, 1);
    opacity: 0.3;
  }
}
@keyframes yh-spin-fade {
  0%, 39%, 100% {
    opacity: 0.2;
    transform: scale(0.8);
  }
  40% {
    opacity: 1;
    transform: scale(1);
  }
}
@keyframes yh-spin-rotate {
  100% {
    transform: rotate(360deg);
  }
}
@keyframes yh-spin-dash {
  0% {
    stroke-dasharray: 1, 200;
    stroke-dashoffset: 0;
  }
  50% {
    stroke-dasharray: 90, 200;
    stroke-dashoffset: -35px;
  }
  100% {
    stroke-dasharray: 90, 200;
    stroke-dashoffset: -124px;
  }
}
@keyframes yh-spin-move {
  to {
    opacity: 1;
    transform: scale(1);
  }
}
.yh-spin-fade-enter-active,
.yh-spin-fade-leave-active {
  transition: opacity 0.3s ease;
}

.yh-spin-fade-enter-from,
.yh-spin-fade-leave-to {
  opacity: 0;
}
</style>
