/**
 * Save System Integration
 * Integrates SmartSaveManager with existing game systems
 */

console.log('[SAVE INTEGRATION] Save system integration loading');

// Override the game's save method to use SmartSaveManager
function integrateWithGameEngine() {
    if (window.game && window.game.save) {
        // Store original save method
        const originalSave = window.game.save;
        
        // Override save method
        window.game.save = async function() {
            console.log('[SAVE INTEGRATION] Game save called');
            
            // In multiplayer mode, don't save - server is authoritative
            if (window.smartSaveManager && window.smartSaveManager.isMultiplayer) {
                console.log('[SAVE INTEGRATION] Multiplayer mode - client save disabled, server is authoritative');
                this.showNotification('Server manages your game data', 'info', 2000);
                return true;
            }
            
            try {
                // Get current game data
                const gameData = this.getSaveData ? this.getSaveData() : {};
                
                // Use SmartSaveManager for singleplayer
                if (window.smartSaveManager) {
                    const success = await window.smartSaveManager.savePlayerData(gameData);
                    
                    if (success) {
                        this.showNotification('Game saved!', 'success', 2000);
                    } else {
                        this.showNotification('Save failed!', 'error', 3000);
                    }
                    
                    return success;
                } else {
                    // Fallback to original save
                    return await originalSave.call(this);
                }
            } catch (error) {
                console.error('[SAVE INTEGRATION] Save error:', error);
                this.showNotification('Save error!', 'error', 3000);
                return false;
            }
        };
        
        console.log('[SAVE INTEGRATION] Game save method overridden');
    }
}

// Override the game's load method to use SmartSaveManager
function integrateLoadSystem() {
    if (window.game && window.game.load) {
        // Store original load method
        const originalLoad = window.game.load;
        
        // Override load method
        window.game.load = async function(saveData = null) {
            console.log('[SAVE INTEGRATION] Game load called, using SmartSaveManager');
            
            try {
                let dataToLoad = saveData;
                
                // If no data provided, use SmartSaveManager
                if (!dataToLoad && window.smartSaveManager) {
                    dataToLoad = await window.smartSaveManager.loadPlayerData();
                }
                
                // Load the data
                if (dataToLoad) {
                    if (this.loadPlayerData) {
                        this.loadPlayerData(dataToLoad);
                    } else {
                        // Fallback to original load
                        return await originalLoad.call(this, dataToLoad);
                    }
                    
                    console.log('[SAVE INTEGRATION] Game data loaded successfully');
                    return true;
                } else {
                    console.log('[SAVE INTEGRATION] No save data found, starting fresh');
                    return false;
                }
            } catch (error) {
                console.error('[SAVE INTEGRATION] Load error:', error);
                return false;
            }
        };
        
        console.log('[SAVE INTEGRATION] Game load method overridden');
    }
}

// Add server data loading method to game
function addServerDataSupport() {
  if (window.game) {
    // Store pending server data for later application
    window.game.pendingServerData = null;
    
    window.game.loadServerPlayerData = function(serverData) {
      console.log('[SAVE INTEGRATION] Loading server player data into game');
      console.log('[SAVE INTEGRATION] Server data received:', serverData);
      console.log('[SAVE INTEGRATION] Server data type:', typeof serverData);
      console.log('[SAVE INTEGRATION] Server data keys:', serverData ? Object.keys(serverData) : 'No data');
      console.log('[SAVE INTEGRATION] Game systems available:', this.systems ? Object.keys(this.systems) : 'No systems');
      
      // Store server data for later if systems aren't ready
      if (!this.systems || Object.keys(this.systems).length === 0) {
        console.log('[SAVE INTEGRATION] Game systems not ready, storing data for later');
        this.pendingServerData = serverData;
        return;
      }
      
      console.log('[SAVE INTEGRATION] Game systems ready, applying server data now');
      
      try {
        // Apply player stats
        if (serverData.stats && this.systems && this.systems.player) {
          console.log('[SAVE INTEGRATION] Applying player stats:', serverData.stats);
          console.log('[SAVE INTEGRATION] Player system methods:', Object.getOwnPropertyNames(Object.getPrototypeOf(this.systems.player)));
          
          // Check if load method exists
          if (typeof this.systems.player.load === 'function') {
            this.systems.player.load(serverData.stats);
            console.log('[SAVE INTEGRATION] Player stats applied successfully');
            console.log('[SAVE INTEGRATION] Updated player stats:', this.systems.player.stats);
          } else {
            console.warn('[SAVE INTEGRATION] Player system has no load method, trying direct assignment');
            // Direct assignment as fallback
            if (this.systems.player.stats) {
              Object.assign(this.systems.player.stats, serverData.stats);
              console.log('[SAVE INTEGRATION] Player stats assigned directly:', this.systems.player.stats);
            }
          }
        } else {
          console.warn('[SAVE INTEGRATION] No player system or stats in server data');
          console.log('[SAVE INTEGRATION] Has serverData.stats:', !!serverData?.stats);
          console.log('[SAVE INTEGRATION] Has systems.player:', !!(this.systems?.player));
        }
        
        // Apply inventory
        if (serverData.inventory && this.systems && this.systems.inventory) {
          console.log('[SAVE INTEGRATION] Applying player inventory:', serverData.inventory);
          if (typeof this.systems.inventory.load === 'function') {
            this.systems.inventory.load(serverData.inventory);
          } else {
            console.warn('[SAVE INTEGRATION] Inventory system has no load method');
          }
        }
        
        // Apply ship data
        if (serverData.ship && this.systems && this.systems.ship) {
          console.log('[SAVE INTEGRATION] Applying player ship:', serverData.ship);
          if (typeof this.systems.ship.load === 'function') {
            this.systems.ship.load(serverData.ship);
          } else {
            console.warn('[SAVE INTEGRATION] Ship system has no load method');
          }
        }
        
        // Apply base data
        if (serverData.base && this.systems && this.systems.base) {
          console.log('[SAVE INTEGRATION] Applying player base:', serverData.base);
          if (typeof this.systems.base.load === 'function') {
            this.systems.base.load(serverData.base);
          } else {
            console.warn('[SAVE INTEGRATION] Base system has no load method');
          }
        }
        
        // Show notification
        if (this.showNotification) {
          this.showNotification(`Welcome back! Level ${serverData.stats?.level || 1}`, 'success', 3000);
        }
        
        console.log('[SAVE INTEGRATION] Server player data application completed');
        
        // Force UI update
        if (this.systems && this.systems.ui && this.systems.ui.updateUI) {
          this.systems.ui.updateUI();
          console.log('[SAVE INTEGRATION] Server player data application completed');
        }
        
        // Apply pending server data if any exists
        if (this.pendingServerData) {
          console.log('[SAVE INTEGRATION] Applying pending server data');
          this.loadServerPlayerData(this.pendingServerData);
          this.pendingServerData = null;
        }
      } catch (error) {
        console.error('[SAVE INTEGRATION] Error applying server player data:', error);
        if (this.showNotification) {
          this.showNotification('Failed to load server data!', 'error', 3000);
        }
      }
    };
    
    // Method to check and apply pending server data
    window.game.checkAndApplyPendingServerData = function() {
      if (this.pendingServerData && this.systems && Object.keys(this.systems).length > 0) {
        console.log('[SAVE INTEGRATION] Systems ready, applying pending server data');
        this.loadServerPlayerData(this.pendingServerData);
        this.pendingServerData = null;
      }
    };
    
    // Fallback loadPlayerData method if GameEngine doesn't have it
    if (!window.game.loadPlayerData) {
      window.game.loadPlayerData = window.game.loadServerPlayerData;
    }
    
    console.log('[SAVE INTEGRATION] Server data support added to game');
  }
}

// Add save mode switching to UI
function addSaveModeUI() {
    // Add save mode indicator to UI
    const createSaveModeIndicator = () => {
        const indicator = document.createElement('div');
        indicator.id = 'save-mode-indicator';
        indicator.style.cssText = `
            position: fixed;
            top: 10px;
            right: 10px;
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 8px 12px;
            border-radius: 4px;
            font-size: 12px;
            z-index: 10000;
            display: none;
        `;
        document.body.appendChild(indicator);
        return indicator;
    };
    
    const updateSaveModeIndicator = () => {
        const indicator = document.getElementById('save-mode-indicator') || createSaveModeIndicator();
        
        if (window.smartSaveManager) {
            const info = window.smartSaveManager.getSaveInfo();
            indicator.textContent = `Save: ${info.saveLocation}`;
            indicator.style.display = 'block';
            
            // Color code based on mode
            indicator.style.background = info.isMultiplayer ? 'rgba(0, 100, 200, 0.8)' : 'rgba(0, 150, 0, 0.8)';
        }
    };
    
    // Update indicator when mode changes
    if (window.smartSaveManager) {
        const originalSetMultiplayerMode = window.smartSaveManager.setMultiplayerMode;
        window.smartSaveManager.setMultiplayerMode = function(...args) {
            originalSetMultiplayerMode.apply(this, args);
            updateSaveModeIndicator();
        };
    }
    
    // Initial update
    setTimeout(updateSaveModeIndicator, 1000);
}

// Debug function to check data flow
function debugDataFlow() {
    console.log('[DEBUG] === DATA FLOW DEBUG ===');
    
    // Check GameInitializer
    if (window.gameInitializer) {
        console.log('[DEBUG] GameInitializer exists:', !!window.gameInitializer);
        console.log('[DEBUG] GameInitializer serverPlayerData:', window.gameInitializer.serverPlayerData);
        console.log('[DEBUG] GameInitializer gameMode:', window.gameInitializer.gameMode);
    } else {
        console.log('[DEBUG] GameInitializer NOT found');
    }
    
    // Check game systems
    if (window.game) {
        console.log('[DEBUG] Game exists:', !!window.game);
        console.log('[DEBUG] Game systems:', window.game.systems ? Object.keys(window.game.systems) : 'No systems');
        
        if (window.game.systems && window.game.systems.player) {
            console.log('[DEBUG] Player system exists:', !!window.game.systems.player);
            console.log('[DEBUG] Player stats:', window.game.systems.player.stats);
            console.log('[DEBUG] Player credits:', window.game.systems.player.stats?.credits);
        }
    } else {
        console.log('[DEBUG] Game NOT found');
    }
    
    // Check SmartSaveManager
    if (window.smartSaveManager) {
        console.log('[DEBUG] SmartSaveManager exists:', !!window.smartSaveManager);
        console.log('[DEBUG] SmartSaveManager mode:', window.smartSaveManager.isMultiplayer ? 'multiplayer' : 'singleplayer');
    } else {
        console.log('[DEBUG] SmartSaveManager NOT found');
    }
    
    console.log('[DEBUG] === END DEBUG ===');
}

// Debug function available for manual testing
window.debugDataFlow = debugDataFlow;

// Enhanced debug function for connection testing
window.debugConnectionState = function() {
    console.log('=== CONNECTION STATE DEBUG ===');
    console.log('GameInitializer exists:', !!window.gameInitializer);
    console.log('GameInitializer socket connected:', !!window.gameInitializer?.socket?.connected);
    console.log('GameInitializer gameMode:', window.gameInitializer?.gameMode);
    console.log('GameInitializer serverPlayerData:', !!window.gameInitializer?.serverPlayerData);
    console.log('SmartSaveManager exists:', !!window.smartSaveManager);
    console.log('SmartSaveManager mode:', window.smartSaveManager?.isMultiplayer ? 'multiplayer' : 'singleplayer');
    console.log('Game exists:', !!window.game);
    console.log('Game isRunning:', window.game?.isRunning);
    console.log('=== END CONNECTION DEBUG ===');
};

// Initialize integration when DOM is ready
function initializeIntegration() {
    console.log('[SAVE INTEGRATION] Initializing save system integration');
    
    // Wait for game to be ready
    const checkGameReady = () => {
        if (window.game) {
            integrateWithGameEngine();
            integrateLoadSystem();
            addServerDataSupport();
            addSaveModeUI();
            console.log('[SAVE INTEGRATION] Integration complete');
        } else {
            setTimeout(checkGameReady, 500);
        }
    };
    
    checkGameReady();
}

// Auto-initialize
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeIntegration);
} else {
    initializeIntegration();
}

console.log('[SAVE INTEGRATION] Save system integration loaded');
