
using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class BonusManager : MonoBehaviour
{
    public static BonusManager Instance { get; private set; }

    [Header("UI Элементы")]
    public Image bonusIcon;
    public TextMeshProUGUI bonusTimerText;

    private BonusEffect _activeBonus;
    private float _timer;
    private GameObject _player;
    private int _lastDisplayedTime = -1;
    void Awake()
    {
        if (Instance == null) Instance = this;
        else Destroy(gameObject);
    }

    void Start()
    {
        _player = GameObject.FindGameObjectWithTag("Player");
        bonusIcon.gameObject.SetActive(false);
        bonusTimerText.gameObject.SetActive(false);
    }

    void Update()
    {
        if (_activeBonus != null)
        {
            _timer -= Time.deltaTime;
            if (_timer <= 0)
            {
                DeactivateBonus();
            }
            else
            {
                int secondsLeft = Mathf.CeilToInt(_timer);
                if (secondsLeft != _lastDisplayedTime)
                {
                    _lastDisplayedTime = secondsLeft;
                    bonusTimerText.text = secondsLeft.ToString();
                }
            }
        }
    }

    public void ActivateBonus(BonusEffect bonus)
    {
        if (_activeBonus != null)
        {
            DeactivateBonus();
        }

        _activeBonus = bonus;
        _timer = _activeBonus.duration;
        _lastDisplayedTime = -1;

        _activeBonus.Activate(_player);
        
        bonusIcon.gameObject.SetActive(true);
        bonusTimerText.gameObject.SetActive(true);
    }

    private void DeactivateBonus()
    {
        if (_activeBonus != null && _player != null)
        {
            _activeBonus.Deactivate(_player);
        }
        _activeBonus = null;
        _timer = 0;
        
        bonusIcon.gameObject.SetActive(false);
        bonusTimerText.gameObject.SetActive(false);
    }
}
