// AUTO TESTER - Page Loading System

// Page Loader Configuration
const loaderConfig = {
    minLoadTime: 800, // minimum time to show loader (ms)
    maxLoadTime: 5000, // maximum time to show loader (ms)
    fadeOutTime: 300, // fade out animation time (ms)
    showDelay: 100, // delay before showing loader (ms)
    hideOnComplete: true,
    showOnAjax: true,
    showOnFormSubmit: true
};

// Create page loader HTML
function createPageLoader() {
    const loaderHtml = `
        <div id="pageLoader" class="page-loader" role="status" aria-label="Loading page">
            <div class="loader-container">
                <div class="loader-content">
                    <div class="loader-logo">
                        <div class="logo-icon">
                            <i class="fas fa-car"></i>
                        </div>
                        <span class="logo-text">AUTO<span>TESTER</span></span>
                    </div>
                    <div class="loader-spinner">
                        <div class="spinner"></div>
                    </div>
                    <div class="loader-text">
                        <span class="loading-text">Loading...</span>
                        <div class="loading-dots">
                            <span>.</span>
                            <span>.</span>
                            <span>.</span>
                        </div>
                    </div>
                    <div class="loader-progress">
                        <div class="progress-bar">
                            <div class="progress-fill"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Add to page
    const container = document.createElement('div');
    container.innerHTML = loaderHtml;
    document.body.appendChild(container.firstElementChild);
}

// Show page loader
function showPageLoader(message = 'Loading...', showProgress = false) {
    const loader = document.getElementById('pageLoader');
    
    if (!loader) {
        createPageLoader();
        showPageLoader(message, showProgress);
        return;
    }
    
    // Update loading message
    const loadingText = loader.querySelector('.loading-text');
    if (loadingText) {
        loadingText.textContent = message;
    }
    
    // Show/hide progress bar
    const progressBar = loader.querySelector('.loader-progress');
    if (progressBar) {
        progressBar.style.display = showProgress ? 'block' : 'none';
    }
    
    // Show loader
    setTimeout(() => {
        loader.classList.add('show');
        document.body.style.overflow = 'hidden'; // Prevent scrolling
    }, loaderConfig.showDelay);
    
    // Start progress animation if needed
    if (showProgress) {
        startProgressAnimation();
    }
    
    // Auto-hide if max time exceeded
    setTimeout(() => {
        hidePageLoader();
    }, loaderConfig.maxLoadTime);
}

// Hide page loader
function hidePageLoader() {
    const loader = document.getElementById('pageLoader');
    
    if (!loader) return;
    
    // Calculate minimum display time
    const showTime = Date.now() - (loader.dataset.showTime || Date.now());
    const remainingTime = Math.max(0, loaderConfig.minLoadTime - showTime);
    
    setTimeout(() => {
        loader.classList.remove('show');
        loader.classList.add('fade-out');
        
        // Restore scrolling
        document.body.style.overflow = '';
        
        // Remove loader after fade out
        setTimeout(() => {
            if (loader.parentNode) {
                loader.parentNode.removeChild(loader);
            }
        }, loaderConfig.fadeOutTime);
    }, remainingTime);
}

// Progress animation
function startProgressAnimation() {
    const progressFill = document.querySelector('.progress-fill');
    if (!progressFill) return;
    
    let progress = 0;
    const interval = setInterval(() => {
        progress += Math.random() * 30;
        if (progress >= 90) {
            progress = 90;
            clearInterval(interval);
        }
        progressFill.style.width = progress + '%';
    }, 200);
}

// Complete progress animation
function completeProgressAnimation() {
    const progressFill = document.querySelector('.progress-fill');
    if (progressFill) {
        progressFill.style.width = '100%';
    }
}

// Initialize page loader
function initPageLoader() {
    // Show loader on page load
    if (document.readyState === 'loading') {
        showPageLoader('Loading AUTO TESTER...', true);
        
        // Hide when page is loaded
        window.addEventListener('load', () => {
            completeProgressAnimation();
            setTimeout(hidePageLoader, 200);
        });
    }
    
    // Show loader on form submissions
    if (loaderConfig.showOnFormSubmit) {
        document.addEventListener('submit', (e) => {
            const form = e.target;
            if (form.tagName === 'FORM' && !form.classList.contains('no-loader')) {
                showPageLoader('Processing...', true);
            }
        });
    }
    
    // Show loader on AJAX requests
    if (loaderConfig.showOnAjax) {
        const originalFetch = window.fetch;
        window.fetch = function(...args) {
            showPageLoader('Loading...', false);
            return originalFetch.apply(this, args)
                .finally(() => {
                    setTimeout(hidePageLoader, 500);
                });
        };
        
        // Override XMLHttpRequest
        const originalXHROpen = XMLHttpRequest.prototype.open;
        XMLHttpRequest.prototype.open = function(method, url, ...args) {
            originalXHROpen.apply(this, [method, url, ...args]);
            
            this.addEventListener('loadstart', () => {
                showPageLoader('Loading...', false);
            });
            
            this.addEventListener('loadend', () => {
                setTimeout(hidePageLoader, 500);
            });
        };
    }
    
    // Show loader on navigation (for SPA)
    if (typeof window.navigation !== 'undefined') {
        window.navigation.addEventListener('navigate', (e) => {
            if (e.destination.url !== window.location.href) {
                showPageLoader('Loading...', true);
            }
        });
    }
}

// Manual loader control
function manualShowLoader(message, showProgress = false) {
    showPageLoader(message, showProgress);
}

function manualHideLoader() {
    hidePageLoader();
}

// Loading messages for different contexts
const loadingMessages = {
    general: 'Loading...',
    login: 'Signing in...',
    logout: 'Signing out...',
    submit: 'Processing...',
    upload: 'Uploading...',
    download: 'Downloading...',
    saving: 'Saving...',
    deleting: 'Deleting...',
    searching: 'Searching...',
    loading: 'Loading...',
    processing: 'Processing...',
    authenticating: 'Authenticating...',
    connecting: 'Connecting...',
    initializing: 'Initializing...'
};

// Context-aware loader
function showContextLoader(context, showProgress = false) {
    const message = loadingMessages[context] || loadingMessages.general;
    showPageLoader(message, showProgress);
}

// Export functions for global use
window.showPageLoader = showPageLoader;
window.hidePageLoader = hidePageLoader;
window.manualShowLoader = manualShowLoader;
window.manualHideLoader = manualHideLoader;
window.showContextLoader = showContextLoader;

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', initPageLoader);

// Handle browser back/forward buttons
window.addEventListener('pageshow', (e) => {
    if (e.persisted) {
        hidePageLoader();
    }
});

// Handle page unload
window.addEventListener('beforeunload', () => {
    // Show loader briefly to indicate navigation
    showPageLoader('Loading...', false);
});

// Error handling
window.addEventListener('error', (e) => {
    hidePageLoader();
});

// Unhandled promise rejection
window.addEventListener('unhandledrejection', (e) => {
    hidePageLoader();
});

// Development helpers (remove in production)
if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
    window.testLoader = {
        show: () => showPageLoader('Test Loading...', true),
        hide: () => hidePageLoader(),
        progress: () => startProgressAnimation(),
        complete: () => completeProgressAnimation()
    };
}
