/**
 * Smart Save Manager
 * Intelligently handles save data for both singleplayer and multiplayer modes
 */

class SmartSaveManager {
    constructor() {
        this.isMultiplayer = false;
        this.serverPlayerData = null;
        this.localSaveData = null;
        this.gameInitializer = null;
        
        console.log('[SMART SAVE] SmartSaveManager initialized');
    }
    
    setMultiplayerMode(isMultiplayer, gameInitializer = null) {
        const oldMode = this.isMultiplayer;
        this.isMultiplayer = isMultiplayer;
        this.gameInitializer = gameInitializer;
        
        console.log(`[SMART SAVE] Mode change: ${oldMode ? 'multiplayer' : 'singleplayer'} -> ${isMultiplayer ? 'multiplayer' : 'singleplayer'}`);
        console.log(`[SMART SAVE] Set to ${isMultiplayer ? 'multiplayer' : 'singleplayer'} mode`);
        
        if (isMultiplayer && gameInitializer) {
            // Load server data when switching to multiplayer
            this.loadServerData();
        }
    }
    
    // Load player data (intelligently chooses source)
    async loadPlayerData() {
        if (this.isMultiplayer) {
            return await this.loadServerData();
        } else {
            return await this.loadLocalData();
        }
    }
    
    // Save player data (intelligently chooses destination)
    async savePlayerData(gameData) {
        if (this.isMultiplayer) {
            return await this.saveServerData(gameData);
        } else {
            return await this.saveLocalData(gameData);
        }
    }
    
    // Load server data
    async loadServerData() {
        try {
            if (!this.gameInitializer || !this.gameInitializer.socket) {
                // Don't warn during initialization - this is expected before socket is ready
                // console.warn('[SMART SAVE] No multiplayer connection available');
                return null;
            }
            
            console.log('[SMART SAVE] Loading server player data');
            
            // Request data from server
            this.gameInitializer.loadGameDataFromServer();
            
            // Return cached server data if available
            return this.serverPlayerData;
        } catch (error) {
            console.error('[SMART SAVE] Error loading server data:', error);
            return null;
        }
    }
    
    // Save server data (DISABLED - client should not send data to server)
    async saveServerData(gameData) {
        console.warn('[SMART SAVE] Client save disabled - server is authoritative');
        return true; // Pretend it worked to avoid client errors
    }
    
    // Load local data
    async loadLocalData() {
        try {
            console.log('[SMART SAVE] Loading local save data');
            
            // Use existing local save system
            if (window.mainMenu && window.mainMenu.loadGame) {
                const saveData = await window.mainMenu.loadGame(1); // Load slot 1
                this.localSaveData = saveData;
                return saveData;
            }
            
            // Fallback to localStorage
            const saveKey = 'gso_save_slot_1';
            const saveData = localStorage.getItem(saveKey);
            
            if (saveData) {
                const parsed = JSON.parse(saveData);
                this.localSaveData = parsed;
                return parsed;
            }
            
            return null;
        } catch (error) {
            console.error('[SMART SAVE] Error loading local data:', error);
            return null;
        }
    }
    
    // Save local data
    async saveLocalData(gameData) {
        try {
            // Don't save locally when in multiplayer mode
            if (this.isMultiplayer) {
                console.log('[SMART SAVE] Skipping local save - in multiplayer mode');
                return true;
            }
            
            console.log('[SMART SAVE] Saving locally');
            
            // Use existing local save system
            if (window.mainMenu && window.mainMenu.saveGame) {
                await window.mainMenu.saveGame(1, gameData); // Save to slot 1
                this.localSaveData = gameData;
                return true;
            }
            
            // Fallback to localStorage
            const saveKey = 'gso_save_slot_1';
            localStorage.setItem(saveKey, JSON.stringify(gameData));
            this.localSaveData = gameData;
            
            return true;
        } catch (error) {
            console.error('[SMART SAVE] Error saving local data:', error);
            return false;
        }
    }
    
    // Apply server data to game
    applyServerDataToGame(serverData) {
        console.log('[SMART SAVE] Applying server data to game');
        
        this.serverPlayerData = serverData;
        
        // Apply to game if game is running (try both methods)
        if (window.game) {
            console.log('[SMART SAVE] Game is available, checking for data loading methods');
            console.log('[SMART SAVE] - loadPlayerData:', !!window.game.loadPlayerData);
            console.log('[SMART SAVE] - loadServerPlayerData:', !!window.game.loadServerPlayerData);
            
            if (window.game.loadServerPlayerData) {
                console.log('[SMART SAVE] Using loadServerPlayerData method');
                window.game.loadServerPlayerData(serverData);
                console.log('[SMART SAVE] Server data applied to game, forcing UI refresh');
                
                // Force UI refresh after applying server data
                if (window.game.systems && window.game.systems.ui && window.game.systems.ui.forceRefreshAllUI) {
                    console.log('[SMART SAVE] Forcing UI refresh after server data application');
                    window.game.systems.ui.forceRefreshAllUI();
                } else {
                    console.warn('[SMART SAVE] UI refresh not available after server data application - systems:', !!window.game.systems, 'ui:', !!window.game.systems?.ui, 'forceRefreshAllUI:', !!window.game.systems?.ui?.forceRefreshAllUI);
                }
            } else if (window.game.loadPlayerData) {
                console.log('[SMART SAVE] Using loadPlayerData method');
                window.game.loadPlayerData(serverData);
                console.log('[SMART SAVE] Server data applied to game, forcing UI refresh');
                
                // Force UI refresh after applying server data
                if (window.game.systems && window.game.systems.ui && window.game.systems.ui.forceRefreshAllUI) {
                    console.log('[SMART SAVE] Forcing UI refresh after server data application');
                    window.game.systems.ui.forceRefreshAllUI();
                } else {
                    console.warn('[SMART SAVE] UI refresh not available after server data application - systems:', !!window.game.systems, 'ui:', !!window.game.systems?.ui, 'forceRefreshAllUI:', !!window.game.systems?.ui?.forceRefreshAllUI);
                    
                    // Try delayed UI refresh since UIManager might not be ready yet
                    console.log('[SMART SAVE] Attempting delayed UI refresh...');
                    setTimeout(() => {
                        if (window.game.systems && window.game.systems.ui && window.game.systems.ui.forceRefreshAllUI) {
                            console.log('[SMART SAVE] Delayed UI refresh successful');
                            window.game.systems.ui.forceRefreshAllUI();
                        } else {
                            console.warn('[SMART SAVE] Delayed UI refresh also failed - systems:', !!window.game.systems, 'ui:', !!window.game.systems?.ui, 'forceRefreshAllUI:', !!window.game.systems?.ui?.forceRefreshAllUI);
                        }
                    }, 2000); // Wait 2 seconds for systems to initialize
                }
            } else {
                console.warn('[SMART SAVE] No data loading method available on game object');
            }
        } else {
            console.warn('[SMART SAVE] Game not available for data application');
        }
        
        // Store for game engine
        if (window.gameInitializer) {
            window.gameInitializer.serverPlayerData = serverData;
        }
    }
    
    // Get current save source info
    getSaveInfo() {
        return {
            isMultiplayer: this.isMultiplayer,
            hasServerData: !!this.serverPlayerData,
            hasLocalData: !!this.localSaveData,
            saveLocation: this.isMultiplayer ? 'Server Database' : 'Local Storage'
        };
    }
    
    // Sync data between local and server (for migration)
    async syncData(direction = 'toServer') {
        if (direction === 'toServer') {
            // Upload local data to server
            const localData = await this.loadLocalData();
            if (localData) {
                await this.saveServerData(localData);
                console.log('[SMART SAVE] Synced local data to server');
            }
        } else {
            // Download server data to local
            const serverData = await this.loadServerData();
            if (serverData) {
                await this.saveLocalData(serverData);
                console.log('[SMART SAVE] Synced server data to local');
            }
        }
    }
}

// Create global instance
window.smartSaveManager = new SmartSaveManager();

console.log('[SMART SAVE] SmartSaveManager loaded and available globally');
