using UnityEngine;
using UnityEngine.UIElements;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.SceneManagement;
///
/// Controls the TeamOverview UI panel on the right side of the map scene.
/// Displays current team information, stats, and provides navigation controls.
/// Works with the main map UI document.
///
public class TeamOverviewController : MonoBehaviour
{
[Header("Settings")]
[SerializeField] public bool showDebugLogs = false;
// UI Elements
private VisualElement teamOverviewPanel;
private ScrollView teamMembersList;
private Button manageTeamButton;
private Button saveGameButton;
private Label memberCountLabel;
private Label totalGoldLabel;
private Label averageLevelLabel;
private Toggle perceptionVisualizationToggle;
// UI Document reference (shared with map)
private UIDocument uiDocument;
// Team data
private List currentTeam;
void Awake()
{
// Get the UIDocument component from this GameObject
uiDocument = GetComponent();
if (uiDocument == null)
{
Debug.LogError("â TeamOverviewController: No UIDocument component found on this GameObject!");
}
}
void Start()
{
// Ensure GameStateManager has loaded data if it exists
if (GameStateManager.Instance != null && PlayerPrefs.HasKey("GameSaved"))
{
GameStateManager.Instance.LoadGame();
}
SetupUI();
LoadTeamData();
ShowTeamOverview();
}
///
/// Sets up the UI elements and event handlers
///
private void SetupUI()
{
if (uiDocument?.rootVisualElement == null)
{
Debug.LogError("â TeamOverviewController: UIDocument not found or has no root element!");
return;
}
var root = uiDocument.rootVisualElement;
// Find UI elements - using the correct button names from TeamOverview.uxml
teamOverviewPanel = root.Q("TeamOverviewPanel");
teamMembersList = root.Q("TeamMembersList");
manageTeamButton = root.Q("ReturnToTeamSelectButton");
saveGameButton = root.Q("SaveGameButton");
memberCountLabel = root.Q("MemberCountLabel");
totalGoldLabel = root.Q("TotalGoldLabel");
averageLevelLabel = root.Q("AverageLevelLabel");
perceptionVisualizationToggle = root.Q("PerceptionVisualizationToggle");
// Debug: Check which elements were found
if (showDebugLogs)
{
Debug.Log($"đ UI Elements found:");
Debug.Log($" TeamOverviewPanel: {teamOverviewPanel != null}");
Debug.Log($" TeamMembersList: {teamMembersList != null}");
Debug.Log($" ManageTeamButton: {manageTeamButton != null}");
Debug.Log($" SaveGameButton: {saveGameButton != null}");
Debug.Log($" MemberCountLabel: {memberCountLabel != null}");
Debug.Log($" TotalGoldLabel: {totalGoldLabel != null}");
Debug.Log($" AverageLevelLabel: {averageLevelLabel != null}");
Debug.Log($" PerceptionVisualizationToggle: {perceptionVisualizationToggle != null}");
}
// Setup event handlers
if (manageTeamButton != null)
{
manageTeamButton.clicked += OnManageTeamClicked;
}
if (saveGameButton != null)
{
saveGameButton.clicked += OnSaveGameClicked;
}
if (perceptionVisualizationToggle != null)
{
// Load saved toggle state
bool savedState = PlayerPrefs.GetInt("ShowPerceptionVisualization", 1) == 1;
perceptionVisualizationToggle.value = savedState;
// Set up event handler
perceptionVisualizationToggle.RegisterValueChangedCallback(OnPerceptionVisualizationToggled);
// Apply initial state to visualizer
UpdatePerceptionVisualizationState(savedState);
}
if (showDebugLogs)
{
Debug.Log("â
TeamOverviewController: UI setup complete");
}
}
///
/// Loads current team data from the save system
///
private void LoadTeamData()
{
currentTeam = new List();
// Method 1: Try to load from MainTeamSelectScript (if in TeamSelect scene)
var teamSelectScript = FindFirstObjectByType();
if (teamSelectScript != null)
{
currentTeam = teamSelectScript.GetConfiguredCharacters();
if (showDebugLogs)
{
Debug.Log($"đ Loaded team from MainTeamSelectScript: {currentTeam.Count} members");
}
return;
}
// Method 2: Try to load from GameStateManager
if (GameStateManager.Instance != null && GameStateManager.Instance.savedTeam != null)
{
foreach (var character in GameStateManager.Instance.savedTeam)
{
if (character != null)
{
currentTeam.Add(character);
}
}
if (currentTeam.Count > 0)
{
if (showDebugLogs)
{
Debug.Log($"đ Loaded team from GameStateManager: {currentTeam.Count} members");
}
return;
}
}
// Method 3: Try to load directly from PlayerPrefs (fallback)
for (int i = 0; i < 4; i++)
{
string prefix = $"Character{i}_";
if (PlayerPrefs.HasKey(prefix + "Exists") && PlayerPrefs.GetInt(prefix + "Exists") == 1)
{
var character = new TeamCharacter();
character.name = PlayerPrefs.GetString(prefix + "Name", "");
character.isMale = PlayerPrefs.GetInt(prefix + "IsMale", 1) == 1;
character.strength = PlayerPrefs.GetInt(prefix + "Strength", 10);
character.dexterity = PlayerPrefs.GetInt(prefix + "Dexterity", 10);
character.constitution = PlayerPrefs.GetInt(prefix + "Constitution", 10);
character.wisdom = PlayerPrefs.GetInt(prefix + "Wisdom", 10);
character.perception = PlayerPrefs.GetInt(prefix + "Perception", 10);
character.gold = PlayerPrefs.GetInt(prefix + "Gold", 25);
character.silver = PlayerPrefs.GetInt(prefix + "Silver", 0);
character.copper = PlayerPrefs.GetInt(prefix + "Copper", 0);
if (!string.IsNullOrEmpty(character.name))
{
currentTeam.Add(character);
}
}
}
if (currentTeam.Count > 0)
{
if (showDebugLogs)
{
Debug.Log($"đ Loaded team from PlayerPrefs: {currentTeam.Count} members");
}
}
else
{
if (showDebugLogs)
{
Debug.Log("âšī¸ No team data found - this is normal for a new game");
}
}
} ///
/// Shows the team overview panel
///
public void ShowTeamOverview()
{
if (teamOverviewPanel == null) return;
teamOverviewPanel.style.display = DisplayStyle.Flex;
UpdateTeamDisplay();
if (showDebugLogs)
{
Debug.Log("đĨ TeamOverviewController: Team overview panel shown");
}
}
///
/// Hides the team overview panel
///
public void HideTeamOverview()
{
if (teamOverviewPanel == null) return;
teamOverviewPanel.style.display = DisplayStyle.None;
if (showDebugLogs)
{
Debug.Log("đģ TeamOverviewController: Team overview panel hidden");
}
}
///
/// Updates the team display with current data
///
private void UpdateTeamDisplay()
{
if (currentTeam == null)
{
if (showDebugLogs)
{
Debug.Log("â ī¸ UpdateTeamDisplay: currentTeam is null");
}
return;
}
if (teamMembersList == null)
{
if (showDebugLogs)
{
Debug.Log("â ī¸ UpdateTeamDisplay: teamMembersList is null - UI elements not found");
}
return;
}
if (showDebugLogs)
{
Debug.Log($"đ¨ UpdateTeamDisplay: Updating display for {currentTeam.Count} team members");
}
// Clear existing team member displays
teamMembersList.Clear();
// Add each team member
foreach (var member in currentTeam)
{
if (member != null)
{
CreateTeamMemberCard(member);
if (showDebugLogs)
{
Debug.Log($"đ Added card for member: {member.name}");
}
}
}
// Update team stats
UpdateTeamStats();
if (showDebugLogs)
{
Debug.Log($"â
UpdateTeamDisplay: Display updated with {currentTeam.Count} members");
}
}
///
/// Creates a visual card for a team member
///
private void CreateTeamMemberCard(TeamCharacter member)
{
var memberCard = new VisualElement();
memberCard.style.backgroundColor = new StyleColor(new Color(0.3f, 0.3f, 0.3f, 0.8f));
memberCard.style.borderTopColor = new StyleColor(new Color(0.5f, 0.5f, 0.5f));
memberCard.style.borderBottomColor = new StyleColor(new Color(0.5f, 0.5f, 0.5f));
memberCard.style.borderLeftColor = new StyleColor(new Color(0.5f, 0.5f, 0.5f));
memberCard.style.borderRightColor = new StyleColor(new Color(0.5f, 0.5f, 0.5f));
memberCard.style.borderTopWidth = 1;
memberCard.style.borderBottomWidth = 1;
memberCard.style.borderLeftWidth = 1;
memberCard.style.borderRightWidth = 1;
memberCard.style.borderTopLeftRadius = 4;
memberCard.style.borderTopRightRadius = 4;
memberCard.style.borderBottomLeftRadius = 4;
memberCard.style.borderBottomRightRadius = 4;
memberCard.style.marginBottom = 8;
memberCard.style.paddingTop = 8;
memberCard.style.paddingBottom = 8;
memberCard.style.paddingLeft = 8;
memberCard.style.paddingRight = 8;
// Member header with name and level
var memberHeader = new VisualElement();
memberHeader.style.flexDirection = FlexDirection.Row;
memberHeader.style.justifyContent = Justify.SpaceBetween;
memberHeader.style.alignItems = Align.Center;
memberHeader.style.marginBottom = 5;
var nameLabel = new Label(member.name);
nameLabel.style.color = new StyleColor(new Color(1f, 1f, 1f));
nameLabel.style.fontSize = 12;
nameLabel.style.unityFontStyleAndWeight = FontStyle.Bold;
var hpLabel = new Label($"HP: {member.HitPoints} | AC: {member.ArmorClass}");
hpLabel.style.color = new StyleColor(new Color(0.8f, 0.8f, 1f));
hpLabel.style.fontSize = 10;
memberHeader.Add(nameLabel);
memberHeader.Add(hpLabel);
memberCard.Add(memberHeader);
// Stats container
var statsContainer = new VisualElement();
statsContainer.style.flexDirection = FlexDirection.Row;
statsContainer.style.flexWrap = Wrap.Wrap;
statsContainer.style.justifyContent = Justify.SpaceBetween;
// Add attribute stats in a compact layout
AddCompactStatLabel(statsContainer, "STR", member.strength);
AddCompactStatLabel(statsContainer, "DEX", member.dexterity);
AddCompactStatLabel(statsContainer, "CON", member.constitution);
AddCompactStatLabel(statsContainer, "WIS", member.wisdom);
AddCompactStatLabel(statsContainer, "PER", member.perception);
memberCard.Add(statsContainer);
teamMembersList.Add(memberCard);
}
///
/// Adds a compact stat label to a container
///
private void AddCompactStatLabel(VisualElement container, string statName, int statValue)
{
var statElement = new VisualElement();
statElement.style.flexDirection = FlexDirection.Row;
statElement.style.width = new StyleLength(new Length(18, LengthUnit.Percent));
statElement.style.marginBottom = 1;
var statLabel = new Label($"{statName}:");
statLabel.style.color = new StyleColor(new Color(0.8f, 0.8f, 0.8f));
statLabel.style.fontSize = 9;
statLabel.style.width = new StyleLength(new Length(60, LengthUnit.Percent));
var valueLabel = new Label(statValue.ToString());
valueLabel.style.color = new StyleColor(new Color(1f, 1f, 1f));
valueLabel.style.fontSize = 9;
valueLabel.style.width = new StyleLength(new Length(40, LengthUnit.Percent));
statElement.Add(statLabel);
statElement.Add(valueLabel);
container.Add(statElement);
}
///
/// Updates the team summary statistics
///
private void UpdateTeamStats()
{
if (currentTeam == null) return;
// Update member count
if (memberCountLabel != null)
{
memberCountLabel.text = currentTeam.Count.ToString();
}
// Update total gold (assuming team shares resources)
if (totalGoldLabel != null)
{
var totalGold = currentTeam.Sum(member => member.gold);
totalGoldLabel.text = totalGold.ToString();
}
// Since TeamCharacter doesn't have level property, assume level 1 for all characters
if (averageLevelLabel != null)
{
averageLevelLabel.text = "1";
}
}
///
/// Handle manage team button click
///
private void OnManageTeamClicked()
{
if (showDebugLogs)
{
Debug.Log("đ TeamOverviewController: Returning to Team Select scene");
}
// Load the Team Select scene
var sceneManager = FindFirstObjectByType();
if (sceneManager != null)
{
sceneManager.GoToTeamSelect();
}
else
{
// Fallback to direct scene loading
UnityEngine.SceneManagement.SceneManager.LoadScene("TeamSelect");
}
}
///
/// Handle save game button click
///
private void OnSaveGameClicked()
{
if (showDebugLogs)
{
Debug.Log("đž TeamOverviewController: Saving game");
}
try
{
// Use GameStateManager to save current game state
var gameStateManager = FindFirstObjectByType();
if (gameStateManager != null)
{
gameStateManager.SaveGame();
Debug.Log("â
Game saved successfully!");
}
else
{
Debug.LogWarning("â ī¸ GameStateManager not found!");
}
}
catch (System.Exception e)
{
Debug.LogError($"â Failed to save game: {e.Message}");
}
}
///
/// Handle perception visualization toggle change
///
private void OnPerceptionVisualizationToggled(ChangeEvent evt)
{
bool newValue = evt.newValue;
if (showDebugLogs)
{
Debug.Log($"đī¸ TeamOverviewController: Perception visualization toggled to {newValue}");
}
// Save the setting
PlayerPrefs.SetInt("ShowPerceptionVisualization", newValue ? 1 : 0);
PlayerPrefs.Save();
// Update the visualizer
UpdatePerceptionVisualizationState(newValue);
}
///
/// Updates the perception visualization state
///
private void UpdatePerceptionVisualizationState(bool enabled)
{
var visualizer = TeamPerceptionVisualizer.Instance;
if (visualizer != null)
{
visualizer.SetPerceptionVisualizationEnabled(enabled);
}
else if (showDebugLogs)
{
Debug.LogWarning("â ī¸ TeamPerceptionVisualizer instance not found");
}
}
///
/// Refreshes the team data and display
///
public void RefreshTeamData()
{
LoadTeamData();
UpdateTeamDisplay();
if (showDebugLogs)
{
Debug.Log("đ TeamOverviewController: Team data refreshed");
}
}
///
/// Forces a reload of team data from all sources
///
public void ForceReloadTeamData()
{
// Force GameStateManager to reload if possible
if (GameStateManager.Instance != null && PlayerPrefs.HasKey("GameSaved"))
{
GameStateManager.Instance.LoadGame();
}
LoadTeamData();
UpdateTeamDisplay();
if (showDebugLogs)
{
Debug.Log("đ TeamOverviewController: Team data force reloaded");
}
}
///
/// Context menu methods for debugging
///
[ContextMenu("Show Team Overview")]
public void TestShowTeamOverview()
{
ShowTeamOverview();
}
[ContextMenu("Hide Team Overview")]
public void TestHideTeamOverview()
{
HideTeamOverview();
}
[ContextMenu("Refresh Team Data")]
public void TestRefreshTeamData()
{
RefreshTeamData();
}
[ContextMenu("Force Reload Team Data")]
public void TestForceReloadTeamData()
{
ForceReloadTeamData();
}
[ContextMenu("Debug Team Data Sources")]
public void DebugTeamDataSources()
{
Debug.Log("=== TEAM DATA DEBUG ===");
// Check MainTeamSelectScript
var teamSelectScript = FindFirstObjectByType();
Debug.Log($"MainTeamSelectScript found: {teamSelectScript != null}");
if (teamSelectScript != null)
{
var characters = teamSelectScript.GetConfiguredCharacters();
Debug.Log($"MainTeamSelectScript characters: {characters.Count}");
}
// Check GameStateManager
Debug.Log($"GameStateManager.Instance: {GameStateManager.Instance != null}");
if (GameStateManager.Instance != null)
{
Debug.Log($"GameStateManager.savedTeam: {GameStateManager.Instance.savedTeam != null}");
if (GameStateManager.Instance.savedTeam != null)
{
int count = 0;
foreach (var character in GameStateManager.Instance.savedTeam)
{
if (character != null) count++;
}
Debug.Log($"GameStateManager team count: {count}");
}
}
// Check PlayerPrefs
int playerPrefsCount = 0;
for (int i = 0; i < 4; i++)
{
if (PlayerPrefs.HasKey($"Character{i}_Exists") && PlayerPrefs.GetInt($"Character{i}_Exists") == 1)
{
string name = PlayerPrefs.GetString($"Character{i}_Name", "");
if (!string.IsNullOrEmpty(name))
{
playerPrefsCount++;
Debug.Log($"PlayerPrefs Character {i}: {name}");
}
}
}
Debug.Log($"PlayerPrefs character count: {playerPrefsCount}");
Debug.Log($"Current team loaded: {currentTeam?.Count ?? 0}");
if (currentTeam != null)
{
foreach (var member in currentTeam)
{
Debug.Log($" - {member?.name ?? "null"} (STR:{member?.strength ?? 0}, DEX:{member?.dexterity ?? 0}, CON:{member?.constitution ?? 0}, WIS:{member?.wisdom ?? 0}, PER:{member?.perception ?? 0})");
}
}
Debug.Log("=== END DEBUG ===");
}
[ContextMenu("Force Update Display")]
public void ForceUpdateDisplay()
{
if (currentTeam != null && currentTeam.Count > 0)
{
Debug.Log($"đ Force updating display with {currentTeam.Count} team members");
UpdateTeamDisplay();
}
else
{
Debug.Log("â ī¸ No team data to display");
}
}
}