<script setup>
import { ref, computed, onBeforeUnmount, inject } from "vue";
import { useNamespace } from "@yh-ui/hooks";
const props = defineProps({
  modelValue: { type: Number, required: true },
  vertical: { type: Boolean, required: true, default: false },
  disabled: { type: Boolean, required: true, default: false },
  min: { type: Number, required: true },
  max: { type: Number, required: true },
  step: { type: Number, required: true },
  showTooltip: { type: Boolean, required: true, default: true },
  formatTooltip: { type: Function, required: false, default: void 0 },
  tooltipClass: { type: String, required: false, default: void 0 },
  placement: { type: String, required: false, default: "top" }
});
const emit = defineEmits(["update:modelValue", "input", "change"]);
const ns = useNamespace("slider");
const slider = inject("slider");
const dragging = ref(false);
const hovering = ref(false);
const isClick = ref(false);
const startX = ref(0);
const startY = ref(0);
const startPosition = ref(0);
const newPosition = ref(0);
const tooltipVisible = computed(() => props.showTooltip && (dragging.value || hovering.value));
const currentPosition = computed(() => {
  return `${(props.modelValue - props.min) / (props.max - props.min) * 100}%`;
});
const wrapperStyle = computed(() => {
  return props.vertical ? { bottom: currentPosition.value, top: "auto" } : { left: currentPosition.value, top: "50%" };
});
const displayValue = computed(() => {
  if (props.formatTooltip) {
    return props.formatTooltip(props.modelValue);
  }
  return props.modelValue;
});
const handleMouseEnter = () => {
  hovering.value = true;
};
const handleMouseLeave = () => {
  hovering.value = false;
};
const onButtonDown = (event) => {
  if (props.disabled) return;
  event.preventDefault();
  onDragStart(event);
  window.addEventListener("mousemove", onDragging);
  window.addEventListener("touchmove", onDragging);
  window.addEventListener("mouseup", onDragEnd);
  window.addEventListener("touchend", onDragEnd);
  window.addEventListener("contextmenu", onDragEnd);
};
const onDragStart = (event) => {
  dragging.value = true;
  isClick.value = true;
  if (event instanceof MouseEvent) {
    startX.value = event.clientX;
    startY.value = event.clientY;
  } else {
    startX.value = event.touches[0].clientX;
    startY.value = event.touches[0].clientY;
  }
  startPosition.value = parseFloat(currentPosition.value);
  newPosition.value = startPosition.value;
};
const onDragging = (event) => {
  if (dragging.value) {
    isClick.value = false;
    let diff = 0;
    const sliderSize = getSliderSize();
    if (sliderSize > 0) {
      if (event instanceof MouseEvent) {
        if (props.vertical) {
          diff = (startY.value - event.clientY) / sliderSize * 100;
        } else {
          diff = (event.clientX - startX.value) / sliderSize * 100;
        }
      } else {
        if (props.vertical) {
          diff = (startY.value - event.touches[0].clientY) / sliderSize * 100;
        } else {
          diff = (event.touches[0].clientX - startX.value) / sliderSize * 100;
        }
      }
      newPosition.value = startPosition.value + diff;
      setPosition(newPosition.value);
    }
  }
};
const onDragEnd = () => {
  if (dragging.value) {
    setTimeout(() => {
      dragging.value = false;
      if (!isClick.value) {
        setPosition(newPosition.value);
      }
      emit("change", props.modelValue);
    }, 0);
    window.removeEventListener("mousemove", onDragging);
    window.removeEventListener("touchmove", onDragging);
    window.removeEventListener("mouseup", onDragEnd);
    window.removeEventListener("touchend", onDragEnd);
    window.removeEventListener("contextmenu", onDragEnd);
  }
};
const getSliderSize = () => {
  if (!slider?.sliderRef?.value) return 0;
  return props.vertical ? slider.sliderRef.value.offsetHeight : slider.sliderRef.value.offsetWidth;
};
const setPosition = (percent) => {
  if (percent < 0) percent = 0;
  if (percent > 100) percent = 100;
  const lengthPerStep = 100 / ((props.max - props.min) / props.step);
  const steps = Math.round(percent / lengthPerStep);
  let value = steps * lengthPerStep * (props.max - props.min) * 0.01 + props.min;
  value = parseFloat(value.toFixed(getPrecision(props.step)));
  if (value !== props.modelValue) {
    emit("update:modelValue", value);
    emit("input", value);
  }
};
const getPrecision = (step) => {
  const stepStr = step.toString();
  const dotIndex = stepStr.indexOf(".");
  return dotIndex > -1 ? stepStr.length - dotIndex - 1 : 0;
};
onBeforeUnmount(() => {
  window.removeEventListener("mousemove", onDragging);
  window.removeEventListener("touchmove", onDragging);
  window.removeEventListener("mouseup", onDragEnd);
  window.removeEventListener("touchend", onDragEnd);
  window.removeEventListener("contextmenu", onDragEnd);
});
defineExpose({
  onButtonDown
});
</script>

<template>
  <div
    ref="button"
    :class="[ns.e('button-wrapper'), ns.is('dragging', dragging)]"
    :style="wrapperStyle"
    @mouseenter="handleMouseEnter"
    @mouseleave="handleMouseLeave"
    @mousedown="onButtonDown"
    @touchstart="onButtonDown"
  >
    <slot name="thumb" :value="modelValue">
      <div :class="[ns.e('button'), ns.is('hover', hovering), ns.is('dragging', dragging)]"></div>
    </slot>
    <transition name="yh-fade">
      <div v-if="tooltipVisible" :class="[ns.e('tooltip'), tooltipClass]">
        <div :class="ns.e('tooltip-content')">
          {{ displayValue }}
        </div>
        <div :class="ns.e('tooltip-arrow')"></div>
      </div>
    </transition>
  </div>
</template>

<style>
@charset "UTF-8";
/**
 * YH-UI Sass Variables
 * 原具体的 CSS 变量输出规则 (:root, html.dark 等) 已移至 root.scss，以防止各组件样式编译时产生重复的全局变量 CSS 冗余。
 */
.yh-slider {
  --yh-slider-main-color: var(--yh-color-primary);
  --yh-slider-main-color-rgb: 64, 158, 255;
  --yh-slider-secondary-color: var(--yh-color-primary);
  --yh-slider-bg-color: var(--yh-border-color-light);
  --yh-slider-hover-bg-color: var(--yh-border-color-dark);
  --yh-slider-button-size: 16px;
  --yh-slider-button-border: 2px;
  --yh-slider-runway-height: 6px;
  --yh-slider-transition: var(--yh-transition-base);
  display: inline-flex;
  align-items: center;
  width: 100%;
  height: var(--yh-slider-height, 32px);
  position: relative;
  user-select: none;
  box-sizing: border-box;
}
.yh-slider.is-vertical {
  display: inline-flex;
  width: auto;
  height: 100%;
  flex-direction: column;
  padding: 0;
  margin: 0 12px;
  align-items: center;
}
.yh-slider.is-vertical .yh-slider__runway {
  width: var(--yh-slider-runway-height);
  height: 100%;
  flex: 1;
  margin: 0;
  position: relative;
}

.yh-slider.is-vertical .yh-slider__button-wrapper {
  left: 50%;
  transform: translate(-50%, 50%);
  top: auto;
  z-index: 10;
}

.yh-slider.is-vertical .yh-slider__bar {
  width: 100%;
  height: auto;
  left: 0;
  bottom: 0;
  top: auto;
  background: linear-gradient(to top, var(--yh-slider-main-color), var(--yh-slider-secondary-color));
}

.yh-slider.is-vertical .yh-slider__stop {
  left: 50%;
  top: auto;
  transform: translate(-50%, 50%);
}

.yh-slider.is-vertical .yh-slider__marks {
  position: absolute;
  left: 18px;
  top: 0;
  bottom: 0;
  width: 0;
}

.yh-slider.is-vertical .yh-slider__mark-text {
  left: 0;
  top: auto;
  transform: translateY(50%);
  white-space: nowrap;
}

.yh-slider.is-vertical .yh-slider__input {
  margin-right: 0;
  margin-top: 20px;
  width: auto;
}

.yh-slider__input {
  flex-shrink: 0;
  margin-right: 20px;
  width: auto;
}

.yh-slider__runway {
  flex: 1;
  height: var(--yh-slider-runway-height);
  background-color: var(--yh-slider-bg-color);
  border-radius: 3px;
  position: relative;
  cursor: pointer;
  vertical-align: middle;
}
.yh-slider__runway:hover {
  background-color: var(--yh-slider-hover-bg-color);
}

.yh-slider.is-disabled .yh-slider__runway {
  cursor: not-allowed;
  background-color: var(--yh-fill-color-light);
}
.yh-slider.is-disabled .yh-slider__runway:hover {
  background-color: var(--yh-fill-color-light);
}

.yh-slider.is-disabled .yh-slider__bar {
  background: var(--yh-text-color-placeholder);
  box-shadow: none;
}

.yh-slider.is-disabled .yh-slider__button {
  border-color: var(--yh-text-color-placeholder);
  background-color: var(--yh-bg-color);
  cursor: not-allowed;
}
.yh-slider.is-disabled .yh-slider__button:hover {
  transform: none;
  box-shadow: none;
}

.yh-slider.is-disabled .yh-slider__button-wrapper {
  cursor: not-allowed;
}

.yh-slider__bar {
  position: absolute;
  height: 100%;
  left: 0;
  top: 0;
  border-radius: inherit;
  background: linear-gradient(90deg, var(--yh-slider-main-color), var(--yh-slider-secondary-color));
  box-shadow: 0 4px 12px rgba(var(--yh-slider-main-color-rgb, 64, 158, 255), 0.2);
  transition: width var(--yh-duration-base), left var(--yh-duration-base), height var(--yh-duration-base), bottom var(--yh-duration-base);
}

.yh-slider__button-wrapper {
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 24px;
  height: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
  cursor: grab;
  transition: left var(--yh-duration-base), bottom var(--yh-duration-base);
}
.yh-slider__button-wrapper:active {
  cursor: grabbing;
}
.yh-slider__button-wrapper.is-dragging {
  z-index: 11;
}

.yh-slider__button {
  width: var(--yh-slider-button-size);
  height: var(--yh-slider-button-size);
  border: var(--yh-slider-button-border) solid var(--yh-slider-main-color);
  background-color: var(--yh-bg-color);
  border-radius: 50%;
  transition: var(--yh-slider-transition);
  box-shadow: var(--yh-shadow-sm);
}
.yh-slider__button.is-hover {
  transform: scale(1.2);
  box-shadow: 0 0 0 6px rgba(var(--yh-slider-main-color-rgb, 64, 158, 255), 0.15);
}

.yh-slider__button.is-dragging {
  transform: scale(1.2);
  box-shadow: 0 0 0 6px rgba(var(--yh-slider-main-color-rgb, 64, 158, 255), 0.15);
}

.yh-slider__stop {
  position: absolute;
  width: 4px;
  height: 4px;
  background-color: var(--yh-bg-color);
  border-radius: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 1;
}

.yh-slider__mark-text {
  position: absolute;
  top: 15px;
  transform: translateX(-50%);
  font-size: var(--yh-font-size-base);
  color: var(--yh-text-color-secondary);
  margin-top: 10px;
}

.yh-slider__tooltip {
  position: absolute;
  bottom: calc(100% + 10px);
  left: 50%;
  transform: translateX(-50%);
  padding: 6px 10px;
  background: var(--yh-text-color-primary);
  backdrop-filter: blur(4px);
  color: var(--yh-bg-color);
  border-radius: var(--yh-radius-base);
  font-size: var(--yh-font-size-xs);
  white-space: nowrap;
  z-index: 20;
  box-shadow: var(--yh-shadow-md);
}

.yh-slider__tooltip-arrow {
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  border: 5px solid transparent;
  border-top-color: var(--yh-text-color-primary);
}

.yh-slider--large {
  --yh-slider-height: 48px;
  --yh-slider-runway-height: 10px;
  --yh-slider-button-size: 24px;
}

.yh-slider--small {
  --yh-slider-height: 24px;
  --yh-slider-runway-height: 4px;
  --yh-slider-button-size: 12px;
}

.yh-fade-enter-active,
.yh-fade-leave-active {
  transition: opacity 0.2s, transform 0.2s;
}

.yh-fade-enter-from,
.yh-fade-leave-to {
  opacity: 0;
  transform: translateX(-50%) translateY(5px);
}
</style>
