using UnityEngine;

public class DebuffInstance
{
    public DebuffData Data { get; private set; }
    public float RemainingTime { get; private set; }
    public bool IsExpired => RemainingTime <= 0f;

    private StatusEffectReceiver _receiver;
    private float _tickAccumulator;
    private GameObject _visualInstance;

    public DebuffInstance(DebuffData data, StatusEffectReceiver receiver)
    {
        Data = data;
        _receiver = receiver;
        RemainingTime = data.Duration;
        _tickAccumulator = 0f;
    }

    public void OnApply()
    {
        if (Data.EffectPrefab != null)
        {
            _visualInstance = Object.Instantiate(Data.EffectPrefab, _receiver.transform);
        }
    }

    public void Tick(float deltaTime)
    {
        RemainingTime -= deltaTime;

        if (Data.DebuffType == DebuffType.DamageOverTime && Data.TickInterval > 0)
        {
            _tickAccumulator += deltaTime;
            if (_tickAccumulator >= Data.TickInterval)
            {
                _tickAccumulator -= Data.TickInterval;
                IDamageable damageable = _receiver.GetComponent<IDamageable>();
                damageable?.TakeDamage(Mathf.RoundToInt(Data.Value), null);
            }
        }
    }

    public void OnRemove()
    {
        if (_visualInstance != null)
            Object.Destroy(_visualInstance);
    }

    public void RefreshDuration()
    {
        RemainingTime = Data.Duration;
    }
}
