using UnityEngine;

public class DestructibleBlock : Entity
{
    [SerializeField] private GameObject[] debrisPrefabs; 
    [SerializeField] private int debrisCount = 5;        
    [SerializeField] private float explosionForce = 5f; 
    [SerializeField] private float debrisLifetime = 2f; 

    protected override void Die()
    {
        SpawnDebris(); 
        base.Die();    
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            Player player = collision.gameObject.GetComponent<Player>();
            if (player != null && player.IsDashing)
            {
                Die();
            }
        }
    }

    private void SpawnDebris()
    {
        if (debrisPrefabs == null || debrisPrefabs.Length == 0)
        {
            return;
        }

        for (int i = 0; i < debrisCount; i++)
        {
            Vector2 spawnPos = (Vector2)transform.position + Random.insideUnitCircle * 0.5f;
            GameObject prefab = debrisPrefabs[Random.Range(0, debrisPrefabs.Length)];
            GameObject debris = Instantiate(prefab, spawnPos, Quaternion.identity);
            Rigidbody2D rb = debris.GetComponent<Rigidbody2D>();
            if (rb != null)
            {
                Vector2 dir = (spawnPos - (Vector2)transform.position).normalized;
                dir += Random.insideUnitCircle * 0.5f;
                rb.AddForce(dir.normalized * explosionForce, ForceMode2D.Impulse);
                rb.AddTorque(Random.Range(-180f, 180f));
            }

            Destroy(debris, debrisLifetime);
        }
    }
}