# Combat Event to Battle Scene Integration Guide

## Overview

This guide explains how to implement the new combat event system that allows players to fight combat encounters and loads the BattleScene with team data (characters, weapons, etc.) and terrain information (plains, mountain, road, etc.).

## 🎯 Features Implemented

### 1. **Combat Data Transfer System**
- **File**: `Assets/Scripts/BattleSetup/CombatDataTransfer.cs`
- **Purpose**: Transfers team data, enemy data, and environmental information between scenes
- **Features**:
  - Team character combat data (stats, equipment, resources)
  - Enemy combat data (health, armor class, threat level)
  - Environmental context (terrain type, weather, time of day)
  - Legacy compatibility with existing BattleSetupData

### 2. **Combat Scene Manager**
- **File**: `Assets/Scripts/BattleSetup/CombatSceneManager.cs`
- **Purpose**: Manages the transition from travel events to battle scenes
- **Features**:
  - Loads battle scene with proper data transfer
  - Sets up terrain based on combat location
  - Manages team data collection from multiple sources
  - Handles return to map after battle

### 3. **Enhanced Battle Setup**
- **File**: `Assets/Scripts/BattleScene/EnhancedBattleSetup.cs`
- **Purpose**: Extends existing BattleSetup with rich combat data
- **Features**:
  - Terrain configuration in battle scene
  - UI updates with battle context
  - Enhanced character stat application
  - Debug and monitoring tools

### 4. **Updated Combat Event Integration**
- **File**: `Assets/Scripts/Events/CombatEventIntegration.cs` (modified)
- **Purpose**: Connects the new system with existing combat events
- **Features**:
  - Uses CombatSceneManager for battle transitions
  - Fallback to legacy systems when needed
  - Proper error handling and logging

## 🚀 Setup Instructions

### Step 1: Add CombatSceneManager to Your Map Scene

1. **Create the Manager GameObject**:
   ```
   In your MapScene2 (or main travel scene):
   1. Create an empty GameObject
   2. Name it "CombatSceneManager"
   3. Add the CombatSceneManager component
   ```

2. **Configure the Manager**:
   ```
   In the CombatSceneManager inspector:
   - Battle Scene Name: "BattleScene" (or your battle scene name)
   - Show Debug Logs: ✓ (recommended for testing)
   - Terrain Generator: (will auto-find BFMTerrainGenerator)
   ```

### Step 2: Add EnhancedBattleSetup to Your Battle Scene

1. **Enhance Battle Setup**:
   ```
   In your BattleScene:
   1. Find the GameObject with BattleSetup component
   2. Add the EnhancedBattleSetup component to the same GameObject
   3. Configure the component settings
   ```

2. **Configure Enhanced Setup**:
   ```
   In the EnhancedBattleSetup inspector:
   - Use Enhanced Setup: ✓
   - Battle Context Text: (drag a UI Text element for battle info)
   - Terrain Generator: (will auto-find BFMTerrainGenerator)
   - Show Debug Logs: ✓ (recommended for testing)
   ```

### Step 3: Verify Combat Event Integration

1. **Check CombatEventIntegration**:
   ```
   In your MapScene2:
   1. Find the GameObject with CombatEventIntegration component
   2. Ensure it's properly configured with popup references
   3. The system will automatically use the new CombatSceneManager
   ```

## 🎮 How It Works

### 1. **Combat Event Triggered**
```
Player travels on map → Travel Event System → Combat Event occurs → Combat popup appears
```

### 2. **Player Chooses to Fight**
```
Player clicks "ATTACK!" → CombatEventIntegration → CombatSceneManager → Battle scene loads
```

### 3. **Data Transfer Process**
```
1. CombatDataTransfer.InitializeCombatSession() is called
2. Team data is collected from MainTeamSelectScript/GameStateManager/PlayerPrefs
3. Enemy data is extracted from combat event
4. Terrain and weather information is captured
5. Legacy BattleSetupData is populated for compatibility
6. Battle scene is loaded
```

### 4. **Battle Scene Setup**
```
1. EnhancedBattleSetup detects combat session data
2. Terrain is configured based on travel location
3. UI is updated with battle context
4. Character placement proceeds using existing BattleSetup
5. Enhanced stats are applied to characters
```

### 5. **Battle End**
```
Battle completes → EnhancedBattleSetup.EndBattleSession() → Return to map scene
```

## 🌍 Terrain System

### Supported Terrain Types
- **Plains**: Open grasslands (BFMTerrainType.Plain)
- **Forest**: Dense woodland (BFMTerrainType.Forest)
- **Mountain**: Rocky mountain terrain (BFMTerrainType.Mountain)
- **River**: Along flowing water (defaults to Plain)
- **Lake**: Near peaceful lake (defaults to Plain)
- **Ocean**: Along coastline (defaults to Plain)

### Environmental Features
- **Roads**: Well-traveled paths
- **Bridges**: Stone crossings
- **Towns/Villages**: Settlement areas
- **Tunnels**: Underground passages
- **Harbors**: Coastal trading posts

### Battle Context Examples
```
"Battle on a well-traveled road in open grasslands"
"Battle in dense woodland during evening (clear weather)"
"Battle at a stone bridge in rocky mountain terrain"
```

## 📊 Data Flow

### Team Character Data
```csharp
TeamCharacter → TeamCharacterCombatData:
- Name, gender, core stats (STR, DEX, CON, WIS, PER)
- Combat stats (HP, AC) calculated from attributes
- Equipment (weapons, armor)
- Resources (gold, silver, copper)
```

### Enemy Data
```csharp
EnemyCharacterData → EnemyCombatData:
- Enemy name and type
- Health, armor class, threat level
- Preferred weapons
- Source data reference
```

### Environmental Data
```csharp
TravelEventContext → CombatSessionData:
- Battle location coordinates
- Terrain type and features
- Weather conditions
- Time of day
```

## 🔧 Integration Points

### With Existing Systems

1. **Travel Event System**: Automatically triggered during combat events
2. **Team Selection**: Uses saved team data from character creation
3. **Battle Setup**: Compatible with existing character placement system
4. **Enemy System**: Works with EnemyCharacterData assets
5. **UI System**: Integrates with existing combat popups

### Data Sources Priority
```
1. MainTeamSelectScript.GetConfiguredCharacters() (if in scene)
2. GameStateManager.Instance.savedTeam (persistent data)
3. PlayerPrefs (fallback for individual character data)
```

## 🐛 Troubleshooting

### Common Issues

1. **"No team members found" Error**:
   ```
   Solution: Ensure team data is saved properly:
   - Create characters in Team Select scene
   - Click "Save Game" or "Proceed to Battle"
   - Check GameStateManager.Instance.savedTeam is populated
   ```

2. **"CombatSceneManager not found" Warning**:
   ```
   Solution: Add CombatSceneManager to your map scene:
   - Create empty GameObject in MapScene2
   - Add CombatSceneManager component
   - Configure battle scene name
   ```

3. **Terrain not changing in battle**:
   ```
   Solution: Ensure BFMTerrainGenerator is properly set up:
   - Add BFMTerrainGenerator to battle scene
   - Assign to EnhancedBattleSetup.terrainGenerator field
   - Check terrain type conversion in logs
   ```

4. **Battle scene not loading**:
   ```
   Solution: Check Build Settings:
   - Ensure "BattleScene" is added to Build Settings
   - Verify scene name matches CombatSceneManager.battleSceneName
   - Check console for scene loading errors
   ```

### Debug Features

1. **Enable Debug Logs**:
   ```
   - CombatSceneManager: showDebugLogs = true
   - EnhancedBattleSetup: showDebugLogs = true
   ```

2. **Use Context Menu Commands**:
   ```
   - CombatSceneManager: "Start Test Combat"
   - EnhancedBattleSetup: "Debug Combat Session"
   ```

3. **Check Combat Session Data**:
   ```csharp
   CombatDataTransfer.DebugLogSession(); // Call in console or script
   ```

## 🎯 Testing the System

### 1. **Basic Test**
```
1. Start game → Create team → Travel on map
2. Trigger combat event (wait for random or use debug)
3. Choose "ATTACK!" in combat popup
4. Verify battle scene loads with correct terrain
5. Check console logs for data transfer info
```

### 2. **Terrain Test**
```
1. Travel to different terrain types (forest, mountain, plains)
2. Trigger combat in each location
3. Verify battle terrain matches travel terrain
4. Check UI shows correct battle context
```

### 3. **Team Data Test**
```
1. Create characters with different equipment
2. Start combat and check character stats in battle
3. Verify weapons and armor are properly equipped
4. Check combat stats (HP, AC) are calculated correctly
```

## 🔮 Future Enhancements

### Planned Features
- **Weather Effects**: Visual weather in battle scene
- **Time of Day Lighting**: Dynamic lighting based on combat time
- **Terrain Modifiers**: Stat bonuses/penalties based on terrain
- **Equipment Integration**: Full equipment system in combat
- **Experience Rewards**: Post-combat character progression

### Extension Points
- **Custom Terrain Types**: Add new BFMTerrainType values
- **Environmental Hazards**: Weather-based combat effects
- **Dynamic Enemy Scaling**: Terrain-based enemy modifications
- **Post-Battle Events**: Consequences based on victory/defeat

## 📝 Notes

- The system maintains full backward compatibility with existing battle setup
- All enhanced features are optional and can be disabled
- Legacy BattleSetupData is still populated for existing systems
- Debug logging provides detailed information for troubleshooting
- The system gracefully degrades when components are missing

---

## Summary

This combat integration system provides:
✅ **Rich Data Transfer**: Team stats, equipment, and environmental context
✅ **Terrain-Based Battles**: Dynamic battle environments based on travel location  
✅ **Seamless Integration**: Works with existing combat and travel systems
✅ **Robust Fallbacks**: Graceful degradation when components are missing
✅ **Debug Support**: Comprehensive logging and testing tools

The system transforms simple combat events into rich, contextual battle experiences that reflect where and when the fight takes place, while maintaining full compatibility with existing game systems.
