/* Forms-specific JavaScript - Loaded only on pages with forms */
(function() {
  'use strict';
  
  // Lazy load form functionality when form is in viewport
  if ('IntersectionObserver' in window) {
    const forms = document.querySelectorAll('form');
    
    if (forms.length === 0) return;
    
    const formObserver = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          initializeForm(entry.target);
          formObserver.unobserve(entry.target);
        }
      });
    });
    
    forms.forEach(form => formObserver.observe(form));
  } else {
    // Fallback
    document.addEventListener('DOMContentLoaded', () => {
      document.querySelectorAll('form').forEach(initializeForm);
    });
  }
  
  function initializeForm(form) {
    // Email subscription form optimization
    const emailGlobalUnsub = form.querySelector('input[name="globalunsub"]');
    
    if (emailGlobalUnsub) {
      emailGlobalUnsub.addEventListener('change', function() {
        const emailSubItems = form.querySelectorAll('#email-prefs-form .item');
        
        requestAnimationFrame(() => {
          emailSubItems.forEach(item => {
            const input = item.querySelector('input');
            
            if (this.checked) {
              item.classList.add('disabled');
              input.setAttribute('disabled', 'disabled');
              input.checked = false;
            } else {
              item.classList.remove('disabled');
              input.removeAttribute('disabled');
            }
          });
        });
      }, { passive: true });
    }
    
    // Form validation optimization
    const inputs = form.querySelectorAll('input, textarea, select');
    
    inputs.forEach(input => {
      // Debounce validation for better performance
      let validationTimeout;
      
      input.addEventListener('blur', function() {
        clearTimeout(validationTimeout);
        validationTimeout = setTimeout(() => {
          validateField(this);
        }, 300);
      }, { passive: true });
    });
  }
  
  function validateField(field) {
    // Add your validation logic here
    if (field.hasAttribute('required') && !field.value.trim()) {
      field.classList.add('error');
    } else {
      field.classList.remove('error');
    }
  }
})();