using System.Collections;
using UnityEngine;

public class GameSession : MonoBehaviour
{
    [TextArea]
    public string hintText = "WASD move  SHIFT sprint  SPACE jump  LMB fire  R reload  1/2/3 or wheel switch";

    [TextArea]
    public string objectiveIntroText = "Clear the turrets, use cover, then push the boss platform.";

    public float introMessageDuration = 4.5f;

    private HUDController _hud;
    private PlayerHealth _playerHealth;
    private Coroutine _centerMessageRoutine;

    private void Awake()
    {
        _hud = FindObjectOfType<HUDController>(true);
        _playerHealth = FindObjectOfType<PlayerHealth>(true);
    }

    private void OnEnable()
    {
        EnemyTarget.ObjectiveCountChanged += HandleObjectiveCountChanged;
    }

    private void OnDisable()
    {
        EnemyTarget.ObjectiveCountChanged -= HandleObjectiveCountChanged;
    }

    private void Start()
    {
        EnemyTarget.RecalculateObjectivesInScene();

        if (_hud == null)
        {
            return;
        }

        _hud.HideOverlay();
        _hud.SetHint(hintText);
        _hud.SetCenterMessage(objectiveIntroText);
        _hud.SetObjectiveCount(EnemyTarget.RemainingObjectives);

        if (!string.IsNullOrWhiteSpace(objectiveIntroText) && introMessageDuration > 0f)
        {
            _centerMessageRoutine = StartCoroutine(ClearCenterMessageAfterDelay());
        }

        if (_playerHealth != null)
        {
            _hud.SetHealth(_playerHealth.CurrentHealth, _playerHealth.maxHealth);
        }
    }

    private void HandleObjectiveCountChanged(int remaining)
    {
        if (_hud == null)
        {
            return;
        }

        _hud.SetObjectiveCount(remaining);
        if (remaining <= 0)
        {
            _hud.ShowVictoryScreen();
            _hud.SetCenterMessage("Mission Complete");
        }
    }

    private IEnumerator ClearCenterMessageAfterDelay()
    {
        yield return new WaitForSeconds(introMessageDuration);

        if (_hud != null && EnemyTarget.RemainingObjectives > 0)
        {
            _hud.SetCenterMessage(string.Empty);
        }

        _centerMessageRoutine = null;
    }
}
