document.addEventListener('DOMContentLoaded', () => {
    const loader = document.querySelector('.pageloader');
    if (!loader) {return;}

    const percentEl = loader.querySelector('.pageloader_percentage');

    const markAsDone = () => {
        if (!loader.classList.contains('pageloader_click')) {
            setTimeout( function() {
                loader.classList.add('pageloader_done');
                setTimeout(() => loader.classList.add('pageloader_done_all'), 500 );
            }, document.querySelector( '.customize-partial-edit-shortcuts-shown' ) ? 3000 : 10 );
        }
    };

    if (percentEl) {
        let count = 0;
        const updateCounter = () => {
            if (count <= 100) {
                percentEl.textContent = `${count}%`;
                count++;
                setTimeout(() => requestAnimationFrame(updateCounter), 30);
            } else {
                markAsDone();
            }
        };
        updateCounter();
    } else {
        window.addEventListener('load', markAsDone, { once: true });
    }

    setTimeout(markAsDone, 6000);

    if (!percentEl) {
        document.addEventListener('click', (e) => {
            const anchor = e.target.closest('a');
            if (!anchor || anchor.classList.contains('sf-with-ul') || e.target.tagName === 'I') {return;}

            const href = anchor.getAttribute('href') || '';
            const isExternal = href.includes('//');
            const isExcluded = /#|\?|\.jpg|\.jpeg|\.png|\.gif|\.mp3|\.zip|\.rar|\.mov|\.mp4|\.pdf|\.mpeg|youtube\.com|youtu\.be|vimeo\.com|wp-login|wp-admin/.test(href);
            const hasSpecialClass = anchor.closest('.cz_lightbox, .product, .esgbox, .fancybox, .lightbox, .add_to_cart_button');

            if (isExternal && !isExcluded && !hasSpecialClass && anchor.target !== '_blank') {
                loader.classList.remove('pageloader_done', 'pageloader_done_all');
                loader.classList.add('pageloader_click');
            }
        });
    }
});