/**
 * Idle Timeout - Dashboard (Perangkat / Admin)
 * Jika tidak ada aktivitas selama 15 menit, redirect ke logout.
 * Juga: session di server hanya 15 menit; tutup browser = session hilang.
 */
(function () {
    var IDLE_MINUTES = 15;
    var IDLE_MS = IDLE_MINUTES * 60 * 1000;
    var logoutUrl = (typeof window.IDLE_LOGOUT_URL !== 'undefined' && window.IDLE_LOGOUT_URL) ||
                    (typeof window.PERANGKAT_LOGOUT_URL !== 'undefined' && window.PERANGKAT_LOGOUT_URL) ||
                    '';

    if (!logoutUrl) return;

    var timeoutId;

    function redirectLogout() {
        var separator = logoutUrl.indexOf('?') === -1 ? '?' : '&';
        window.location.href = logoutUrl + separator + 'reason=timeout';
    }

    function resetIdleTimer() {
        if (timeoutId) clearTimeout(timeoutId);
        timeoutId = setTimeout(redirectLogout, IDLE_MS);
    }

    function setupIdleListeners() {
        var events = ['mousemove', 'mousedown', 'keydown', 'scroll', 'touchstart', 'click'];
        events.forEach(function (eventName) {
            document.addEventListener(eventName, resetIdleTimer);
        });
        resetIdleTimer();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', setupIdleListeners);
    } else {
        setupIdleListeners();
    }
})();
