<template>
  <div class="slider-wrapper">
    <div
      class="track-container"
      ref="trackRef"
      @mousedown.prevent="handleTrackDown"
      @touchstart.prevent="handleTrackDown"
    >
      <div class="track-bg"></div>

      <div
        class="track-fill"
        :style="{ width: percentage + '%', backgroundColor: color }"
      ></div>

      <div class="thumb anchor-thumb" :style="{ borderColor: color }"></div>

      <div
        class="thumb drag-thumb"
        :style="{ left: percentage + '%', borderColor: color }"
      ></div>
    </div>

    <div class="ticks">
      <span
        v-for="(mark, i) in marks"
        :key="i"
        class="tick-label"
        :style="{ left: (i / (marks.length - 1)) * 100 + '%' }"
      >
        {{ mark }}x
      </span>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onUnmounted } from 'vue';

const props = defineProps({
  modelValue: { type: Number, default: 10 },
  color: { type: String, default: '#f6465d' },
  // 固定阶梯
  marks: {
    type: Array,
    default: () => [10, 50, 100, 500, 1000]
  }
});

const emit = defineEmits(['update:modelValue']);

const trackRef = ref(null);
const isDragging = ref(false);

// === 核心 1: 根据当前数值，反推在轨道上的百分比位置 ===
const percentage = computed(() => {
  const currentVal = props.modelValue;
  const list = props.marks;

  // 找到当前数值对应数组里的第几个 (Index)
  // 如果数值不在数组里(比如初始传入了11)，则找最近的一个
  let closestIndex = 0;
  let minDiff = Infinity;

  list.forEach((val, index) => {
    const diff = Math.abs(val - currentVal);
    if (diff < minDiff) {
      minDiff = diff;
      closestIndex = index;
    }
  });

  // 比如有5个点，索引是0-4。第2个点位置就是 2/4 = 50%
  return (closestIndex / (list.length - 1)) * 100;
});

const getClientX = (event) => {
  if (event.touches && event.touches.length > 0) {
    return event.touches[0].clientX;
  }
  return event.clientX;
};

// === 核心 2: 根据点击位置，吸附到最近的刻度 ===
const updateValueByPosition = (clientX) => {
  if (!trackRef.value) return;

  const rect = trackRef.value.getBoundingClientRect();
  const width = rect.width;
  let offsetX = clientX - rect.left;

  // 限制范围
  if (offsetX < 0) offsetX = 0;
  if (offsetX > width) offsetX = width;

  // 计算当前触摸点占总长度的比例 (0.0 - 1.0)
  const ratio = offsetX / width;

  // 总段数 (比如5个点就是4段)
  const segments = props.marks.length - 1;

  // 四舍五入找到最近的索引
  // 例如 ratio = 0.6，segments = 4 => 2.4 => round => 2 (即第3个点)
  const targetIndex = Math.round(ratio * segments);

  // 取出对应的值
  const newValue = props.marks[targetIndex];

  // 如果变了才发送更新
  if (newValue !== props.modelValue) {
    emit('update:modelValue', newValue);
  }
};

const handleTrackDown = (e) => {
  isDragging.value = true;
  updateValueByPosition(getClientX(e));
  document.addEventListener('mousemove', onDrag);
  document.addEventListener('mouseup', stopDrag);
  document.addEventListener('touchmove', onDrag, { passive: false });
  document.addEventListener('touchend', stopDrag);
};

const onDrag = (e) => {
  if (!isDragging.value) return;
  if (e.type === 'touchmove') e.preventDefault();
  updateValueByPosition(getClientX(e));
};

const stopDrag = () => {
  isDragging.value = false;
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
  document.removeEventListener('touchmove', onDrag);
  document.removeEventListener('touchend', stopDrag);
};

onUnmounted(() => stopDrag());
</script>

<style scoped>
/* 样式保持不变，复用之前的优美样式 */
.slider-wrapper {
  padding: 15px 0;
  width: 100%;
  touch-action: none;
  position: relative;
  margin-bottom: 10px;
}

.track-container {
  position: relative;
  height: 8px;
  width: 100%;
  cursor: pointer;
  padding: 10px 0;
  margin-top: -10px;
  margin-bottom: -10px;
}

.track-bg {
  position: absolute;
  top: 50%; transform: translateY(-50%);
  width: 100%; height: 8px;
  background: #f5f5f5;
  border-radius: 4px;
}

.track-fill {
  position: absolute;
  top: 50%; transform: translateY(-50%);
  height: 8px;
  border-radius: 4px 0 0 4px;
  pointer-events: none;
  transition: width 0.1s; /* 增加一点过渡动画，让吸附效果更平滑 */
}

.thumb {
  position: absolute;
  top: 50%; transform: translate(-50%, -50%);
  width: 26px; height: 26px;
  background: #fff;
  border: 2px solid;
  border-radius: 50%;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  z-index: 2;
  pointer-events: none;
  box-sizing: border-box;
  transition: left 0.1s; /* 增加一点过渡动画 */
}

.anchor-thumb { left: 0%; z-index: 1; }

.ticks {
  position: relative;
  width: 100%;
  height: 20px;
  margin-top: 15px;
}

.tick-label {
  position: absolute;
  transform: translateX(-50%);
  color: #5e6673;
  font-size: 12px;
  white-space: nowrap;
}

.tick-label:first-child { transform: translateX(0); }
.tick-label:last-child { transform: translateX(-100%); }
</style>