(function() {
    'use strict';
    
    // ==================== DOM ELEMENTS ====================
    const elements = {
        logo: null,
        loginBtn: null, // Ini akan di-update oleh logout.js
        playBtn: null,
        leaderboardBtn: null,
        heroTitle: null,
        heroSubtitle: 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();
            
            console.log('✅ Homepage initialized successfully');
        } catch (error) {
            console.error('Error initializing homepage:', error);
        }
    }
    
    // ==================== CACHE ELEMENTS ====================
    function cacheElements() {
        elements.logo = document.querySelector('.logo');
        // ✅ PERBAIKAN: Jangan cache loginBtn, biar logout.js yang handle
        // Cek apakah button Login atau Logout
        elements.loginBtn = document.querySelector('.btn-login') || document.querySelector('.btn-logout');
        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');
    }
    
    // ==================== VALIDATE ELEMENTS ====================
    function validateElements() {
        const requiredElements = ['logo', 'playBtn'];
        const missingElements = requiredElements.filter(key => !elements[key]);
        
        if (missingElements.length > 0) {
            console.warn('Missing elements:', missingElements);
            return false;
        }
        
        return true;
    }
    
    // ==================== EVENT LISTENERS ====================
    function setupEventListeners() {
        // Logo click - reload page
        if (elements.logo) {
            elements.logo.addEventListener('click', handleLogoClick);
        }
        
        // ✅ PERBAIKAN: JANGAN tambah event listener ke loginBtn
        // Biar logout.js yang handle login/logout button
        
        // 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 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' to login (hanya jika belum login)
        if (e.key === 'l' || e.key === 'L') {
            const loginBtn = document.querySelector('.btn-login');
            if (loginBtn) {
                loginBtn.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
    };
    
    // ==================== CLEANUP ====================
    window.cleanupHomepage = function() {
        // Remove event listeners
        if (elements.logo) {
            elements.logo.removeEventListener('click', handleLogoClick);
        }
        
        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();
    
})();