function updateValues() {
  $('input[name=starter_kit_product]').attr('value', $.map($('#starter_kit-product input'), element => element.value).join());
}

$(document).ready(function() {
  const INPUT = $('input[name=product]');
  INPUT.autocomplete({
    delay: 500,
    source: function(request, response) {
      $.ajax({
        url:
          'index.php?route=catalog/product/autocomplete&token=' +
          TOKEN +
          '&filter_name=' +
          encodeURIComponent(request.term) +
          '&filter_grade=0',
        dataType: 'json',
        success: function(json) {
          response(
            $.map(json, function(item) {
              return {
                label: item.name,
                value: item.product_id,
              };
            })
          );
        },
      });
    },
    select: function(event, ui) {
      if ($('#starter_kit-product' + ui.item.value).length > 0) {
        alert('Este produto já foi adicionado a lista!');
        return false;
      }

      let container = $('#starter_kit-product');
      container.append(`
        <div id="starter_kit-product${ui.item.value}" class="scrollbox-item flex between-xs">
          <span class="text-small text-dark">${ui.item.label}</span>
          <i class="fas fa-trash-alt text-small right-margin-small text-error cursor-pointer"></i>
          <input type="hidden" value="${ui.item.value}">
        </div>
      `);
      container.scrollTop(2000);

      updateValues();

      return false;
    },
    focus: function(event, ui) {
      return false;
    },
    closeOnSelect: false,
  });

  $('#starter_kit-product').on('click', 'i', function() {
    $(this)
      .parent()
      .remove();
    updateValues();
  });
});
