// Blazor Server Reconnection Timer
(function() {
    let reconnectTimer = null;
    let startTime = null;

    function startTimer() {
        if (reconnectTimer) return; // Already running

        console.log('Blazor reconnection started, timer running...');
        startTime = Date.now();

        reconnectTimer = setInterval(() => {
            const elapsedSeconds = Math.floor((Date.now() - startTime) / 1000);
            const timerElement = document.getElementById('reconnect-elapsed-time');

            if (timerElement) {
                timerElement.textContent = `${elapsedSeconds}s`;
            }
        }, 1000);
    }

    function stopTimer() {
        if (reconnectTimer) {
            console.log('Blazor reconnection ended, stopping timer');
            clearInterval(reconnectTimer);
            reconnectTimer = null;

            // Reset timer display
            const timerElement = document.getElementById('reconnect-elapsed-time');
            if (timerElement) {
                timerElement.textContent = '0s';
            }
        }
    }

    function checkReconnectionState() {
        const modal = document.getElementById('components-reconnect-modal');

        if (!modal) return;

        // Check if modal has the "show" class (Blazor applies this when reconnecting)
        if (modal.classList.contains('components-reconnect-show')) {
            startTimer();
        } else {
            stopTimer();
        }
    }

    // MutationObserver to watch for class changes on the modal
    const observer = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
            if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
                checkReconnectionState();
            }
        });
    });

    // Start observing when DOM is ready
    function init() {
        const modal = document.getElementById('components-reconnect-modal');

        if (modal) {
            observer.observe(modal, {
                attributes: true,
                attributeFilter: ['class']
            });

            // Check initial state
            checkReconnectionState();
            console.log('Blazor reconnection timer initialized');
        } else {
            console.warn('components-reconnect-modal not found, retrying...');
            setTimeout(init, 100);
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
