using UnityEngine;
using System.Collections;
///
/// Enhanced Travel Event System that provides player choice for combat encounters
/// Integrates CombatEventPopup for better user experience
///
public class EnhancedTravelEventSystem : MonoBehaviour
{
[Header("Enhanced Event System")]
public CombatEventPopup combatEventPopup;
public bool allowRunningAway = true;
[Range(0f, 1f)]
public float runAwaySuccessChance = 0.75f;
public int runAwayHealthPenalty = 5;
[Header("Run Away Messages")]
[TextArea(2, 4)]
public string[] successfulRunAwayMessages = {
"Your party successfully escapes from the enemies!",
"Quick thinking allows your party to avoid the confrontation!",
"Your party slips away unnoticed by the enemies."
};
[TextArea(2, 4)]
public string[] failedRunAwayMessages = {
"The enemies catch up to your party! You take {damage} damage while trying to escape.",
"Your escape attempt fails! The enemies pursue and wound your party for {damage} damage.",
"The enemies block your escape route! Your party suffers {damage} damage in the failed attempt."
};
// Component references
private TravelEventSystem originalEventSystem;
private TravelEventUI eventUI;
// Current combat state
private BattleEventData pendingBattleData;
private TravelEventContext pendingContext;
private bool waitingForCombatDecision = false;
void Start()
{
// Find required components
originalEventSystem = FindFirstObjectByType();
eventUI = FindFirstObjectByType();
if (combatEventPopup == null)
combatEventPopup = FindFirstObjectByType();
if (originalEventSystem == null)
{
Debug.LogError("❌ Enhanced Travel Event System requires a TravelEventSystem component!");
enabled = false;
return;
}
if (combatEventPopup == null)
{
Debug.LogError("❌ Enhanced Travel Event System requires a CombatEventPopup component!");
enabled = false;
return;
}
// Setup combat popup callback
combatEventPopup.OnCombatDecision += HandleCombatDecision;
Debug.Log("✅ Enhanced Travel Event System initialized");
}
void OnDestroy()
{
if (combatEventPopup != null)
combatEventPopup.OnCombatDecision -= HandleCombatDecision;
}
///
/// Enhanced combat event handler that shows popup before battle
/// Call this instead of the original HandleBattleEvent
///
public void HandleEnhancedBattleEvent(BattleEventData battleData, TravelEventContext context, string eventDescription)
{
if (battleData == null || waitingForCombatDecision)
return;
Debug.Log($"🎭 Enhanced battle event triggered: {eventDescription}");
// Store pending battle data
pendingBattleData = battleData;
pendingContext = context;
waitingForCombatDecision = true;
// Show combat popup
combatEventPopup.ShowCombatEncounter(battleData, context, eventDescription);
}
///
/// Handle the player's combat decision from the popup
///
private void HandleCombatDecision(bool chooseToAttack)
{
if (!waitingForCombatDecision || pendingBattleData == null)
return;
waitingForCombatDecision = false;
if (chooseToAttack)
{
HandleAttackChoice();
}
else
{
HandleRunAwayChoice();
}
// Clear pending data
pendingBattleData = null;
pendingContext = null;
}
///
/// Handle when player chooses to attack
///
private void HandleAttackChoice()
{
Debug.Log("⚔️ Player chose to fight! Setting up battle...");
// Call the original battle setup logic
if (originalEventSystem != null)
{
// Use reflection to call the private HandleBattleEvent method
var method = originalEventSystem.GetType().GetMethod("HandleBattleEvent",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
if (method != null)
{
method.Invoke(originalEventSystem, new object[] { pendingBattleData, pendingContext });
}
else
{
Debug.LogError("❌ Could not find HandleBattleEvent method in TravelEventSystem");
// Fallback: just log the battle setup
LogBattleSetup(pendingBattleData);
}
}
}
///
/// Handle when player chooses to run away
///
private void HandleRunAwayChoice()
{
Debug.Log("🏃 Player chose to run away! Rolling for escape...");
if (!allowRunningAway)
{
Debug.Log("❌ Running away is not allowed! Forcing combat...");
HandleAttackChoice();
return;
}
bool escapeSuccessful = Random.value <= runAwaySuccessChance;
if (escapeSuccessful)
{
HandleSuccessfulEscape();
}
else
{
HandleFailedEscape();
}
}
///
/// Handle successful escape attempt
///
private void HandleSuccessfulEscape()
{
string message = successfulRunAwayMessages[Random.Range(0, successfulRunAwayMessages.Length)];
Debug.Log($"✅ Escape successful: {message}");
// Show escape message
if (eventUI != null)
{
eventUI.ShowEventMessage(message, EventType.Discovery, false);
}
else
{
Debug.Log($"📜 ESCAPE: {message}");
}
// Continue travel (no resource penalties for successful escape)
ResumeTravelAfterEvent();
}
///
/// Handle failed escape attempt
///
private void HandleFailedEscape()
{
string message = failedRunAwayMessages[Random.Range(0, failedRunAwayMessages.Length)];
message = message.Replace("{damage}", runAwayHealthPenalty.ToString());
Debug.Log($"❌ Escape failed: {message}");
// Apply health penalty
ApplyRunAwayPenalty();
// Show failure message
if (eventUI != null)
{
eventUI.ShowEventMessage(message, EventType.Hazard, false);
}
else
{
Debug.Log($"📜 ESCAPE FAILED: {message}");
}
// Start combat anyway
StartCoroutine(DelayedCombatStart());
}
///
/// Apply penalties for failed escape attempt
///
private void ApplyRunAwayPenalty()
{
// This would integrate with your character health system
Debug.Log($"❤️ Party takes {runAwayHealthPenalty} damage from failed escape attempt");
// TODO: Actually apply health damage to party members
// Example: TeamHealthManager.ApplyDamageToParty(runAwayHealthPenalty);
}
///
/// Resume travel after successful escape
///
private void ResumeTravelAfterEvent()
{
// The travel system should continue normally
Debug.Log("🚗 Resuming travel after event...");
// No need to stop travel for successful escapes
}
///
/// Start combat after a delay (for failed escape)
///
private IEnumerator DelayedCombatStart()
{
yield return new WaitForSeconds(3f); // Wait for escape message to be read
Debug.Log("⚔️ Starting combat after failed escape...");
HandleAttackChoice();
}
///
/// Fallback battle setup logging
///
private void LogBattleSetup(BattleEventData battleData)
{
Debug.Log($"⚔️ Setting up battle: {battleData.enemyCount} {battleData.enemyType}(s)");
if (battleData.enemyCharacterData != null)
{
Debug.Log($"🎯 Using enemy data: {battleData.enemyCharacterData.enemyName}");
Debug.Log($"📊 Enemy stats: HP={battleData.enemyCharacterData.maxHealth}, " +
$"AC={battleData.enemyCharacterData.armorClass}, " +
$"Threat={battleData.enemyCharacterData.threatLevel}");
}
// TODO: Actually set up battle scene transition
Debug.Log("🎬 Transitioning to battle scene...");
}
///
/// Check if the system is currently waiting for player input
///
public bool IsWaitingForCombatDecision => waitingForCombatDecision;
///
/// Cancel pending combat (for cleanup)
///
public void CancelPendingCombat()
{
if (waitingForCombatDecision)
{
waitingForCombatDecision = false;
pendingBattleData = null;
pendingContext = null;
if (combatEventPopup != null)
combatEventPopup.ForceClose();
}
}
}