$('.main-delivery').on('change', '[data-delivery-seller-input]', function(e) {
   $('[data-opener="[data-ordering-sellers]"]').click();
});

$('body').on('click update', '[data-custom-opener]', function(e) {
   let $this = $(e.currentTarget),
      $target = $($this.data('custom-opener')),
      checked = $this.is('.active');

   if (e.type != 'update')
      checked = !checked;

   $target[checked ? 'slideDown' : 'slideUp']()[checked ? 'addClass' : 'removeClass']('active').trigger('opened');
   $this[checked ? 'addClass' : 'removeClass']('active');

   return !$this.is('a');
}).find('[data-custom-opener]').trigger('update');

jQuery.expr[':'].icontains = function(a, i, m) {
   return jQuery(a).text().toLowerCase()
      .indexOf(m[3].toLowerCase()) >= 0;
};


const normalizeString = (str) => {
   return str
      .normalize("NFD")
      .replace(/[\u0300-\u036f]/g, "")
      .toLowerCase();
};

// sellers search
$('body').on('keyup change', '[data-seller-search-input]', function(e) {
   const identifier = $(this).data('seller-search-input');
   const $sellers_list = $('[data-seller-list="' + identifier + '"]');
   const $seller_not_found = $('[data-seller-not-found="' + identifier + '"]');
   const pattern = normalizeString($(this).val());

   wpj.domUtils.resetTimer('sellers-search', 200, function() {
      if (pattern) {
         $sellers_list.addClass('searching');
         $sellers_list.find('.seller-row').hide().filter(function() {
            const sellerTitle = normalizeString($(this).text());
            return sellerTitle.includes(pattern);
         }).css('display', 'flex');

         if ($sellers_list.find('.seller-row:visible').length) {
            $seller_not_found.hide();
         } else {
            $seller_not_found.show();
         }
      } else {
         $sellers_list.removeClass('searching');
         $sellers_list.find('.seller-row').css('display', 'flex');
         $seller_not_found.hide();
      }
   });
});
