/**
 * Page Loader & Transition Manager
 * Handles hiding the fixed pre-loader and managing top progress bar transitions.
 */

(function () {
    'use strict';

    // Hide loader
    function hideLoader() {
        const loader = document.getElementById('pageLoader');
        if (loader) {
            loader.classList.add('hidden');
            setTimeout(() => {
                loader.style.display = 'none';
            }, 600);
        }
    }

    // Start transition bar
    function startTransition() {
        const bar = document.getElementById('transitionBar');
        if (bar) {
            bar.classList.add('active');
        }
    }

    // Initialize
    function init() {
        // Hide loader when page is physically finished loading
        if (document.readyState === 'complete') {
            setTimeout(hideLoader, 300);
        } else {
            window.addEventListener('load', () => {
                setTimeout(hideLoader, 300);
            });
        }

        // Add event listeners for smooth transitions
        document.addEventListener('click', (e) => {
            const link = e.target.closest('a');
            if (!link) return;

            const href = link.getAttribute('href');
            const target = link.getAttribute('target');
            const rel = link.getAttribute('rel');

            // Basic internal link detection
            if (!href ||
                href.startsWith('#') ||
                href.startsWith('javascript:') ||
                href.startsWith('mailto:') ||
                href.startsWith('tel:') ||
                target === '_blank' ||
                rel === 'external' ||
                e.ctrlKey || e.shiftKey || e.metaKey || e.button !== 0) {
                return;
            }

            const isInternal = !href.includes('://') || href.includes(window.location.hostname);

            if (isInternal) {
                startTransition();

                const isLogout = link.classList.contains('logout') || (href && href.includes('logout.php'));
                const isMenuLink = link.classList.contains('menu-link');

                if (isLogout || !isMenuLink) {
                    e.preventDefault();
                    setTimeout(() => {
                        window.location.href = href;
                    }, 400);
                }
            }
        });
    }

    // Run as soon as possible
    if (document.body) {
        init();
    } else {
        document.addEventListener('DOMContentLoaded', init);
    }
})();
