/* ==========================================
   ANIMATION HOMEPAGE - Homepage Controller
   ==========================================
   fitur utama:
   1. updateAuthButton() - Toggle LOGIN/LOGOUT button
   2. handleLogout() - Logout logic dengan PHP
   3. Event listeners untuk semua button & keyboard
   4. Smooth scroll & responsive handling
   ========================================== */

// Animation Homepage.js
(function() {
    'use strict';
    
    /* ==========================================
       DOM ELEMENTS - Cache semua element penting
       ========================================== */
    const elements = {
        logo: null,
        authBtn: null,
        playBtn: null,
        leaderboardBtn: null,
        heroTitle: null,
        heroSubtitle: null,
        logoutOverlay: null,
        logoutFailedOverlay: null
    };
    
    /* ==========================================
       INITIALIZE - Setup saat page load
       ========================================== */
    function init() {
        if (document.readyState === 'loading') {
            // Kalau DOM belum ready, tunggu event
            document.addEventListener('DOMContentLoaded', initAll);
        } else {
            // Kalau sudah ready, langsung init
            initAll();
        }
    }
    
    function initAll() {
        try {
            // Step 1: Cache semua DOM elements
            cacheElements();
            
            // Step 2: Validasi element wajib ada
            if (!validateElements()) {
                console.error('Some required elements are missing');
                return;
            }
            
            // Step 3: Setup event listeners
            setupEventListeners();
            
            // Step 4: Initialize smooth scroll
            initSmoothScroll();
            
            // Step 5: Update button LOGIN/LOGOUT sesuai status
            updateAuthButton();
            
            console.log('✅ Homepage initialized successfully');
        } catch (error) {
            console.error('Error initializing homepage:', error);
        }
    }
    
    /* ==========================================
       CACHE ELEMENTS - Simpan reference ke variable
       ========================================== 
       Kenapa? Biar nggak query DOM berkali-kali (performa)
       ========================================== */
    function cacheElements() {
        elements.logo = document.querySelector('.logo');
        elements.authBtn = document.getElementById('auth-button');
        elements.playBtn = document.querySelector('a[href="2048.html"]');
        elements.leaderboardBtn = document.querySelector('a[href="leaderboard.html"]');
        elements.heroTitle = document.querySelector('.hero-title');
        elements.heroSubtitle = document.querySelector('.hero-subtitle');
        elements.logoutOverlay = document.getElementById('logout-overlay');
        elements.logoutFailedOverlay = document.getElementById('logout-failed-overlay');
    }
    
    /* ==========================================
       VALIDATE ELEMENTS - Cek element wajib ada
       ========================================== */
    function validateElements() {
        // Element yang HARUS ada: logo, authBtn, playBtn
        const requiredElements = ['logo', 'authBtn', 'playBtn'];
        const missingElements = requiredElements.filter(key => !elements[key]);
        
        if (missingElements.length > 0) {
            console.warn('Missing elements:', missingElements);
            return false; // Gagal validasi
        }
        
        return true; // Semua element ada
    }
    
    /* ==========================================
       UPDATE AUTH BUTTON - Toggle LOGIN/LOGOUT
       ========================================== 
       Cek dari localStorage & sessionStorage
       ========================================== */
    function updateAuthButton() {
        // Cek apakah user sudah login
        // 3 cara cek: authToken, username, atau loggedInUser
        const authToken = localStorage.getItem('authToken');
        const username = localStorage.getItem('username');
        const loggedInUser = sessionStorage.getItem('loggedInUser');
        
        if (authToken || username || loggedInUser) {
            //  User SUDAH LOGIN → show LOGOUT button
            elements.authBtn.textContent = 'LOGOUT';
            elements.authBtn.classList.add('logout-mode');
        } else {
            //  User BELUM LOGIN → show LOGIN button
            elements.authBtn.textContent = 'LOGIN';
            elements.authBtn.classList.remove('logout-mode');
        }
    }
    
    /* ==========================================
       SETUP EVENT LISTENERS - Bind semua event
       ========================================== */
    function setupEventListeners() {
        // Logo click → reload homepage
        if (elements.logo) {
            elements.logo.addEventListener('click', handleLogoClick);
        }
        
        // Auth button → login/logout
        if (elements.authBtn) {
            elements.authBtn.addEventListener('click', handleAuthClick);
        }
        
        // Play button → go to game
        if (elements.playBtn) {
            elements.playBtn.addEventListener('click', handlePlayClick);
        }
        
        // Leaderboard button
        if (elements.leaderboardBtn) {
            elements.leaderboardBtn.addEventListener('click', handleLeaderboardClick);
        }
        
        // Keyboard shortcuts (P, L, B)
        document.addEventListener('keydown', handleKeyPress);
        
        // Window events
        window.addEventListener('resize', handleResize);
        window.addEventListener('beforeunload', handleBeforeUnload);
    }
    
    /* ==========================================
       EVENT HANDLERS
       ========================================== */
    
    function handleLogoClick(e) {
        e.preventDefault();
        window.location.href = 'Homepage.html';
    }
    
    /* ==========================================
       HANDLE AUTH CLICK - Login atau Logout
       ========================================== */
    function handleAuthClick(e) {
        // Cek status login dari localStorage & sessionStorage
        const authToken = localStorage.getItem('authToken');
        const username = localStorage.getItem('username');
        const loggedInUser = sessionStorage.getItem('loggedInUser');
        
        if (authToken || username || loggedInUser) {
            // User sudah login → LOGOUT
            handleLogout();
        } else {
            // User belum login → ke halaman LOGIN
            window.location.href = 'Login.html';
        }
    }
    
    /* ==========================================
       HANDLE LOGOUT - Logout Logic dengan PHP
       ========================================== */
    async function handleLogout() {
        try {
            // Step 1: Panggil PHP untuk hapus session di server
            const response = await fetch("http://localhost/Kelompok06_2048/Logout.php", {
                method: "POST"
            });
            
            const data = await response.json();
            
            // Step 2: Hapus token & username dari localStorage
            localStorage.removeItem("authToken");
            localStorage.removeItem("username");
            
            // Step 3: Hapus juga dari sessionStorage
            sessionStorage.removeItem('loggedInUser');
            sessionStorage.removeItem('showTutorial');
            
            // Step 4: Show success modal
            if (elements.logoutOverlay) {
                elements.logoutOverlay.style.display = 'flex';
                
                // Auto close setelah 2 detik & redirect
                setTimeout(() => {
                    elements.logoutOverlay.style.display = 'none';
                    window.location.href = "Homepage.html";
                }, 2000);
            }
            
        } catch (error) {
            console.error('Logout failed:', error);
            
            // Tetap hapus data lokal meski server error
            localStorage.removeItem("authToken");
            localStorage.removeItem("username");
            sessionStorage.removeItem('loggedInUser');
            sessionStorage.removeItem('showTutorial');
            
            // Show error modal
            if (elements.logoutFailedOverlay) {
                elements.logoutFailedOverlay.style.display = 'flex';
                
                // Auto close setelah 2.5 detik
                setTimeout(() => {
                    elements.logoutFailedOverlay.style.display = 'none';
                    window.location.href = "Homepage.html";
                }, 2500);
            }
        }
    }
    
    function handlePlayClick(e) {
        // Allow default behavior (navigate ke 2048.html)
        console.log('Starting game...');
    }
    
    function handleLeaderboardClick(e) {
        // Allow default behavior (navigate ke leaderboard.html)
        console.log('Opening leaderboard...');
    }
    
    /* ==========================================
       KEYBOARD SHORTCUTS
       ========================================== */
    function handleKeyPress(e) {
        // Press 'P' → Play game
        if (e.key === 'p' || e.key === 'P') {
            if (elements.playBtn) {
                elements.playBtn.click();
            }
        }
        
        // Press 'L' → Login/Logout
        if (e.key === 'l' || e.key === 'L') {
            if (elements.authBtn) {
                elements.authBtn.click();
            }
        }
        
        // Press 'B' → Leaderboard (Board)
        if (e.key === 'b' || e.key === 'B') {
            if (elements.leaderboardBtn) {
                elements.leaderboardBtn.click();
            }
        }
    }
    
    function handleResize() {
        // Handle responsive behavior (mobile, tablet, desktop)
        const width = window.innerWidth;
        
        if (width < 768) {
            console.log('Mobile view');
        } else if (width < 1024) {
            console.log('Tablet view');
        } else {
            console.log('Desktop view');
        }
    }
    
    function handleBeforeUnload(e) {
        // Cleanup sebelum page unload
        console.log('Page unloading...');
    }
    
    /* ==========================================
       SMOOTH SCROLL - Untuk anchor links (#)
       ========================================== */
    function initSmoothScroll() {
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function(e) {
                const href = this.getAttribute('href');
                if (href === '#' || !href) return;
                
                e.preventDefault();
                const target = document.querySelector(href);
                
                if (target) {
                    target.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            });
        });
    }
    
    /* ==========================================
       UTILITY FUNCTIONS
       ========================================== */
    function checkBrowserSupport() {
        const features = {
            localStorage: typeof(Storage) !== 'undefined',
            flexbox: CSS.supports('display', 'flex'),
            grid: CSS.supports('display', 'grid')
        };
        
        console.log('Browser support:', features);
        return features;
    }
    
    function isMobile() {
        return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    }
    
    /* ==========================================
       PUBLIC API - Fungsi yang bisa dipanggil dari luar
       ========================================== */
    window.Homepage = {
        init: initAll,
        isMobile: isMobile,
        checkSupport: checkBrowserSupport,
        updateAuthButton: updateAuthButton
    };
    
    /* ==========================================
       CLEANUP - Remove semua event listener
       ========================================== */
    window.cleanupHomepage = function() {
        // Remove event listeners (untuk prevent memory leak)
        if (elements.logo) {
            elements.logo.removeEventListener('click', handleLogoClick);
        }
        
        if (elements.authBtn) {
            elements.authBtn.removeEventListener('click', handleAuthClick);
        }
        
        if (elements.playBtn) {
            elements.playBtn.removeEventListener('click', handlePlayClick);
        }
        
        if (elements.leaderboardBtn) {
            elements.leaderboardBtn.removeEventListener('click', handleLeaderboardClick);
        }
        
        document.removeEventListener('keydown', handleKeyPress);
        window.removeEventListener('resize', handleResize);
        window.removeEventListener('beforeunload', handleBeforeUnload);
        
        console.log('Homepage cleaned up');
    };
    
    // Start initialization saat script load
    init();
    
})(); // IIFE - langsung execute