(function($) {
    'use strict';

    if (typeof wtolsAutoLogout === 'undefined') {
        return;
    }

    var idleTime = 0;
    var maxIdle = parseInt(wtolsAutoLogout.idleTimeout, 10);
    var warningTime = parseInt(wtolsAutoLogout.warningTime, 10);
    var logoutTimer = null;
    var idleInterval = null;
    var overlay = null;
    var countdownEl = null;
    var countdownSeconds = warningTime;
    var isWarningShown = false;

    function init() {
        // Increment idle time counter every second
        idleInterval = setInterval(timerIncrement, 1000);

        // Reset idle time on user activity
        $(document).on('mousemove keypress mousedown touchstart scroll click', function() {
            if (!isWarningShown) {
                idleTime = 0;
            }
        });

        createModalHtml();
    }

    function createModalHtml() {
        var html = '<div id="wtols-logout-overlay" class="wtols-logout-overlay">' +
            '  <div class="wtols-logout-modal">' +
            '    <div class="wtols-logout-icon">' +
            '      <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path><line x1="12" y1="9" x2="12" y2="13"></line><line x1="12" y1="17" x2="12.01" y2="17"></line></svg>' +
            '    </div>' +
            '    <h3 class="wtols-logout-title">' + wtolsAutoLogout.warningTitle + '</h3>' +
            '    <p class="wtols-logout-message">' + wtolsAutoLogout.warningMessage.replace('{seconds}', '<span id="wtols-countdown-sec">' + warningTime + '</span>') + '</p>' +
            '    <div class="wtols-logout-buttons">' +
            '      <button type="button" id="wtols-stay-logged-in" class="wtols-btn wtols-btn-primary">' + wtolsAutoLogout.btnKeepAlive + '</button>' +
            '      <button type="button" id="wtols-log-out-now" class="wtols-btn wtols-btn-secondary">' + wtolsAutoLogout.btnLogOut + '</button>' +
            '    </div>' +
            '  </div>' +
            '</div>';

        $('body').append(html);
        overlay = $('#wtols-logout-overlay');
        countdownEl = $('#wtols-countdown-sec');

        $('#wtols-stay-logged-in').on('click', function(e) {
            e.preventDefault();
            stayLoggedIn();
        });

        $('#wtols-log-out-now').on('click', function(e) {
            e.preventDefault();
            logoutUser();
        });
    }

    function timerIncrement() {
        if (isWarningShown) {
            return;
        }

        idleTime++;
        if (idleTime >= (maxIdle - warningTime)) {
            showWarning();
        }
    }

    function showWarning() {
        isWarningShown = true;
        countdownSeconds = warningTime;
        countdownEl.text(countdownSeconds);
        overlay.addClass('wtols-active');

        // Start countdown
        logoutTimer = setInterval(function() {
            countdownSeconds--;
            countdownEl.text(countdownSeconds);

            if (countdownSeconds <= 0) {
                clearInterval(logoutTimer);
                logoutUser();
            }
        }, 1000);
    }

    function stayLoggedIn() {
        // Send AJAX keep alive to refresh server session
        $.post(wtolsAutoLogout.ajaxUrl, {
            action: 'wtols_keep_alive',
            nonce: wtolsAutoLogout.nonce
        }, function(response) {
            if (response.success) {
                resetWarning();
            } else {
                // If nonce invalid or session expired on server already, log out
                logoutUser();
            }
        }).fail(function() {
            // Even if AJAX fails, reset warning locally so we don't break the UI immediately
            resetWarning();
        });
    }

    function resetWarning() {
        clearInterval(logoutTimer);
        overlay.removeClass('wtols-active');
        isWarningShown = false;
        idleTime = 0;
    }

    function logoutUser() {
        clearInterval(idleInterval);
        clearInterval(logoutTimer);
        window.location.href = wtolsAutoLogout.logoutUrl;
    }

    $(document).ready(init);

})(jQuery);
