/**
 * Asset Optimization Helper
 * Handles lazy loading, deferred loading, and resource hints
 */

// Defer non-critical CSS
function deferCSS(href) {
    const link = document.createElement('link');
    link.rel = 'preload';
    link.as = 'style';
    link.href = href;
    link.onload = function() {
        this.onload = null;
        this.rel = 'stylesheet';
    };
    document.head.appendChild(link);
}

// Defer JavaScript loading
function deferJS(src, callback) {
    const script = document.createElement('script');
    script.src = src;
    script.defer = true;
    if (callback) {
        script.onload = callback;
    }
    document.head.appendChild(script);
}

// Lazy load images
function lazyLoadImages() {
    if ('IntersectionObserver' in window) {
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    img.src = img.dataset.src;
                    img.classList.remove('lazy');
                    observer.unobserve(img);
                }
            });
        });
        
        document.querySelectorAll('img[data-src]').forEach(img => {
            imageObserver.observe(img);
        });
    }
}

// Add resource hints for performance
function addResourceHints() {
    // DNS prefetch for external resources
    const dnsPrefetch = [
        // Add your external domains here
    ];
    
    dnsPrefetch.forEach(domain => {
        const link = document.createElement('link');
        link.rel = 'dns-prefetch';
        link.href = domain;
        document.head.appendChild(link);
    });
}

// Initialize optimizations on DOM ready
document.addEventListener('DOMContentLoaded', function() {
    lazyLoadImages();
    addResourceHints();
    
    // Report performance metrics (in development)
    if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
        window.addEventListener('load', function() {
            const perfData = performance.getEntriesByType('navigation')[0];
            console.log('Page Load Time:', perfData.loadEventEnd - perfData.fetchStart, 'ms');
            console.log('DOM Content Loaded:', perfData.domContentLoadedEventEnd - perfData.fetchStart, 'ms');
        });
    }
});
