// ==========================
// LOGOUT SYSTEM WITH PHP INTEGRATION
// ==========================

document.addEventListener("DOMContentLoaded", () => {
    checkLoginStatus();
    setupLogoutListeners();
});

// Cek status login dan update button
function checkLoginStatus() {
    const loggedInUser = sessionStorage.getItem("loggedInUser");
    const authToken = localStorage.getItem("authToken"); // Cek token juga
    const loginBtn = document.querySelector('.login-btn, .logout-btn'); // Cari button
    
    if (!loginBtn) return;
    
    // Kalau ada user login ATAU ada authToken
    if (loggedInUser || authToken) {
        // User sudah login - ubah jadi logout button
        loginBtn.textContent = 'Logout';
        loginBtn.className = 'logout-btn'; // Set class langsung
        loginBtn.onclick = showLogoutConfirmation;
    } else {
        // User belum login - tampilkan login button
        loginBtn.textContent = 'Login';
        loginBtn.className = 'login-btn'; // Set class langsung
        loginBtn.onclick = () => window.location.href = 'Login.html';
    }
}

// Setup event listeners untuk logout modals
function setupLogoutListeners() {
    const btnLogoutCancel = document.getElementById('btn-logout-cancel');
    const btnLogoutConfirm = document.getElementById('btn-logout-confirm');
    const logoutOverlay = document.getElementById('logout-overlay');
    
    if (btnLogoutCancel) {
        btnLogoutCancel.addEventListener('click', hideLogoutConfirmation);
    }
    
    if (btnLogoutConfirm) {
        btnLogoutConfirm.addEventListener('click', performLogout);
    }
    
    // Close modal ketika klik di luar
    if (logoutOverlay) {
        logoutOverlay.addEventListener('click', (e) => {
            if (e.target === logoutOverlay) {
                hideLogoutConfirmation();
            }
        });
    }
}

// Tampilkan konfirmasi logout
function showLogoutConfirmation() {
    const overlay = document.getElementById('logout-overlay');
    if (overlay) {
        overlay.style.display = 'flex';
    }
}

// Sembunyikan konfirmasi logout
function hideLogoutConfirmation() {
    const overlay = document.getElementById('logout-overlay');
    if (overlay) {
        overlay.style.display = 'none';
    }
}

// Perform logout dengan integrasi PHP
async function performLogout() {
    try {
        // Panggil PHP untuk hapus session
        const response = await fetch("http://localhost/Kelompok06_2048/Logout.php", {
            method: "POST",
            headers: {
                'Content-Type': 'application/json'
            }
        });

        const result = await response.json();
        
        // Hapus data dari localStorage & sessionStorage
        localStorage.removeItem("authToken");
        localStorage.removeItem("username");
        sessionStorage.removeItem("loggedInUser");
        sessionStorage.removeItem("showTutorial");
        
        // Sembunyikan confirmation modal
        hideLogoutConfirmation();
        
        // Tampilkan success modal
        showLogoutSuccess();
        
        // Setelah 2 detik, reload/redirect ke homepage
        setTimeout(() => {
            window.location.href = "Homepage.html";
        }, 2000);
        
    } catch (error) {
        console.error("Logout error:", error);
        
        // Kalau gagal koneksi ke PHP, tetap logout dari client side
        localStorage.removeItem("authToken");
        localStorage.removeItem("username");
        sessionStorage.removeItem("loggedInUser");
        sessionStorage.removeItem("showTutorial");
        
        // Tampilkan error modal (opsional)
        showLogoutError();
        
        // Tetap redirect setelah 2 detik
        setTimeout(() => {
            window.location.href = "Homepage.html";
        }, 2000);
    }
}

// Tampilkan logout success
function showLogoutSuccess() {
    const overlay = document.getElementById('logout-success-overlay');
    if (overlay) {
        overlay.style.display = 'flex';
    }
}

// Tampilkan logout error (OPSIONAL - tambahkan modal error jika mau)
function showLogoutError() {
    // Bisa pakai alert sederhana atau buat modal error sendiri
    console.log("Logout gagal terhubung ke server, tapi data lokal sudah dihapus");
    
    // Atau tetap tampilkan success (karena client-side logout berhasil)
    showLogoutSuccess();
}