using UnityEngine;
using UnityEngine.UIElements;

/// <summary>
/// Controls the game UI, updating score and timer displays.
/// </summary>
[RequireComponent(typeof(UIDocument))]
public class UIController : MonoBehaviour
{
    private UIDocument uiDocument;

    // UI Elements
    private Label homeTeamLabel;
    private Label homeScoreLabel;
    private Label awayTeamLabel;
    private Label awayScoreLabel;
    private Label timerLabel;
    private Label periodLabel;

    [Header("Team Names")]
    [SerializeField] private string homeTeamName = "Home Team";
    [SerializeField] private string awayTeamName = "Away Team";

    void Awake()
    {
        uiDocument = GetComponent<UIDocument>();
    }

    void OnEnable()
    {
        // Get root visual element
        var root = uiDocument.rootVisualElement;

        // Query UI elements
        homeTeamLabel = root.Q<Label>("HomeTeamLabel");
        homeScoreLabel = root.Q<Label>("HomeScoreLabel");
        awayTeamLabel = root.Q<Label>("AwayTeamLabel");
        awayScoreLabel = root.Q<Label>("AwayScoreLabel");
        timerLabel = root.Q<Label>("TimerLabel");
        periodLabel = root.Q<Label>("PeriodLabel");

        // Set team names
        if (homeTeamLabel != null)
            homeTeamLabel.text = homeTeamName;

        if (awayTeamLabel != null)
            awayTeamLabel.text = awayTeamName;

        // Subscribe to GameManager events
        if (GameManager.Instance != null)
        {
            GameManager.Instance.OnScoreChanged += UpdateScore;
            GameManager.Instance.OnTimeChanged += UpdateTimer;
            GameManager.Instance.OnPeriodChanged += UpdatePeriod;

            // Initialize display
            UpdateScore(GameManager.Instance.HomeScore, GameManager.Instance.AwayScore);
            UpdateTimer(GameManager.Instance.TimeRemaining);
            UpdatePeriod(GameManager.Instance.CurrentPeriod);
        }
    }

    void OnDisable()
    {
        // Unsubscribe from events
        if (GameManager.Instance != null)
        {
            GameManager.Instance.OnScoreChanged -= UpdateScore;
            GameManager.Instance.OnTimeChanged -= UpdateTimer;
            GameManager.Instance.OnPeriodChanged -= UpdatePeriod;
        }
    }

    private void UpdateScore(int homeScore, int awayScore)
    {
        if (homeScoreLabel != null)
            homeScoreLabel.text = homeScore.ToString();

        if (awayScoreLabel != null)
            awayScoreLabel.text = awayScore.ToString();
    }

    private void UpdateTimer(float timeRemaining)
    {
        if (timerLabel != null)
        {
            int minutes = Mathf.FloorToInt(timeRemaining / 60f);
            int seconds = Mathf.FloorToInt(timeRemaining % 60f);
            timerLabel.text = $"{minutes:00}:{seconds:00}";
        }
    }

    private void UpdatePeriod(int period)
    {
        if (periodLabel != null)
        {
            periodLabel.text = $"Period {period}";
        }
    }
}
