<template>
  <div class="bg-[#f3f9ff] p-[4px_7px] flex items-center rounded-[8px]">
    <van-icon name="minus" size="24" color="#D1D1D1" @click="decrease" />
    <span class="max-w-[40px] text-center text-[14px] font-medium text-black ml-[4px] mr-[4px]">
      {{ value }} {{ unit }}
    </span>
    <van-icon name="plus" size="24" color="#198CFF" @click="increase" />
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from "vue";

// Props
const props = defineProps({
  modelValue: {
    type: Number,
    default: 1,
  },
  min: {
    type: Number,
    default: 1,
  },
  max: {
    type: Number,
    default: 100,
  },
  unit: {
    type: String,
    default: "",
  },
});

// Emit
const emit = defineEmits(["update:modelValue", "decrease", "increase"]);

// Local state
const value = ref(props.modelValue);

// 监听外部值变化，同步更新本地状态
watch(
  () => props.modelValue,
  (newValue) => {
    value.value = newValue;
  },
  { immediate: true },
);

// Methods
const decrease = () => {
  if (value.value === 1) return;

  if (value.value > props.min) {
    value.value--;
    emit("update:modelValue", value.value);
    emit("decrease");
  }
};

const increase = () => {
  if (value.value < props.max) {
    value.value++;
    emit("update:modelValue", value.value);
    emit("increase");
  }
};
</script>
