// Session Timeout Warning
(function () {
    const SESSION_CHECK_INTERVAL = 30000; // Check every 30s (needed to reliably hit 60s warning)
    const WARNING_THRESHOLD = 60; // Show warning 1 minute before timeout
    const FOCUS_RECHECK_DEBOUNCE_MS = 1000;
    let warningShown = false;
    let sessionCheckTimer = null;
    let inFlight = false;
    let lastSessionExpiryTime = null;
    const basePath = (window.appBasePath || '').replace(/\/$/, '');
    let focusRecheckTimer = null;

    // Initialize when DOM is ready
    function initSessionWarning() {
        console.log('Session warning script initialized');

        // Check immediately on load
        scheduleNextCheck(0);

        // Also check on user activity
        document.addEventListener('mousemove', handleUserActivity);
        document.addEventListener('keypress', handleUserActivity);
        document.addEventListener('click', handleUserActivity);

        // Browsers may throttle timers in background tabs. Re-check immediately when user returns.
        document.addEventListener('visibilitychange', handleVisibilityOrFocus);
        window.addEventListener('focus', handleVisibilityOrFocus);
    }

    function handleVisibilityOrFocus() {
        if (document.visibilityState && document.visibilityState !== 'visible') {
            return;
        }
        if (focusRecheckTimer) {
            clearTimeout(focusRecheckTimer);
        }
        focusRecheckTimer = setTimeout(function () {
            scheduleNextCheck(0);
        }, FOCUS_RECHECK_DEBOUNCE_MS);
    }

    function scheduleNextCheck(delayMs) {
        if (sessionCheckTimer) {
            clearTimeout(sessionCheckTimer);
        }
        sessionCheckTimer = setTimeout(checkSessionStatus, Math.max(0, delayMs));
    }

    function handleUserActivity() {
        // Log activity but don't auto-extend session
        // User must explicitly click "Continue Session" button
    }

    function checkSessionStatus() {
        if (inFlight) {
            // avoid overlapping requests if a call is slow
            scheduleNextCheck(1000);
            return;
        }

        inFlight = true;
        fetch(`${basePath}/api/session/check`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            },
            credentials: 'include'  // Include cookies for authorization
        })
            .then(response => {
                if (!response.ok) {
                    if (response.status === 401) {
                        // Unauthorized - auth/session expired
                        expireSession();
                        return null;
                    }
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (!data) {
                    return;
                }
                console.log('Session check response:', data);

                if (data.isActive) {
                    const secondsRemaining = data.secondsRemaining;
                    lastSessionExpiryTime = new Date(data.expiryTime);

                    // Show warning if less than WARNING_THRESHOLD seconds remain
                    if (secondsRemaining <= WARNING_THRESHOLD && secondsRemaining > 0 && !warningShown) {
                        console.log(`Showing warning - ${secondsRemaining}s remaining`);
                        showSessionWarning(secondsRemaining);
                        warningShown = true;

                        // while warning is visible, poll every second so UI remains accurate
                        scheduleNextCheck(1000);
                        return;
                    }
                    // Hide warning if time has been extended (more than threshold)
                    else if (secondsRemaining > WARNING_THRESHOLD && warningShown) {
                        console.log('Hiding warning - session extended');
                        hideSessionWarning();
                        warningShown = false;
                    }
                    // If session is about to expire
                    else if (secondsRemaining <= 0) {
                        console.log('Session time expired');
                        expireSession();
                    }
                } else {
                    console.log('Session is not active');
                    if (!warningShown) {
                        expireSession();
                    }
                }

                // normal polling cadence
                scheduleNextCheck(SESSION_CHECK_INTERVAL);
            })
            .catch(error => {
                console.error('Session check failed:', error);
                // Don't expire on network error - might be temporary

                // back off a bit on errors
                scheduleNextCheck(SESSION_CHECK_INTERVAL);
            })
            .finally(() => {
                inFlight = false;
            });
    }

    function showSessionWarning(secondsRemaining) {
        // Remove if already exists
        const existingModal = document.getElementById('sessionWarningModal');
        if (existingModal) {
            existingModal.remove();
        }

        const modal = document.createElement('div');
        modal.id = 'sessionWarningModal';
        modal.setAttribute('role', 'dialog');
        modal.setAttribute('aria-modal', 'true');
        modal.style.cssText = `
            position: fixed;
            inset: 0;
            background-color: rgba(0, 0, 0, 0.35);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        `;

        const dialog = document.createElement('div');
        dialog.style.cssText = `
            width: 340px;
            background: #fff;
            border: 1px solid #c9c9c9;
            border-radius: 3px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.2);
            font-family: Arial, sans-serif;
            overflow: hidden;
        `;

        const header = document.createElement('div');
        header.textContent = 'Session Expiring';
        header.style.cssText = `
            padding: 12px 16px;
            text-align: center;
            font-weight: 700;
            color: #333;
            background: linear-gradient(#f7f7f7, #ededed);
            border-bottom: 1px solid #dcdcdc;
        `;

        const body = document.createElement('div');
        body.style.cssText = `
            padding: 18px 20px 10px 20px;
            color: #333;
            font-size: 14px;
            line-height: 1.5;
        `;

        const line1 = document.createElement('div');
        line1.textContent = 'Your session is about to expire!';
        line1.style.cssText = 'margin-bottom: 12px; text-align: center;';

        const timerDisplay = document.createElement('div');
        timerDisplay.id = 'sessionTimer';
        timerDisplay.textContent = formatSeconds(secondsRemaining);
        timerDisplay.style.cssText = `
            margin: 0 auto 12px auto;
            width: fit-content;
            font-size: 20px;
            font-weight: 400;
            color: #333;
            font-variant-numeric: tabular-nums;
        `;

        const line2 = document.createElement('div');
        line2.textContent = 'Click OK to continue your session.';
        line2.style.cssText = 'margin-bottom: 8px; text-align: center;';

        const footer = document.createElement('div');
        footer.style.cssText = `
            padding: 12px 16px 14px 16px;
            border-top: 1px solid #e6e6e6;
            background: #fff;
            display: flex;
            justify-content: flex-start;
        `;

        const okButton = document.createElement('button');
        okButton.textContent = 'OK';
        okButton.type = 'button';
        okButton.onclick = extendSession;
        okButton.style.cssText = `
            min-width: 86px;
            padding: 8px 18px;
            border-radius: 4px;
            border: 1px solid #2b78d6;
            background: linear-gradient(#fdfefe, #d7e9ff);
            color: #1a1a1a;
            cursor: pointer;
            font-size: 14px;
            box-shadow: inset 0 1px 0 rgba(255,255,255,0.9);
        `;
        okButton.onfocus = function () { this.style.outline = '2px solid rgba(43,120,214,0.35)'; };
        okButton.onblur = function () { this.style.outline = 'none'; };

        body.appendChild(line1);
        body.appendChild(timerDisplay);
        body.appendChild(line2);
        footer.appendChild(okButton);

        dialog.appendChild(header);
        dialog.appendChild(body);
        dialog.appendChild(footer);
        modal.appendChild(dialog);
        document.body.appendChild(modal);

        // focus for accessibility
        okButton.focus();

        // Start countdown
        startCountdown(secondsRemaining);
    }

    function formatSeconds(seconds) {
        const s = Math.max(0, Number(seconds) || 0);
        const mm = Math.floor(s / 60);
        const ss = s % 60;
        return `${mm}:${String(ss).padStart(2, '0')}`;
    }

    function startCountdown(seconds) {
        let remaining = seconds;

        const countdownInterval = setInterval(function () {
            remaining--;
            const timerDisplay = document.getElementById('sessionTimer');
            if (timerDisplay) {
                timerDisplay.textContent = formatSeconds(remaining);
            }

            if (remaining <= 0) {
                clearInterval(countdownInterval);
                // Don't auto-expire here, let the next check do it
            }
        }, 1000);
    }

    function hideSessionWarning() {
        const modal = document.getElementById('sessionWarningModal');
        if (modal) {
            modal.remove();
        }
    }

    function extendSession() {
        console.log('Extending session...');

        fetch(`${basePath}/api/session/extend`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            credentials: 'include'  // Include cookies for authorization
        })
            .then(response => {
                if (!response.ok) {
                    if (response.status === 401) {
                        expireSession();
                        return null;
                    }
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (!data) {
                    return;
                }
                if (data.success) {
                    console.log('Session extended successfully');
                    hideSessionWarning();
                    warningShown = false;
                    lastSessionExpiryTime = new Date(data.newExpiryTime);

                    // Force an immediate re-check so UI state is accurate.
                    scheduleNextCheck(0);
                } else {
                    console.log('Failed to extend session');
                    expireSession();
                }
            })
            .catch(error => {
                console.error('Failed to extend session:', error);
                expireSession();
            });
    }

    function expireSession() {
        if (sessionCheckTimer) {
            clearTimeout(sessionCheckTimer);
            sessionCheckTimer = null;
        }
        hideSessionWarning();

        const message = 'Your session has expired. You will be redirected to the login page.';
        console.log(message);
        alert(message);
        window.location.href = `${basePath}/Login/Index?sessionExpired=true`;
    }

    // Initialize when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initSessionWarning);
    } else {
        initSessionWarning();
    }
})();
