(function() {
    'use strict';
    
    // CHECK LOGIN STATUS
    function checkLoginStatus() {
        const loggedInUser = sessionStorage.getItem("loggedInUser");
        const loginBtn = document.querySelector('.btn-login');
        
        if (loggedInUser && loginBtn) {
            // Mengubah button login menjadi logout
            loginBtn.textContent = 'Logout';
            loginBtn.classList.remove('btn-login');
            loginBtn.classList.add('btn-logout');
            loginBtn.href = '#';
            loginBtn.replaceWith(loginBtn.cloneNode(true));
            
            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
    // Mencegah halaman refresh secara otomatis dan langsung menampilkan jendela pop-up konfirmasi logout
    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);
            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 (mencegah error double click)
        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 (area gelap)
        if (overlay) {
            overlay.onclick = function(e) {
                if (e.target === overlay) {
                    closeLogoutModal();
                }
            };
        }
        
        // Aktifkan tombol escape untuk menutup modal
        document.addEventListener('keydown', handleEscapeKey);
    }
    
    // HANDLE ESCAPE KEY
    // Menutup jendela pop-up (modal) logout menggunakan tombol keyboard Esc
    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() {
        console.log("Mencoba logout ke server..."); // Debugging

        // Panggil PHP untuk hancurkan sesi server
        fetch('Logout.php') 
            .then(response => {
                console.log("Respon server:", response);
                return response.json(); // Ubah ke JSON biar bisa dicek
            })
            .then(data => {
                console.log("Status Logout:", data);
            
                // Hapus data di browser (Session Storage)
                sessionStorage.removeItem("loggedInUser");
                sessionStorage.removeItem("authToken");
                sessionStorage.clear(); // Bersihkan semuanya biar aman
            
                // Tutup Modal & Redirect
                closeLogoutModal();
                showSuccessModal();
            
                setTimeout(() => {
                    // Redirect ke Homepage
                    window.location.replace('Homepage.html'); 
                }, 1500);
            })
            .catch(error => {
                console.error('Logout error:', error);
                // Fallback: Kalau server error, tetap paksa keluar di tampilan
                sessionStorage.clear();
                window.location.replace('Homepage.html');
            });
    }
    
    // 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
    // Menjamin agar kode tidak mencuri start sebelum elemen HTML tersedia.
    function init() {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', checkLoginStatus);
        } else {
            checkLoginStatus();
        }
    }
    
    init();
    
})();