using UnityEngine;

public class Grenade : MonoBehaviour
{
    public float fuseTime = 3f;
    public float explosionRadius = 5f;
    public float explosionForce = 700f;

    public GameObject explosionEffect;

    private float countdown;
    private bool hasExploded = false;

    void Start()
    {
        countdown = fuseTime;
    }

    void Update()
    {
        countdown -= Time.deltaTime;
        if (countdown <= 0f && !hasExploded)
        {
            Explode();
            hasExploded = true;
        }
    }

    void OnCollisionEnter(Collision collision)
    {
        var target = collision.gameObject.GetComponent<GrenadeTarget>();
        if (target != null)
        {
            if (!hasExploded)
            {
                Explode();
                hasExploded = true;
            }
        }
    }

    void Explode()
    {
        if (explosionEffect)
        {
            Instantiate(explosionEffect, transform.position, transform.rotation);
        }

        var collidersToDamage = Physics.OverlapSphere(transform.position, explosionRadius);

        foreach (var nearbyObject in collidersToDamage)
        {
            var target = nearbyObject.GetComponent<GrenadeTarget>();
            if (target)
            {
                target.DestroyTarget();
            }
        }
        
        var collidersToMove = Physics.OverlapSphere(transform.position, explosionRadius);

        foreach (var nearbyObject in collidersToMove)
        {
            var rb = nearbyObject.GetComponent<Rigidbody>();
            if (rb)
            {
                rb.AddExplosionForce(explosionForce, transform.position, explosionRadius);
            }
        }


        Destroy(gameObject);
    }
}
