/**
 * Proper jQuery Validate Configuration
 * Add this BEFORE any form validation is initialized
 */

jQuery(document).ready(function ($) {

  // 1. Configure jQuery Validate defaults BEFORE initialization
  if (typeof $.validator !== 'undefined') {

    // Set global defaults
    $.validator.setDefaults({
      // Ignore elements that don't need validation
      ignore: [
        // Default WordPress ignores
        ':hidden',

        // Select2 specific
        '.select2-search__field',
        '.select2-hidden-accessible',

        // WordPress editor buttons
        '.ed_button',
        'input[type="button"].ed_button',

        // File upload plugins
        'input[type="file"][style*="opacity: 0"]',
        'input[type="file"][style*="position: absolute"]',
        '.plupload-html5',

        // Mapbox geocoder
        '.mapboxgl-ctrl-geocoder--input',

        // Other third-party
        '.mce-*',
        '.wp-editor-*'
      ].join(', '),

      // Don't validate on keyup for performance
      onkeyup: false,

      // Only validate on submit and blur
      onfocusout: function (element) {
        if ($(element).attr('name')) {
          this.element(element);
        }
      }
    });

    // 2. Override the elements() method to filter problematic inputs
    const originalElements = $.validator.prototype.elements;
    $.validator.prototype.elements = function () {
      const elements = originalElements.call(this);

      // Filter out elements without name attribute
      return elements.filter(function () {
        const $this = $(this);

        // Must have name attribute
        if (!$this.attr('name')) {
          return false;
        }

        // Skip if in ignore list
        const ignore = this.settings.ignore;
        if (ignore && $this.is(ignore)) {
          return false;
        }

        return true;
      }.bind(this));
    };
  }

  // 3. Suppress specific console warnings (last resort)
  function suppressValidationWarnings() {
    const originalError = console.error;
    const originalWarn = console.warn;

    console.error = function (...args) {
      const message = args.join(' ');
      if (!message.includes('has no name assigned')) {
        originalError.apply(console, args);
      }
    };

    console.warn = function (...args) {
      const message = args.join(' ');
      if (!message.includes('has no name assigned')) {
        originalWarn.apply(console, args);
      }
    };
  }

  // Enable warning suppression only if needed
  if (typeof window.SUPPRESS_VALIDATION_WARNINGS !== 'undefined' && window.SUPPRESS_VALIDATION_WARNINGS) {
    suppressValidationWarnings();
  }
});

/**
 * Enhanced form validation initialization
 */
function initializeFormValidation(formSelector) {
  jQuery(formSelector).each(function () {
    const $form = jQuery(this);

    // Skip if already validated
    if ($form.data('validator')) {
      return;
    }

    // Initialize with custom settings
    $form.validate({
      // Custom ignore selector for this form
      ignore: [
        ':hidden:not(.validate-hidden)',
        '.select2-search__field',
        '.ed_button',
        'input[type="file"][style*="opacity: 0"]',
        '.mapboxgl-ctrl-geocoder--input'
      ].join(', '),

      // Custom error placement
      errorPlacement: function (error, element) {
        // Handle different field types
        if (element.hasClass('select2-hidden-accessible')) {
          error.insertAfter(element.siblings('.select2'));
        } else {
          error.insertAfter(element);
        }
      },

      // Custom validation rules
      rules: {
        // Add your custom rules here
      },

      // Custom messages
      messages: {
        // Add your custom messages here
      }
    });
  });
}
