

(function () {
    'use strict';

    const IDLE_TIMEOUT   = 30 * 60 * 1000;
    const HEARTBEAT_INTERVAL = 5 * 60 * 1000;
    const WARNING_BEFORE = 5 * 60 * 1000;

    let lastActivity = Date.now();
    let heartbeatTimer = null;
    let warningShown = false;

    const activityEvents = ['mousemove', 'keydown', 'click', 'scroll', 'touchstart'];

    function resetIdleTimer() {
        lastActivity = Date.now();
        if (warningShown) {
            dismissWarning();
        }
    }

    activityEvents.forEach(function (evt) {
        document.addEventListener(evt, resetIdleTimer, { passive: true });
    });

    function checkIdle() {
        const elapsed = Date.now() - lastActivity;

        if (elapsed >= IDLE_TIMEOUT) {
            performLogout('idle_timeout');
            return;
        }

        if (elapsed >= (IDLE_TIMEOUT - WARNING_BEFORE) && !warningShown) {
            showWarning();
        }
    }

    setInterval(checkIdle, 30000);

    function sendHeartbeat() {
        fetch('?action=heartbeat', {
            method: 'POST',
            headers: {
                'X-CSRF-Token': getCSRFToken(),
                'X-Requested-With': 'XMLHttpRequest',
            },
        }).catch(function () {
            performLogout('session_expired');
        });
    }

    heartbeatTimer = setInterval(sendHeartbeat, HEARTBEAT_INTERVAL);

    function showWarning() {
        warningShown = true;
        const banner = document.createElement('div');
        banner.id = 'session-warning';
        banner.className = 'session-warning';
        banner.innerHTML =
            '<span>Session expiring soon. Move your mouse to stay logged in.</span>' +
            '<button onclick="document.getElementById(\'session-warning\').remove()">Dismiss</button>';
        document.body.appendChild(banner);
    }

    function dismissWarning() {
        warningShown = false;
        const el = document.getElementById('session-warning');
        if (el) el.remove();
    }

    function performLogout(reason) {
        clearInterval(heartbeatTimer);

        fetch('?action=logout&reason=' + encodeURIComponent(reason), {
            method: 'POST',
            headers: { 'X-CSRF-Token': getCSRFToken() },
        }).finally(function () {
            window.location.href = 'login.php?expired=1';
        });
    }

    function getCSRFToken() {
        const meta = document.querySelector('meta[name="csrf-token"]');
        return meta ? meta.getAttribute('content') : '';
    }

    window.addEventListener('beforeunload', function () {
        navigator.sendBeacon('?action=heartbeat', new URLSearchParams({ _csrf: getCSRFToken() }));
    });
})();
