/**
 * Client-side Email Validation Helper
 * Provides live validation feedback for email inputs using the browser's built-in validation API, as opposed to only seeing feedback on submission.
 * NOTE: NOT REALLY WORKING RIGHT NOW, BUT WAS GOOD IN 3047 SO REUSABLE HERE.
 */
(function(){
  function wireEmailLiveValidation(root){
    const inputs = root.querySelectorAll('input[type="email"]');
    inputs.forEach(function(input){
      const container = input.closest('.form-floating, .mb-3, .form-group') || input.parentElement;
      if(!container) return;
      
      let feedback = container.querySelector('.invalid-feedback');
      if(!feedback){
        feedback = document.createElement('div');
        feedback.className = 'invalid-feedback';
        container.appendChild(feedback);
      }
      
      const update = function(){
        // Use the browser's native validation message 
        const msg = input.validationMessage || '';
        if (input.value === '' && !input.required) {
          input.classList.remove('is-invalid');
          // Do not show when optional and empty
          feedback.textContent = '';
          return;
        }
        if (!input.checkValidity()){
          input.classList.add('is-invalid');
          feedback.textContent = msg;
        } else {
          input.classList.remove('is-invalid');
          // Only clear messages from this helper function, not any plugin generated ones.
          if (feedback.dataset.server !== '1') {
            feedback.textContent = '';
          }
        }
      };
      
      input.addEventListener('input', update);
      input.addEventListener('blur', update);
      
      // Initialize on load so current value is reflected
      update();
    });
  }
  
  // Ensure DOM is ready before running
  if (document.readyState === 'loading'){
    document.addEventListener('DOMContentLoaded', function(){ 
      wireEmailLiveValidation(document); 
    });
  } else {
    wireEmailLiveValidation(document);
  }
})();
