(function() {
    'use strict';
    
    // ==================== CHECK LOGIN STATUS ====================
    function checkLoginStatus() {
        const loggedInUser = sessionStorage.getItem("loggedInUser");
        const loginBtn = document.querySelector('.btn-login');
        
        if (loggedInUser && loginBtn) {
            // User is logged in - change to Logout button
            loginBtn.textContent = 'Logout';
            loginBtn.classList.remove('btn-login');
            loginBtn.classList.add('btn-logout');
            loginBtn.href = '#'; // Prevent navigation
            
            // Remove existing click listeners (untuk menghindari duplikat)
            loginBtn.replaceWith(loginBtn.cloneNode(true));
            
            // Get new reference dan add logout handler
            const newLogoutBtn = document.querySelector('.btn-logout');
            if (newLogoutBtn) {
                newLogoutBtn.addEventListener('click', handleLogoutClick);
            }
            
            console.log('✅ User logged in:', loggedInUser);
        } else {
            console.log('ℹ️ No user logged in');
        }
    }
    
    // ==================== LOGOUT CLICK HANDLER ====================
    function handleLogoutClick(e) {
        e.preventDefault();
        showLogoutModal();
    }
    
    // ==================== SHOW LOGOUT CONFIRMATION MODAL ====================
    function showLogoutModal() {
        const overlay = document.getElementById('logout-overlay');
        if (overlay) {
            overlay.style.display = 'flex';
            setTimeout(() => overlay.classList.add('active'), 10);
            
            // Setup modal buttons
            setupModalButtons();
        }
    }
    
    // ==================== SETUP MODAL BUTTONS ====================
    function setupModalButtons() {
        const cancelBtn = document.getElementById('btn-logout-cancel');
        const confirmBtn = document.getElementById('btn-logout-confirm');
        const overlay = document.getElementById('logout-overlay');
        
        // Remove previous listeners
        if (cancelBtn) {
            const newCancelBtn = cancelBtn.cloneNode(true);
            cancelBtn.replaceWith(newCancelBtn);
            newCancelBtn.onclick = closeLogoutModal;
        }
        
        if (confirmBtn) {
            const newConfirmBtn = confirmBtn.cloneNode(true);
            confirmBtn.replaceWith(newConfirmBtn);
            newConfirmBtn.onclick = confirmLogout;
        }
        
        // Close on overlay click
        if (overlay) {
            overlay.onclick = function(e) {
                if (e.target === overlay) {
                    closeLogoutModal();
                }
            };
        }
        
        // ESC key to close (gunakan named function agar bisa di-remove)
        document.addEventListener('keydown', handleEscapeKey);
    }
    
    // ==================== HANDLE ESCAPE KEY ====================
    function handleEscapeKey(e) {
        if (e.key === 'Escape') {
            const overlay = document.getElementById('logout-overlay');
            if (overlay && overlay.classList.contains('active')) {
                closeLogoutModal();
            }
        }
    }
    
    // ==================== CLOSE LOGOUT MODAL ====================
    function closeLogoutModal() {
        const overlay = document.getElementById('logout-overlay');
        if (overlay) {
            overlay.classList.remove('active');
            setTimeout(() => {
                overlay.style.display = 'none';
            }, 300);
        }
        
        // Remove escape key listener
        document.removeEventListener('keydown', handleEscapeKey);
    }
    
    // ==================== CONFIRM LOGOUT ====================
    function confirmLogout() {
        // ✅ Clear semua session data
        sessionStorage.removeItem("loggedInUser");
        sessionStorage.removeItem("authToken");
        
        // Close logout modal
        closeLogoutModal();
        
        // Show success modal
        showSuccessModal();
        
        // Redirect after 1.5 seconds
        setTimeout(() => {
            window.location.href = 'Homepage.html';
        }, 1500);
    }
    
    // ==================== SHOW SUCCESS MODAL ====================
    function showSuccessModal() {
        const successOverlay = document.getElementById('logout-success-overlay');
        if (successOverlay) {
            successOverlay.style.display = 'flex';
            setTimeout(() => successOverlay.classList.add('active'), 10);
            
            // Auto close after 1.3 seconds
            setTimeout(() => {
                successOverlay.classList.remove('active');
                setTimeout(() => {
                    successOverlay.style.display = 'none';
                }, 300);
            }, 1300);
        }
    }
    
    
    // ==================== INITIALIZE ====================
    function init() {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', checkLoginStatus);
        } else {
            checkLoginStatus();
        }
    }
    

    // Start
    init();
    
})();