<script setup lang="ts">
import type { UiSelectOption } from '../contracts'
const props = withDefaults(defineProps<{ modelValue?: Array<string | number | boolean | null>; options: UiSelectOption[]; label?: string; disabled?: boolean; required?: boolean }>(), { modelValue: () => [] })
const emit = defineEmits<{ 'update:modelValue': [value: Array<string | number | boolean | null>] }>()
function update(event: Event): void {
  const selected = Array.from((event.target as HTMLSelectElement).selectedOptions).map(x => {
    const option = props.options[Number(x.value)]
    return option?.value ?? null
  })
  emit('update:modelValue', selected)
}
</script>
<template>
  <label class="ks-field"><span v-if="label">{{ label }}<b v-if="required" aria-hidden="true"> *</b></span>
    <select multiple :disabled="disabled" :required="required" @change="update">
      <option v-for="(option, index) in options" :key="`${index}:${option.label}`" :value="index" :disabled="option.disabled" :selected="modelValue.includes(option.value)">{{ option.label }}</option>
    </select>
  </label>
</template>
