jQuery(document).ready(function($) {
    let timeoutID;
    const timeoutValue = ironSecurityTimeout.timeout * 1000; // Convert to milliseconds
    const warningTime = 60000; // Show warning 1 minute before timeout
    let isWarningShown = false;

    function resetTimer() {
        clearTimeout(timeoutID);
        if (isWarningShown) {
            hideWarning();
        }
        startTimer();
    }

    function startTimer() {
        timeoutID = setTimeout(checkTimeout, timeoutValue - warningTime);
    }

    function checkTimeout() {
        showWarning();
        timeoutID = setTimeout(doTimeout, warningTime);
    }

    function doTimeout() {
        window.location.href = ironSecurityTimeout.logout_url;
    }

    function showWarning() {
        isWarningShown = true;
        const warning = $('<div/>', {
            class: 'iron-security-timeout-warning',
            html: `
                <div class="timeout-warning-content">
                    <p>Your session is about to expire due to inactivity.</p>
                    <button class="button button-primary extend-session">Stay Logged In</button>
                </div>
            `
        }).appendTo('body');

        warning.find('.extend-session').on('click', function() {
            // Ping server to keep session alive
            $.post(ajaxurl, {
                action: 'iron_security_extend_session',
                nonce: ironSecurityTimeout.nonce
            });
            resetTimer();
        });
    }

    function hideWarning() {
        isWarningShown = false;
        $('.iron-security-timeout-warning').remove();
    }

    // Events that reset the timer
    $(document).on('mousemove keypress click', resetTimer);

    // Start the initial timer
    startTimer();
}); 