$(document).ready(function () {
  setTimeout(() => {
    $("input[data-input-type='combobox']").each(function () {
      const $input = $(this);
      const $container = $input.closest('.inail-combobox-input-container');
      const $options = $container.find('.inail-combobox-panel');
      const $optionElements = $options.find('.option');
      const $status = $container.closest('.combobox').find('#ariaOptionStatus');

      let currentFilter = '';
      let isKeyboardNavigation = false;
      let justSelected = false;

      // === Impostazioni ARIA sull'input ===
      $input.attr({
        "role": "combobox",
        "aria-autocomplete": "list",
        "aria-expanded": "false",
        "aria-controls": $options.attr("id"),
        "aria-haspopup": "listbox"
      });

      // === Impostazioni ARIA sul contenitore opzioni ===
      // $options.attr("role", "listbox");
      $optionElements.each(function (index) {
        $(this).attr({
          "role": "option",
          "id": "combo-option-" + index,
          "aria-selected": "false"
        });
      });

      function filterOptions(filter) {
        currentFilter = filter.toLowerCase();
        let hasMatches = false;

        $optionElements.each(function () {
          const $option = $(this);
          const isMatch = $option.text().toLowerCase().includes(currentFilter);
          $option.toggle(isMatch);
          hasMatches = hasMatches || isMatch;
        });

        $options.toggle(hasMatches && currentFilter !== '');
        $input.attr("aria-expanded", hasMatches && currentFilter !== '' ? "true" : "false");
        announceOptionsCount($optionElements.filter(':visible').length);
      }

      function announceOptionsCount(count) {
        if (!$status.length) return;
        $status.text('');
        setTimeout(() => {
          const message = count === 0
            ? 'Nessuna opzione disponibile'
            : `${count} opzion${count > 1 ? 'i' : 'e'} disponibil${count > 1 ? 'i' : 'e'}`;
          $status.text(message);
        }, 10);
      }

      function showAllOptions() {
        $optionElements.show();
        $options.show();
        $input.attr("aria-expanded", "true");
        announceOptionsCount($optionElements.length);
      }

      function setActiveOption($option) {
        $optionElements.attr("aria-selected", "false");
        $option.attr("aria-selected", "true");
        $input.attr("aria-activedescendant", $option.attr("id"));
        $option.focus();
      }

      $input.on('input', function () {
        filterOptions($(this).val());
      }).on('click', function () {
        showAllOptions();
      }).on('keydown', function (e) {
        if (e.key === 'ArrowDown') {
          e.preventDefault();
          isKeyboardNavigation = true;
          const $visible = $optionElements.filter(':visible');
          if ($visible.length) setActiveOption($visible.first());
        } else if (e.key === 'Enter') {
          e.preventDefault();
          showAllOptions();
        } else if (e.key === 'Escape') {
          $options.hide();
          $input.attr("aria-expanded", "false");
        } else if (e.key === 'Tab') {
          // Tab dall'input: chiude le opzioni
          $options.hide();
          $input.attr("aria-expanded", "false");
        }
      }).on('blur', function () {
        setTimeout(() => {
          if (!isKeyboardNavigation && !justSelected) {
            $options.hide();
            $input.attr("aria-expanded", "false");
          }
          justSelected = false;
        }, 150);
      });

      $optionElements.on('click', function () {
        justSelected = true;
        const val = $(this).text();
        $input.val(val).trigger("change").focus();
        $options.hide();
        $input.attr("aria-expanded", "false");
      }).on('keydown', function (e) {
        const $visible = $optionElements.filter(':visible');
        const currentIndex = $visible.index(this);

        if (e.key === 'Enter') {
          e.preventDefault();
          justSelected = true;
          const val = $(this).text();
          $input.val(val).trigger("change").focus();
          $options.hide();
          $input.attr("aria-expanded", "false");
        } else if (e.key === 'ArrowDown') {
          e.preventDefault();
          if (currentIndex + 1 < $visible.length) {
            setActiveOption($visible.eq(currentIndex + 1));
          }
        } else if (e.key === 'ArrowUp') {
          e.preventDefault();
          if (currentIndex <= 0) {
            $input.focus();
            $input.removeAttr("aria-activedescendant");
            $optionElements.attr("aria-selected", "false");
          } else {
            setActiveOption($visible.eq(currentIndex - 1));
          }
        } else if (e.key === 'Escape') {
          $input.focus();
          $options.hide();
          $input.attr("aria-expanded", "false");
        } else if (e.key === 'Tab') {
          // Tab dalle opzioni: chiude le opzioni
          $options.hide();
          $input.attr("aria-expanded", "false");
        }
      });

      $options.on('mouseenter', () => isKeyboardNavigation = false)
        .on('keydown', () => isKeyboardNavigation = true);
    });
  }, 0);
});