(function (Drupal, drupalSettings) {
  Drupal.behaviors.MediaLibraryResetFilters = {
    attach: function (context) {
      const resetLink = once('acquia-dam-clear-filter', '.acquia-dam-clear-filter', context).shift();
      const form = document.getElementById('views-exposed-form-acquia-dam-asset-library-widget') ||
                   document.getElementById('views-exposed-form-acquia-dam-asset-library-widget-table');
      const formSubmit = form ? form.querySelector('.form-submit') : null;

      function handleUrlModification(settings) {
        let decodedUrl = decodeURIComponent(settings.url);
        let url = new URL(decodedUrl, window.location.origin);
        let params = new URLSearchParams(url.search);

        const inputs = form ? form.elements : [];
        const selectedOptions = {};

        for (let i = 0; i < inputs.length; i++) {
          if (inputs[i].tagName === 'SELECT' && inputs[i].multiple) {
            selectedOptions[inputs[i].name] = Array.from(inputs[i].selectedOptions).map(option => option.value);
          }
        }

        Object.keys(selectedOptions).forEach(key => {
          const cleanKey = key.replace(/\[]$/, '');
          Array.from(params.keys()).forEach(paramKey => {
            if (paramKey.startsWith(cleanKey)) {
              params.delete(paramKey);
            }
          });
        });

        Object.entries(selectedOptions).forEach(([key, values]) => {
          const cleanKey = key.replace(/\[]$/, '');
          values.forEach((value, index) => {
            params.append(`${cleanKey}[${index}]`, value);
          });
        });

        url.search = params.toString();
        settings.url = url.toString();
      }

      function resetFormFilters(form) {
        const resetFilters = [];
        const inputs = form ? form.elements : [];
        for (let i = 0; i < inputs.length; i++) {
          const input = inputs[i];
          if (input.tagName === 'INPUT') {
            if (['text', 'textarea', 'select', 'hidden'].includes(input.type)) {
              input.value = '';
            } else if (['radio', 'checkbox'].includes(input.type)) {
              input.checked = false;
            }
          } else if (input.tagName === 'SELECT') {
            if (input.name.endsWith('[]')) {
              input.name = input.name.replace(/\[]$/, '');
            }
            resetFilters.push(input.name);
            if (input.multiple) {
              // Clear all selected options for multi-select
              for (let j = 0; j < input.options.length; j++) {
                input.options[j].selected = false;
              }
            } else {
              input.selectedIndex = 0;
            }
          }
        }
        return resetFilters;
      }

      function handleAjaxSendForReset(resetFilters, triggerButton) {
        return function (event, jqXHR, settings) {
          let decodedUrl = decodeURIComponent(settings.url);
          let url = new URL(decodedUrl, window.location.origin);
          let params = new URLSearchParams(url.search);

          resetFilters.forEach(filter => {
            params.delete(filter);
          });

          url.search = params.toString();
          settings.url = url.toString();
        };
      }

      if (resetLink && form) {
        resetLink.addEventListener('click', function (e) {
          e.preventDefault();
          const resetFilters = resetFormFilters(form);

          const ajaxSendHandler = handleAjaxSendForReset(resetFilters, e.currentTarget);
          jQuery(document).one('ajaxSend', ajaxSendHandler);

          const applyBtn = form.querySelector("input[id*=edit-submit-acquia-dam-asset-library]");
          if (applyBtn) applyBtn.click();
        });
      }

      if (formSubmit && form) {
        formSubmit.addEventListener('click', function (e) {
          e.preventDefault();
          jQuery(document).one('ajaxSend', function (event, jqXHR, settings) {
            handleUrlModification(settings);
          });

          const applyBtn = form.querySelector("input[id*=edit-submit-acquia-dam-asset-library]");
          if (applyBtn) applyBtn.click();
        });
      }
    }
  };
})(Drupal, drupalSettings);
