// Session timeout functionality
(function() {
    // Timeout in milliseconds (9 minutes for warning, 10 minutes for logout)
    const WARNING_TIME = 9 * 60 * 1000; // 9 minutes
    const LOGOUT_TIME = 10 * 60 * 1000; // 10 minutes
    
    let warningTimer;
    let logoutTimer;
    
    // Function to reset timers
    function resetTimers() {
        // Clear existing timers
        clearTimeout(warningTimer);
        clearTimeout(logoutTimer);
        
        // Set new timers
        warningTimer = setTimeout(showTimeoutWarning, WARNING_TIME);
        logoutTimer = setTimeout(logoutUser, LOGOUT_TIME);
    }
    
    // Function to show warning before logout
    function showTimeoutWarning() {
        // Create warning modal if it doesn't exist
        let modal = document.getElementById('session-timeout-modal');
        if (!modal) {
            modal = document.createElement('div');
            modal.id = 'session-timeout-modal';
            modal.className = 'modal fade';
            modal.setAttribute('tabindex', '-1');
            modal.setAttribute('data-bs-backdrop', 'static');
            modal.setAttribute('data-bs-keyboard', 'false');
            
            modal.innerHTML = `
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header bg-warning text-dark">
                            <h5 class="modal-title">
                                <i class="fas fa-exclamation-triangle me-2"></i>Session Timeout Warning
                            </h5>
                        </div>
                        <div class="modal-body">
                            <p>Your session is about to expire due to inactivity. You will be logged out in <span id="countdown">60</span> seconds.</p>
                            <p>To remain logged in, click the "Continue Session" button below.</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-primary" id="continueSession">
                                <i class="fas fa-sync-alt me-2"></i>Continue Session
                            </button>
                            <button type="button" class="btn btn-secondary" id="logoutNow">
                                <i class="fas fa-sign-out-alt me-2"></i>Logout Now
                            </button>
                        </div>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
            
            // Initialize Bootstrap modal
            const modalInstance = new bootstrap.Modal(modal);
            modalInstance.show();
            
            // Start countdown
            let secondsLeft = 60;
            const countdownElement = document.getElementById('countdown');
            const countdownInterval = setInterval(() => {
                secondsLeft--;
                countdownElement.textContent = secondsLeft;
                
                if (secondsLeft <= 0) {
                    clearInterval(countdownInterval);
                }
            }, 1000);
            
            // Continue session button
            document.getElementById('continueSession').addEventListener('click', function() {
                clearInterval(countdownInterval);
                modalInstance.hide();
                resetTimers();
                // Send a request to the server to keep the session alive
                fetch('/keep-alive/', {
                    method: 'GET',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                    },
                    credentials: 'same-origin'
                });
            });
            
            // Logout now button
            document.getElementById('logoutNow').addEventListener('click', function() {
                clearInterval(countdownInterval);
                window.location.href = '/logout/';
            });
            
            // Handle modal hidden event
            modal.addEventListener('hidden.bs.modal', function () {
                modal.remove();
            });
        }
    }
    
    // Function to handle user logout
    function logoutUser() {
        window.location.href = '/logout/';
    }
    
    // Reset timers on user activity
    const events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
    events.forEach(event => {
        document.addEventListener(event, resetTimers, false);
    });
    
    // Initialize timers when the page loads
    document.addEventListener('DOMContentLoaded', resetTimers);
    
    // Also reset timers when the page becomes visible again
    document.addEventListener('visibilitychange', function() {
        if (!document.hidden) {
            resetTimers();
        }
    });
    
})();
