<template>
  <select ref="$el" />
</template>

<script setup>
import { onMounted, onUnmounted, ref, watch } from 'vue';
import 'select2/dist/js/select2.min';
import $ from 'jquery';

const props = defineProps({
  modelValue: {},

  options: {
    type: Array,
    required: true,
  },

  modelValue: {
    type: [Number, String],
    required: true,
  },

  config: {
    type: Object,
    default: () => ({}),
  },
});
const emit = defineEmits(['update:modelValue']);

const $el = ref(null);

onMounted(() => {
  $($el.value)
    .select2({ ...props.config, data: props.options })
    .val(props.modelValue)
    .trigger('change')
    .on('change', (event) => {
      emit('update:modelValue', event.target.value);
    });
});

onUnmounted(() => {
  $($el.value)
    .off()
    .select2('destroy');
});

watch(() => props.options, (value) => {
  $($el.value)
    .empty().select2({ data: value });
});

watch(() => props.modelValue, (value) => {
  $($el.value)
    .val(value)
    .trigger('change');
});
</script>

<style lang="scss">
@import '~select2/dist/css/select2.min.css';

.select2 {
  &-selection {
    height: 2.4375rem !important;
    border-radius: 0 !important;
    border: 1px solid #cacaca !important;

    &__rendered {
      padding: .5rem;
      font-size: 1rem !important;
      line-height: 1.5 !important;
    }

    &__arrow {
      height: 2.4375rem !important;
      top: 0;
    }
  }
}
</style>
