using System.Collections.Generic;
using UnityEngine;

public class StatusEffectReceiver : MonoBehaviour
{
    private List<DebuffInstance> _activeDebuffs = new List<DebuffInstance>();

    public void ApplyDebuff(DebuffData data)
    {
        if (data == null) return;

        if (!data.Stackable)
        {
            DebuffInstance existing = _activeDebuffs.Find(d => d.Data == data);
            if (existing != null)
            {
                existing.RefreshDuration();
                return;
            }
        }
        else
        {
            int count = 0;
            foreach (var d in _activeDebuffs)
                if (d.Data == data) count++;

            if (count >= data.MaxStacks) return;
        }

        DebuffInstance instance = new DebuffInstance(data, this);
        _activeDebuffs.Add(instance);
        instance.OnApply();
    }

    private void Update()
    {
        for (int i = _activeDebuffs.Count - 1; i >= 0; i--)
        {
            _activeDebuffs[i].Tick(Time.deltaTime);
            if (_activeDebuffs[i].IsExpired)
            {
                _activeDebuffs[i].OnRemove();
                _activeDebuffs.RemoveAt(i);
            }
        }
    }

    public bool HasDebuff(DebuffType type)
    {
        foreach (var d in _activeDebuffs)
            if (d.Data.DebuffType == type) return true;
        return false;
    }

    public float GetDebuffValue(DebuffType type)
    {
        float total = 0f;
        foreach (var d in _activeDebuffs)
            if (d.Data.DebuffType == type) total += d.Data.Value;
        return total;
    }

    public void ClearAllDebuffs()
    {
        for (int i = _activeDebuffs.Count - 1; i >= 0; i--)
            _activeDebuffs[i].OnRemove();
        _activeDebuffs.Clear();
    }
}
