// Page Loader functionality
(function() {
    'use strict';
    
    function hideLoader() {
        const loader = document.getElementById('page-loader');
        if (loader && !loader.classList.contains('hidden')) {
            loader.classList.add('hidden');
            setTimeout(function() {
                loader.remove();
                document.body.classList.remove('loading');
                document.body.classList.add('loaded');
            }, 500);
        }
    }
    
    function checkAllLoaded() {
        const headerDiv = document.getElementById('header');
        const footerDiv = document.getElementById('footer-placeholder');
        
        // Check if header is loaded (if it exists)
        const headerLoaded = !headerDiv || (headerDiv && headerDiv.innerHTML.trim() !== '');
        
        // Check if footer is loaded (if it exists)
        const footerLoaded = !footerDiv || (footerDiv && footerDiv.innerHTML.trim() !== '');
        
        // Check if page is ready
        const pageReady = document.readyState === 'complete';
        
        // If all components are loaded, hide the loader
        if (headerLoaded && footerLoaded && pageReady) {
            // Small delay for smooth transition
            setTimeout(hideLoader, 300);
        }
    }
    
    // Wait for DOM to be ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initLoader);
    } else {
        initLoader();
    }
    
    function initLoader() {
        const loader = document.getElementById('page-loader');
        if (!loader) return;
        
        const headerDiv = document.getElementById('header');
        const footerDiv = document.getElementById('footer-placeholder');
        
        // Use MutationObserver to watch for changes in header and footer
        const observer = new MutationObserver(function(mutations) {
            checkAllLoaded();
        });
        
        // Observe header if it exists
        if (headerDiv) {
            observer.observe(headerDiv, {
                childList: true,
                subtree: true,
                characterData: true
            });
        }
        
        // Observe footer if it exists
        if (footerDiv) {
            observer.observe(footerDiv, {
                childList: true,
                subtree: true,
                characterData: true
            });
        }
        
        // Check on window load
        if (document.readyState === 'complete') {
            checkAllLoaded();
        } else {
            window.addEventListener('load', function() {
                checkAllLoaded();
            });
        }
        
        // Initial check
        checkAllLoaded();
        
        // Fallback: Hide loader after max 5 seconds
        setTimeout(function() {
            if (loader && !loader.classList.contains('hidden')) {
                hideLoader();
            }
        }, 5000);
    }
})();
