/**
 * Frontend JS for Custom Animated Preloader
 */
document.addEventListener('DOMContentLoaded', function () {
    const preloader = document.getElementById('swap-preloader');
    if (!preloader) return;

    // Parse Settings
    const fadeSpeed = parseInt(swapVars.fadeSpeed) || 500;
    let minTime = parseInt(swapVars.minTime) || 1000;
    const delay = parseInt(swapVars.delay) || 0;
    const transition = swapVars.transition || 'fade';
    const showPercentage = swapVars.showPercentage === 'yes';
    const showProgressBar = swapVars.showProgressBar === 'yes';

    // Wait for Animation Logic
    let animDuration = 0;

    // Check Logo Wait
    if (swapVars.logoWait === 'yes') {
        const lSpeed = parseInt(swapVars.logoSpeed) || 1000;
        animDuration = Math.max(animDuration, lSpeed);
    }

    // Check Style Wait
    if (swapVars.styleWait === 'yes') {
        const sSpeed = 1000; // Most CSS loaders are around 1s
        animDuration = Math.max(animDuration, sSpeed);

        const styleElements = preloader.querySelectorAll('[class^="swap-tpl-"]');
        if (styleElements.length > 0) {
            let loopFinished = false;
            let elementsFinished = 0;

            styleElements.forEach(el => {
                const onIterate = () => {
                    elementsFinished++;
                    if (elementsFinished >= styleElements.length) {
                        loopFinished = true;
                    }
                    el.removeEventListener('animationiteration', onIterate);
                    el.removeEventListener('animationend', onIterate);
                };
                el.addEventListener('animationiteration', onIterate);
                el.addEventListener('animationend', onIterate);

                setTimeout(onIterate, sSpeed + 400); // Expiration fallback
            });

            window.swapStyleLoopFinished = () => loopFinished;
        }
    }

    if (swapVars.textWait === 'yes') {
        const tSpeed = parseInt(swapVars.textSpeed) || 1000;

        if (swapVars.textAnim === 'typewriter') {
            const textEl = document.querySelector('.swap-anim-typewriter');
            if (textEl) {
                const charDelay = Math.max(20, tSpeed / 10);
                const typeTime = 500 + (textEl.innerText.length * charDelay) + 1000;
                animDuration = Math.max(animDuration, typeTime);
            }
        } else {
            animDuration = Math.max(animDuration, tSpeed);
        }

        // Add event listeners to guarantee at least one loop for CSS animations
        const textElements = preloader.querySelectorAll('.swap-text[class*="swap-text-loader-"], .swap-text.swap-anim-pulse, .swap-text.swap-anim-bounce');
        if (textElements.length > 0) {
            let loopFinished = false;
            let elementsFinished = 0;

            textElements.forEach(el => {
                const onIterate = () => {
                    elementsFinished++;
                    if (elementsFinished >= textElements.length) {
                        loopFinished = true;
                    }
                    el.removeEventListener('animationiteration', onIterate);
                    el.removeEventListener('animationend', onIterate);
                };
                el.addEventListener('animationiteration', onIterate);
                el.addEventListener('animationend', onIterate);

                // Fallback timeout in case event doesn't fire
                setTimeout(onIterate, tSpeed + 200);
            });

            // We hijack the hide function to wait for loopFinished
            window.swapTextLoopFinished = () => loopFinished;
        }
    }

    if (animDuration > minTime) {
        minTime = animDuration;
    }

    // Typewriter Function
    function startTypewriter() {
        const typewriter = document.querySelector('.swap-anim-typewriter');
        if (typewriter) {
            const text = typewriter.innerText;
            typewriter.innerText = '';
            const tSpeed = parseInt(swapVars.textSpeed) || 1000;
            const charDelay = Math.max(20, tSpeed / 12);

            let i = 0;
            function typeWriter() {
                if (i < text.length) {
                    typewriter.innerText += text.charAt(i);
                    i++;
                    setTimeout(typeWriter, charDelay);
                }
            }
            setTimeout(typeWriter, 500);
        }
    }

    // Show Delay Logic
    if (delay > 0) {
        setTimeout(() => {
            preloader.style.display = 'flex';
            startTypewriter();
        }, delay);
    } else {
        preloader.style.display = 'flex';
        startTypewriter();
    }

    // Start Timer
    const startTime = Date.now();

    // Progress Simulation
    if (showProgressBar || showPercentage) {
        let progress = 0;
        // Basic simulation: reaches 90% in 2s, then waits for load
        const interval = setInterval(() => {
            if (progress < 90) {
                progress += Math.random() * 5;
                if (progress > 90) progress = 90;
                updateProgress(progress);
            }
        }, 100);

        window.updateProgress = function (val) {
            if (showProgressBar) {
                const bar = preloader.querySelector('.swap-progress-bar');
                if (bar) bar.style.width = val + '%';
            }
            if (showPercentage) {
                const percent = preloader.querySelector('.swap-percentage');
                if (percent) percent.innerText = Math.round(val) + '%';
            }
        };
    }

    // Hide Logic
    window.addEventListener('load', function () {
        // Smoothly animate progress from current to 100%
        if (typeof window.updateProgress === 'function') {
            var currentBar = preloader.querySelector('.swap-progress-bar');
            var currentPercent = preloader.querySelector('.swap-percentage');
            var startVal = 0;
            if (currentBar) startVal = parseFloat(currentBar.style.width) || 0;
            else if (currentPercent) startVal = parseInt(currentPercent.innerText) || 0;

            var animStart = null;
            var animDur = 500; // 500ms smooth counting
            function animateTo100(ts) {
                if (!animStart) animStart = ts;
                var elapsed = ts - animStart;
                var pct = Math.min(startVal + ((100 - startVal) * (elapsed / animDur)), 100);
                window.updateProgress(pct);
                if (pct < 100) {
                    requestAnimationFrame(animateTo100);
                }
            }
            requestAnimationFrame(animateTo100);
        }

        const elapsedTime = Date.now() - startTime;
        const remainingTime = minTime - elapsedTime;
        const waitTime = remainingTime > 0 ? remainingTime : 0;

        setTimeout(() => {
            const executeHide = () => {
                // Add specific transition class
                preloader.classList.add('swap-exit-' + transition);

                // Set transition duration dynamically
                preloader.style.transitionDuration = (fadeSpeed / 1000) + 's';

                // Remove from DOM after animation
                setTimeout(() => {
                    preloader.remove();
                }, fadeSpeed);
            };

            const checkAndHide = () => {
                let isWaiting = false;

                if (swapVars.textWait === 'yes' && typeof window.swapTextLoopFinished === 'function') {
                    if (!window.swapTextLoopFinished()) isWaiting = true;
                }

                if (swapVars.styleWait === 'yes' && typeof window.swapStyleLoopFinished === 'function') {
                    if (!window.swapStyleLoopFinished()) isWaiting = true;
                }

                if (isWaiting) {
                    setTimeout(checkAndHide, 100);
                } else {
                    executeHide();
                }
            };

            checkAndHide();

        }, waitTime);
    });

    // Fallback safety: hide after 15 seconds max
    setTimeout(function () {
        if (document.getElementById('swap-preloader')) {
            preloader.style.display = 'none';
        }
    }, 15000);

});
