(function() {
    'use strict';
    
    // ==================== DOM ELEMENTS ====================
    const elements = {
        logo: null,
        authBtn: null,
        playBtn: null,
        leaderboardBtn: null,
        heroTitle: null,
        heroSubtitle: null,
        logoutOverlay: null,
        logoutFailedOverlay: null
    };
    
    // ==================== INITIALIZE ====================
    function init() {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initAll);
        } else {
            initAll();
        }
    }
    
    function initAll() {
        try {
            // Cache DOM elements
            cacheElements();
            
            // Validate elements
            if (!validateElements()) {
                console.error('Some required elements are missing');
                return;
            }
            
            // Setup event listeners
            setupEventListeners();
            
            // Initialize smooth scroll
            initSmoothScroll();
            
            // Check login status and update button
            updateAuthButton();
            
            console.log('✅ Homepage initialized successfully');
        } catch (error) {
            console.error('Error initializing homepage:', error);
        }
    }
    
    // ==================== CACHE ELEMENTS ====================
    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 ====================
    function validateElements() {
        const requiredElements = ['logo', 'authBtn', 'playBtn'];
        const missingElements = requiredElements.filter(key => !elements[key]);
        
        if (missingElements.length > 0) {
            console.warn('Missing elements:', missingElements);
            return false;
        }
        
        return true;
    }
    
    // ==================== UPDATE AUTH BUTTON ====================
    function updateAuthButton() {
        // Cek dari localStorage (authToken & username) atau sessionStorage
        const authToken = localStorage.getItem('authToken');
        const username = localStorage.getItem('username');
        const loggedInUser = sessionStorage.getItem('loggedInUser');
        
        if (authToken || username || loggedInUser) {
            // User is logged in - show LOGOUT button
            elements.authBtn.textContent = 'LOGOUT';
            elements.authBtn.classList.add('logout-mode');
        } else {
            // User is not logged in - show LOGIN button
            elements.authBtn.textContent = 'LOGIN';
            elements.authBtn.classList.remove('logout-mode');
        }
    }
    
    // ==================== EVENT LISTENERS ====================
    function setupEventListeners() {
        // Logo click - reload page
        if (elements.logo) {
            elements.logo.addEventListener('click', handleLogoClick);
        }
        
        // Auth button (Login/Logout)
        if (elements.authBtn) {
            elements.authBtn.addEventListener('click', handleAuthClick);
        }
        
        // Play button
        if (elements.playBtn) {
            elements.playBtn.addEventListener('click', handlePlayClick);
        }
        
        // Leaderboard button
        if (elements.leaderboardBtn) {
            elements.leaderboardBtn.addEventListener('click', handleLeaderboardClick);
        }
        
        // Keyboard shortcuts
        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';
    }
    
    function handleAuthClick(e) {
        // Cek dari localStorage atau sessionStorage
        const authToken = localStorage.getItem('authToken');
        const username = localStorage.getItem('username');
        const loggedInUser = sessionStorage.getItem('loggedInUser');
        
        if (authToken || username || loggedInUser) {
            // User is logged in - perform logout
            handleLogout();
        } else {
            // User is not logged in - go to login page
            window.location.href = 'Login.html';
        }
    }
    
    async function handleLogout() {
        try {
            // Panggil PHP untuk hapus session
            const response = await fetch("http://localhost/Kelompok06_2048/Logout.php", {
                method: "POST"
            });
            
            const data = await response.json();
            
            // Hapus token & username dari localStorage
            localStorage.removeItem("authToken");
            localStorage.removeItem("username");
            
            // Hapus juga dari sessionStorage (jika ada)
            sessionStorage.removeItem('loggedInUser');
            sessionStorage.removeItem('showTutorial');
            
            // Show success modal
            if (elements.logoutOverlay) {
                elements.logoutOverlay.style.display = 'flex';
                
                // Auto close after 2 seconds and redirect to homepage
                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 after 2.5 seconds and redirect anyway
                setTimeout(() => {
                    elements.logoutFailedOverlay.style.display = 'none';
                    window.location.href = "Homepage.html";
                }, 2500);
            }
        }
    }
    
    function handlePlayClick(e) {
        // Allow default behavior (navigate to 2048.html)
        console.log('Starting game...');
    }
    
    function handleLeaderboardClick(e) {
        // Allow default behavior (navigate to leaderboard.html)
        console.log('Opening leaderboard...');
    }
    
    function handleKeyPress(e) {
        // Press 'P' to play
        if (e.key === 'p' || e.key === 'P') {
            if (elements.playBtn) {
                elements.playBtn.click();
            }
        }
        
        // Press 'L' for login/logout
        if (e.key === 'l' || e.key === 'L') {
            if (elements.authBtn) {
                elements.authBtn.click();
            }
        }
        
        // Press 'B' for leaderboard
        if (e.key === 'b' || e.key === 'B') {
            if (elements.leaderboardBtn) {
                elements.leaderboardBtn.click();
            }
        }
    }
    
    function handleResize() {
        // Handle responsive behavior if needed
        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 before page unload
        console.log('Page unloading...');
    }
    
    // ==================== SMOOTH SCROLL ====================
    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 ====================
    window.Homepage = {
        init: initAll,
        isMobile: isMobile,
        checkSupport: checkBrowserSupport,
        updateAuthButton: updateAuthButton
    };
    
    // ==================== CLEANUP ====================
    window.cleanupHomepage = function() {
        // Remove event listeners
        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
    init();
    
})();