/**
 * AUX Search Filters Reset Handler
 *
 * Handle custom reset functionality for filter forms on search/filter pages.
 * Prevent default browser reset behavior and manually reset form fields to
 * ensure proper state management for checkboxes, radio buttons, and select elements.
 *
 * This script is conditionally enqueued on search results pages. Loaded by
 * HeadService::enqueueLocalScript() in the SearchService::prepareHooks() method,
 * which is called from WP_AUX::init(). The script is only enqueued when
 * is_search() and is_main_query() conditions are met.
 *
 * The script expects filter forms with the class "filters" containing reset
 * buttons or inputs. It targets elements matching the selector:
 * '.filters form input[type="reset"], .filters form button[type="reset"]'
 *
 * @see \WP_AUX\Services\SearchService::prepareHooks()
 * @see \WP_AUX\Services\HeadService::enqueueLocalScript()
 * @since 1.0.0
 */

(function(){
  // Find all reset buttons and inputs within filter forms
  let $resets = document.querySelectorAll('.filters form input[type="reset"], .filters form button[type="reset"]');

  if ($resets) {
    // Attach click event listener to each reset element
    $resets.forEach(function($reset) {
      $reset.addEventListener('click', function(e) {
        // Prevent default browser reset behavior
        e.preventDefault();

        // Get the parent form element
        let $form = $reset.closest('form');

        // Find all checked radio buttons, checked checkboxes, and select elements
        let $fields = $form.querySelectorAll('input[type="radio"]:checked, input[type="checkbox"]:checked, select');

        // Reset each field to its default state
        $fields.forEach(function($field) {
          if ($field.type === 'checkbox' || $field.type === 'radio') {
            // Uncheck checkbox and radio inputs
            $field.checked = false;
            $field.removeAttribute('checked');
          } else {
            // Reset select elements to first option (index 0)
            $field.selectedIndex = 0;
          }
        })
      })
    })
  }
})();
