<template>
  <div>
    <input
      type="search"
      name="category"
      :value="`${category?.name}`"
      placeholder="Начните вводить название категории..."
      class="form-control"
      ref="categoryRef"
    />
  </div>
</template>

<script setup>
import {onMounted, onUnmounted, ref} from "vue";

const category = defineModel();
const categoryRef = ref(null);

onMounted(() => {
  const input = categoryRef.value;
  if (!input) {
    return;
  }

  $(input).autocomplete({
    'source': function (request, response) {
      if ($(input).val().length === 0) {
        $(input).val(null);
      }

      $.ajax({
        url: `index.php?route=catalog/category/autocomplete&user_token=${window.TeleCart.user_token}&filter_name=` + encodeURIComponent(request),
        dataType: 'json',
        success: function (json) {
          response($.map(json, function (item) {
            return {
              label: item['name'],
              value: item['category_id']
            }
          }));
        }
      });
    },
    'select': function (item) {
      category.value = {
        category_id: Number(item['value']),
        name: item['label'],
      };
    }
  });
});

onUnmounted(() => {
  const input = categoryRef.value;
  if (!input) {
    return;
  }

  $(input).autocomplete('destroy');
});
</script>

<style scoped lang="scss">

</style>
