/* Optimized Main JavaScript - Core functionality only */
(function() {
  'use strict';
  
  // Performance monitoring
  if ('performance' in window && 'PerformanceObserver' in window) {
    // Monitor Largest Contentful Paint
    try {
      const lcpObserver = new PerformanceObserver((list) => {
        const entries = list.getEntries();
        const lastEntry = entries[entries.length - 1];
        console.log('LCP:', lastEntry.renderTime || lastEntry.loadTime);
      });
      lcpObserver.observe({ entryTypes: ['largest-contentful-paint'] });
    } catch (e) {
      // PerformanceObserver not supported
    }
  }
  
  // Lazy load images that don't have native lazy loading
  if ('IntersectionObserver' in window) {
    const images = document.querySelectorAll('img:not([loading="lazy"])');
    const imageObserver = new IntersectionObserver((entries, observer) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const img = entry.target;
          if (img.dataset.src) {
            img.src = img.dataset.src;
            img.removeAttribute('data-src');
          }
          observer.unobserve(img);
        }
      });
    }, {
      rootMargin: '50px 0px',
      threshold: 0.01
    });
    
    images.forEach(img => imageObserver.observe(img));
  }
  
  // Optimize scroll performance
  let ticking = false;
  function requestTick() {
    if (!ticking) {
      window.requestAnimationFrame(updateScrollPosition);
      ticking = true;
    }
  }
  
  function updateScrollPosition() {
    // Add scroll-based functionality here if needed
    ticking = false;
  }
  
  // Use passive event listeners for better scroll performance
  window.addEventListener('scroll', requestTick, { passive: true });
  
  // Dynamically load component JavaScript based on page content
  function loadComponentScripts() {
    // Load header script if header exists
    if (document.querySelector('.header')) {
      const headerScript = document.createElement('script');
      headerScript.src = '{{ get_asset_url("./header.js") }}';
      headerScript.defer = true;
      document.body.appendChild(headerScript);
    }
    
    // Load forms script if forms exist
    if (document.querySelector('form')) {
      const formsScript = document.createElement('script');
      formsScript.src = '{{ get_asset_url("./forms.js") }}';
      formsScript.defer = true;
      document.body.appendChild(formsScript);
    }
  }
  
  // Load scripts when DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', loadComponentScripts);
  } else {
    loadComponentScripts();
  }
  
  // Preload critical resources for next navigation
  function preloadNextResources() {
    const links = document.querySelectorAll('a[href^="/"]');
    links.forEach(link => {
      link.addEventListener('mouseenter', function() {
        const preloadLink = document.createElement('link');
        preloadLink.rel = 'prefetch';
        preloadLink.href = this.href;
        document.head.appendChild(preloadLink);
      }, { passive: true, once: true });
    });
  }
  
  // Start preloading after initial load
  if ('requestIdleCallback' in window) {
    requestIdleCallback(preloadNextResources);
  } else {
    setTimeout(preloadNextResources, 2000);
  }
})();