<template>
  <div>
    <OptionTemplate :name="model.name" :required="model.required">
      <div class="flex flex-wrap gap-2">
        <label
            v-for="value in model.product_option_value"
            class="group relative flex items-center justify-center btn btn-soft btn-secondary btn-sm"
            :class="value.selected ? 'btn-active' : ''"
        >
          <input
              type="checkbox"
              :value="value.product_option_value_id"
              :checked="value.selected"
              @change="select(value)"
              class="absolute inset-0 appearance-none focus:outline-none disabled:cursor-not-allowed"
          />

          <span class="text-xs font-medium group-has-checked:text-white">
            {{ value.name }}<span v-if="value.price"> ({{ value.price_prefix }}{{ value.price }})</span>
          </span>
        </label>
      </div>
    </OptionTemplate>
  </div>
</template>

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

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

function select(toggledValue) {
  model.value.product_option_value.forEach(value => {
    if (value === toggledValue) {
      value.selected = !value.selected;
    }
  });

  model.value.value = model.value.product_option_value.filter(item => item.selected === true);

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