/**
 * Game Initializer
 * Handles initialization of multiplayer game modes
 */

console.log('[GAME INITIALIZER] GameInitializer.js script loaded');

class GameInitializer {
    constructor() {
        console.log('[GAME INITIALIZER] Constructor called');
        this.gameMode = 'multiplayer';
        this.serverData = null;
        this.authToken = null;
        this.currentUser = null;
        this.socket = null;
        this.apiBaseUrl = 'https://api.korvarix.com/api'; // API Server
        this.gameServerUrl = 'https://api.korvarix.com'; // Game Server for Socket.IO
    }
    
    updateServerUrls(apiUrl, gameUrl) {
        console.log('[GAME INITIALIZER] Updating server URLs:', { apiUrl, gameUrl });
        this.apiBaseUrl = apiUrl;
        this.gameServerUrl = gameUrl;
    }
    
    initializeMultiplayer(server, serverData, authToken, currentUser) {
        console.log('[GAME INITIALIZER] Initializing multiplayer game mode');
        this.gameMode = 'multiplayer';
        this.serverData = { ...server, ...serverData };
        this.authToken = authToken;
        this.currentUser = currentUser;
        
        // Initialize Socket.IO connection
        this.initializeSocketConnection();
        
        // Initialize game systems with multiplayer support
        this.initializeGameSystems();
        
        // Update UI for multiplayer mode
        this.updateUIForMultiplayerMode();
        
        console.log('[GAME INITIALIZER] Multiplayer game initialized');
    }
    
    initializeSocketConnection() {
        if (!this.serverData) {
            console.error('[GAME INITIALIZER] No server data for socket connection');
            return;
        }
        
        console.log('[GAME INITIALIZER] Initializing Socket.IO connection');
        
        // Check if we're in local mode and should use mock socket
        if (this.gameServerUrl.includes('localhost') && window.localServerManager && window.localServerManager.localServer) {
            console.log('[GAME INITIALIZER] Using mock socket for local mode');
            this.socket = window.localServerManager.localServer.createMockSocket();
            
            // Trigger connected event immediately since mock socket auto-connects
            setTimeout(() => {
                this.onSocketConnected();
            }, 200);
            
            return;
        }
        
        // Connect to the game server (different from API server)
        this.socket = io(this.gameServerUrl, {
            auth: {
                token: this.authToken,
                serverId: this.serverData.id
            }
        });
        
        // Socket event handlers
        this.socket.on('connect', () => {
            console.log('[GAME INITIALIZER] Connected to server');
            this.onSocketConnected();
        });
        
        this.socket.on('disconnect', () => {
            console.log('[GAME INITIALIZER] Disconnected from server');
            this.onSocketDisconnected();
        });
        
        this.socket.on('error', (error) => {
            console.error('[GAME INITIALIZER] Socket error:', error);
        });
        
        this.socket.on('force_disconnect', (data) => {
            console.warn('[GAME INITIALIZER] Force disconnected:', data);
            this.onForceDisconnect(data);
        });
        
        // Game-specific events
        this.socket.on('playerJoined', (data) => {
            console.log('[GAME INITIALIZER] Player joined:', data);
            this.onPlayerJoined(data);
        });
        
        this.socket.on('playerLeft', (data) => {
            console.log('[GAME INITIALIZER] Player left:', data);
            this.onPlayerLeft(data);
        });
        
        this.socket.on('gameUpdate', (data) => {
            console.log('[GAME INITIALIZER] Game update:', data);
            this.onGameUpdate(data);
        });
        
        this.socket.on('chatMessage', (data) => {
            console.log('[GAME INITIALIZER] Chat message:', data);
            this.onChatMessage(data);
        });
    }
    
    onSocketConnected() {
        // Join the server room
        this.socket.emit('joinServer', {
            serverId: this.serverData.id,
            userId: this.currentUser.userId,
            username: this.currentUser.username
        });
        
        // Show connected status
        this.showConnectionStatus('Connected', 'success');
    }
    
    onSocketDisconnected() {
        // Show disconnected status
        this.showConnectionStatus('Disconnected', 'error');
    }
    
    onPlayerJoined(data) {
        // Handle player joining
        this.updatePlayerList();
        this.showNotification(`${data.username} joined the server`, 'info');
    }
    
    onPlayerLeft(data) {
        // Handle player leaving
        this.updatePlayerList();
        this.showNotification(`${data.username} left the server`, 'info');
    }
    
    onGameUpdate(data) {
        // Handle game state updates
        if (window.game && window.game.handleServerUpdate) {
            window.game.handleServerUpdate(data);
        }
    }
    
    onChatMessage(data) {
        // Handle chat messages
        if (window.game && window.game.handleChatMessage) {
            window.game.handleChatMessage(data);
        }
    }
    
    onForceDisconnect(data) {
        // Handle forced disconnection from server
        console.warn('[GAME INITIALIZER] Force disconnected by server:', data);
        
        // Show notification to user
        if (window.game && window.game.showNotification) {
            window.game.showNotification(
                `Disconnected: ${data.reason}`, 
                'warning', 
                10000
            );
        }
        
        // Disconnect the socket
        if (this.socket) {
            this.socket.disconnect();
        }
        
        // Clean up multiplayer mode
        if (window.game) {
            window.game.setMultiplayerMode(false);
        }
        
        // Return to main menu after a delay
        setTimeout(() => {
            if (window.liveMainMenu) {
                window.liveMainMenu.showLoginSection();
            }
        }, 2000);
    }
    
    initializeGameSystems() {
        console.log('[GAME INITIALIZER] Initializing game systems');
        
        // Wait for the main game script to be ready
        if (typeof window.game !== 'undefined') {
            console.log('[GAME INITIALIZER] window.game is available, calling setupGameSystems');
            this.setupGameSystems();
        } else {
            console.log('[GAME INITIALIZER] window.game not available, waiting 100ms');
            // Wait for the game to be initialized
            setTimeout(() => this.initializeGameSystems(), 100);
        }
    }
    
    setupGameSystems() {
        if (!window.game) {
            console.error('[GAME INITIALIZER] Game not available');
            return;
        }
        
        console.log('[GAME INITIALIZER] Setting up game systems for multiplayer mode');
        
        // Configure game for multiplayer mode
        console.log('[GAME INITIALIZER] Configuring for multiplayer mode');
        window.game.setMultiplayerMode(true, this.socket, this.serverData, this.currentUser);
        
        // Game is already set up with save data, just start the game loop
        if (window.game.start) {
            // console.log('[GAME INITIALIZER] Calling start() to begin game loop');
            window.game.start();
        } else if (window.game.startGame) {
            // console.log('[GAME INITIALIZER] Calling startGame(false) - save data already applied');
            window.game.startGame(false); // false = don't load again (save data already applied)
        } else {
            console.error('[GAME INITIALIZER] No start method available on window.game');
        }
        
        console.log('[GAME INITIALIZER] Game systems configured');
    }
    
    updateUIForMultiplayerMode() {
        // Update UI elements to show multiplayer mode
        const playerName = document.getElementById('playerName');
        if (playerName && this.currentUser) {
            playerName.textContent = this.currentUser.username;
        }
        
        // Show multiplayer-specific UI elements
        this.showMultiplayerUI();
        
        // Show server info
        this.showServerInfo();
    }
    
    hideMultiplayerUI() {
        // Hide elements that are only relevant in multiplayer
        const chatContainer = document.getElementById('chatContainer');
        if (chatContainer) {
            chatContainer.classList.add('hidden');
        }
        
        const playerList = document.getElementById('playerList');
        if (playerList) {
            playerList.classList.add('hidden');
        }
    }
    
    showMultiplayerUI() {
        // Show multiplayer-specific elements
        const chatContainer = document.getElementById('chatContainer');
        if (chatContainer) {
            chatContainer.classList.remove('hidden');
        }
        
        const playerList = document.getElementById('playerList');
        if (playerList) {
            playerList.classList.remove('hidden');
        }
    }
    
    showServerInfo() {
        // Add server information to the UI
        const header = document.querySelector('.game-header');
        if (header && !header.querySelector('.server-info')) {
            const serverInfo = document.createElement('div');
            serverInfo.className = 'server-info';
            serverInfo.innerHTML = `
                <i class="fas fa-server"></i>
                <span>${this.serverData.name} (${this.serverData.currentPlayers}/${this.serverData.maxPlayers})</span>
            `;
            serverInfo.style.cssText = `
                background: rgba(0, 212, 255, 0.2);
                color: #00d4ff;
                padding: 4px 8px;
                border-radius: 4px;
                font-size: 0.8rem;
                margin-left: 10px;
            `;
            header.appendChild(serverInfo);
        }
    }
    
    showConnectionStatus(status, type) {
        // Show connection status in the UI
        const statusElement = document.getElementById('connectionStatus');
        if (statusElement) {
            statusElement.textContent = status;
            statusElement.className = `connection-status ${type}`;
        }
    }
    
    updatePlayerList() {
        // Update the player list UI
        if (this.socket && this.serverData) {
            // Request updated player list from server
            this.socket.emit('getPlayerList', { serverId: this.serverData.id });
        }
    }
    
    showNotification(message, type = 'info') {
        // Show a notification to the user
        if (window.game && window.game.showNotification) {
            window.game.showNotification(message, type, 3000);
        } else {
            // Fallback to alert
            console.log(`[GAME INITIALIZER] Notification: ${message}`);
        }
    }
    
    // Method to send actions to the server
    sendGameAction(actionType, actionData) {
        if (this.socket && this.gameMode === 'multiplayer') {
            this.socket.emit('gameAction', {
                type: actionType,
                data: actionData,
                userId: this.currentUser.userId,
                serverId: this.serverData.id
            });
        }
    }
    
    // Method to send chat messages
    sendChatMessage(message) {
        if (this.socket && this.gameMode === 'multiplayer') {
            this.socket.emit('chatMessage', {
                message: message,
                userId: this.currentUser.userId,
                username: this.currentUser.username,
                serverId: this.serverData.id
            });
        }
    }
    
    // Cleanup method
    cleanup() {
        console.log('[GAME INITIALIZER] Cleaning up');
        
        if (this.socket) {
            this.socket.disconnect();
            this.socket = null;
        }
        
        this.gameMode = null;
        this.serverData = null;
        this.authToken = null;
        this.currentUser = null;
    }
}

// Create global instance
window.gameInitializer = new GameInitializer();

// Export for use in other scripts
if (typeof module !== 'undefined' && module.exports) {
    module.exports = GameInitializer;
}
