/**
 * Modern JavaScript - ES6+ only, no polyfills needed
 * Requires modern browsers (Chrome 90+, Firefox 88+, Safari 14+, Edge 90+)
 */

// Site initialization as ES6 module
export function initSite() {
  initNavigation();
  initLazyLoading();
  initHubSpotForms();
  initAnimations();
  initDarkMode();
}

/**
 * Modern Navigation using ES6 features
 */
function initNavigation() {
  const nav = document.querySelector('.site-nav');
  if (!nav) return;
  
  // Use optional chaining and nullish coalescing
  const toggle = nav.querySelector('.menu-toggle');
  const menu = nav.querySelector('.nav-menu');
  const isOpen = localStorage.getItem('menu-state') ?? 'closed';
  
  // Arrow functions and template literals
  toggle?.addEventListener('click', () => {
    const newState = menu.classList.toggle('open') ? 'open' : 'closed';
    localStorage.setItem('menu-state', newState);
    
    // Animate with Web Animations API
    menu.animate([
      { transform: 'translateX(-100%)', opacity: 0 },
      { transform: 'translateX(0)', opacity: 1 }
    ], {
      duration: 300,
      easing: 'cubic-bezier(0.4, 0, 0.2, 1)'
    });
  });
  
  // Keyboard navigation with destructuring
  nav.addEventListener('keydown', ({ key, target }) => {
    if (key === 'Escape') {
      menu.classList.remove('open');
    }
  });
}

/**
 * Native lazy loading with Intersection Observer
 */
function initLazyLoading() {
  // Use native lazy loading for images
  const images = document.querySelectorAll('img[data-src]');
  
  if ('IntersectionObserver' in window) {
    const imageObserver = new IntersectionObserver((entries) => {
      for (const entry of entries) {
        if (entry.isIntersecting) {
          const img = entry.target;
          img.src = img.dataset.src;
          img.removeAttribute('data-src');
          imageObserver.unobserve(img);
          
          // Use CSS custom properties for loading animation
          img.style.setProperty('--loading-progress', '100%');
        }
      }
    }, {
      rootMargin: '50px',
      threshold: 0.01
    });
    
    images.forEach(img => imageObserver.observe(img));
  }
  
  // Lazy load videos
  const videos = document.querySelectorAll('video[data-src]');
  videos.forEach(video => {
    if ('IntersectionObserver' in window) {
      const videoObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            video.src = video.dataset.src;
            video.load();
            videoObserver.unobserve(video);
          }
        });
      });
      videoObserver.observe(video);
    }
  });
}

/**
 * HubSpot Forms Enhancement with modern features
 */
function initHubSpotForms() {
  // Listen for HubSpot form events
  window.addEventListener('message', (event) => {
    if (event.data.type === 'hsFormCallback') {
      const { eventName, data } = event.data;
      
      switch(eventName) {
        case 'onFormReady':
          enhanceHubSpotForm(data.formId);
          break;
        case 'onFormSubmit':
          handleFormSubmit(data);
          break;
        case 'onFormSubmitted':
          handleFormSuccess(data);
          break;
      }
    }
  });
  
  // Enhance existing HubSpot forms on page
  const forms = document.querySelectorAll('.hs-form');
  forms.forEach(enhanceHubSpotForm);
}

/**
 * Enhance HubSpot form with modern features
 */
function enhanceHubSpotForm(formIdOrElement) {
  const form = typeof formIdOrElement === 'string' 
    ? document.querySelector(`#hsForm_${formIdOrElement}`)
    : formIdOrElement;
    
  if (!form) return;
  
  // Add modern CSS classes
  form.classList.add('modern-form');
  
  // Enhance form fields with modern attributes
  const inputs = form.querySelectorAll('input, textarea, select');
  inputs.forEach(input => {
    // Add modern HTML5 attributes based on field type
    const fieldName = input.name?.toLowerCase() || '';
    
    if (fieldName.includes('email')) {
      input.type = 'email';
      input.autocomplete = 'email';
    } else if (fieldName.includes('phone')) {
      input.type = 'tel';
      input.autocomplete = 'tel';
    } else if (fieldName.includes('url') || fieldName.includes('website')) {
      input.type = 'url';
      input.autocomplete = 'url';
    }
    
    // Add floating labels effect
    if (input.placeholder) {
      const wrapper = input.parentElement;
      wrapper.classList.add('field-wrapper');
      
      input.addEventListener('focus', () => wrapper.classList.add('focused'));
      input.addEventListener('blur', () => {
        if (!input.value) wrapper.classList.remove('focused');
      });
    }
    
    // Real-time validation feedback
    input.addEventListener('input', () => {
      if (input.validity.valid) {
        input.classList.add('valid');
        input.classList.remove('invalid');
      } else if (input.value) {
        input.classList.add('invalid');
        input.classList.remove('valid');
      }
    });
  });
  
  // Add progress indicator for multi-step forms
  const fieldsets = form.querySelectorAll('fieldset');
  if (fieldsets.length > 1) {
    createFormProgress(form, fieldsets);
  }
}

/**
 * Create progress indicator for multi-step forms
 */
function createFormProgress(form, fieldsets) {
  const progress = document.createElement('div');
  progress.className = 'form-progress';
  progress.innerHTML = `
    <div class="progress-bar">
      <div class="progress-fill" style="--progress: ${100 / fieldsets.length}%"></div>
    </div>
    <div class="progress-steps">
      ${Array.from(fieldsets).map((_, i) => 
        `<span class="step ${i === 0 ? 'active' : ''}">${i + 1}</span>`
      ).join('')}
    </div>
  `;
  form.prepend(progress);
}

/**
 * Handle form submission
 */
async function handleFormSubmit(data) {
  // Show loading state
  const submitBtn = document.querySelector(`#hsForm_${data.formId} input[type="submit"]`);
  if (submitBtn) {
    submitBtn.disabled = true;
    submitBtn.dataset.originalText = submitBtn.value;
    submitBtn.value = 'Sending...';
    
    // Add loading animation
    submitBtn.classList.add('loading');
  }
}

/**
 * Handle form success
 */
function handleFormSuccess(data) {
  // Success animation
  const form = document.querySelector(`#hsForm_${data.formId}`);
  if (form) {
    form.animate([
      { transform: 'scale(1)', opacity: 1 },
      { transform: 'scale(0.95)', opacity: 0.5 },
      { transform: 'scale(1)', opacity: 1 }
    ], {
      duration: 500,
      easing: 'ease-out'
    });
  }
  
  // Track conversion if GTM is available
  if (window.dataLayer) {
    window.dataLayer.push({
      event: 'form_submitted',
      formId: data.formId,
      formGuid: data.formGuid
    });
  }
}

/**
 * Modern animations using Web Animations API
 */
function initAnimations() {
  // Animate elements on scroll
  const animateOnScroll = document.querySelectorAll('[data-animate]');
  
  if ('IntersectionObserver' in window) {
    const animationObserver = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const element = entry.target;
          const animation = element.dataset.animate;
          
          // Use Web Animations API
          const animations = {
            fadeIn: [
              { opacity: 0, transform: 'translateY(20px)' },
              { opacity: 1, transform: 'translateY(0)' }
            ],
            slideIn: [
              { transform: 'translateX(-100%)' },
              { transform: 'translateX(0)' }
            ],
            zoomIn: [
              { transform: 'scale(0.8)', opacity: 0 },
              { transform: 'scale(1)', opacity: 1 }
            ]
          };
          
          element.animate(animations[animation] || animations.fadeIn, {
            duration: 600,
            easing: 'cubic-bezier(0.4, 0, 0.2, 1)',
            fill: 'forwards'
          });
          
          animationObserver.unobserve(element);
        }
      });
    }, {
      threshold: 0.1
    });
    
    animateOnScroll.forEach(el => animationObserver.observe(el));
  }
}

/**
 * Tracks system dark mode preference on data-theme for any JS that needs to read it.
 * CSS dark mode is handled entirely by @media (prefers-color-scheme: dark).
 */
function initDarkMode() {
  const prefersDark = window.matchMedia('(prefers-color-scheme: dark)');
  document.documentElement.dataset.theme = prefersDark.matches ? 'dark' : 'light';
  prefersDark.addEventListener('change', (e) => {
    document.documentElement.dataset.theme = e.matches ? 'dark' : 'light';
  });
}


// Export additional utilities
export const utils = {
  // Modern fetch wrapper with timeout
  async fetchWithTimeout(url, options = {}, timeout = 5000) {
    const controller = new AbortController();
    const id = setTimeout(() => controller.abort(), timeout);
    
    try {
      const response = await fetch(url, {
        ...options,
        signal: controller.signal
      });
      clearTimeout(id);
      return response;
    } catch (error) {
      clearTimeout(id);
      throw error;
    }
  },
  
  // Debounce function using modern syntax
  debounce(func, wait) {
    let timeout;
    return (...args) => {
      clearTimeout(timeout);
      timeout = setTimeout(() => func.apply(this, args), wait);
    };
  },
  
  // Format currency using Intl API
  formatCurrency(amount, currency = 'USD') {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency
    }).format(amount);
  },
  
  // Format date using Intl API
  formatDate(date, options = {}) {
    return new Intl.DateTimeFormat('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      ...options
    }).format(new Date(date));
  }
};

// Auto-initialize when imported
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initSite);
} else {
  initSite();
}


