<template>
  <div class="input-with-unit">
    <input
      v-if="showRange"
      type="range"
      :value="modelValue.value"
      :min="min"
      :max="max"
      :step="step"
      @input="updateValue(Number($event.target.value))"
    />
    <input
      type="number"
      :value="modelValue.value"
      :min="min"
      :max="max"
      :step="step"
      class="size-input"
      @input="updateValue(Number($event.target.value))"
    />
    <UnitToggle
      :modelValue="modelValue.unit"
      :units="units"
      @update:modelValue="updateUnit"
    />
    <slot name="after" />
  </div>
</template>

<script setup>
import UnitToggle from './UnitToggle.vue';

const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
    validator: (v) => 'value' in v && 'unit' in v
  },
  units: {
    type: Array,
    default: () => ['mm', 'px']
  },
  min: {
    type: Number,
    default: 0
  },
  max: {
    type: Number,
    default: 100
  },
  step: {
    type: Number,
    default: 1
  },
  showRange: {
    type: Boolean,
    default: false
  }
});

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

const updateValue = (value) => {
  emit('update:modelValue', { ...props.modelValue, value });
};

const updateUnit = (unit) => {
  emit('update:modelValue', { ...props.modelValue, unit });
};
</script>
