<template>
  <OptionTemplate :name="model.name" :required="model.required">
    <select
        :name="`option-${model.product_option_id}`"
        class="select"
        @change="onChange"
    >
      <option value="" disabled selected>Выберите значение</option>
      <option
          v-for="value in model.product_option_value"
          :key="value.product_option_value_id"
          :value="value.product_option_value_id"
          :selected="value.selected"
      >
        {{ value.name }}<span v-if="value.price"> ({{ value.price_prefix }}{{ value.price }})</span>
      </option>
    </select>
  </OptionTemplate>
</template>

<script setup>
import OptionTemplate from "./OptionTemplate.vue";

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

function onChange(event) {
  const selectedId = Number(event.target.value);

  model.value.product_option_value.forEach(value => {
    value.selected = (value.product_option_value_id === selectedId);
  });

  model.value.value = model.value.product_option_value.find(value => value.product_option_value_id === selectedId);

  emit('update:modelValue', model.value);
}
</script>
