using UnityEngine;

public class ExplosiveProjectile : MonoBehaviour
{
    public float speed = 10f;
    public float explosionRadius = 3f;
    public float damage = 50f;
    public GameObject explosionEffectPrefab;

    // 유니티 인스펙터에서 "Enemy" 레이어를 선택할 수 있게 합니다.
    public LayerMask enemyLayer;

    private Vector3 _targetPosition;

    public void SetTargetPosition(Vector3 position)
    {
        _targetPosition = position;
    }

    void Update()
    {
        transform.position = Vector3.MoveTowards(transform.position, _targetPosition, speed * Time.deltaTime);

        if (Vector3.Distance(transform.position, _targetPosition) < 0.1f)
        {
            Explode();
        }
    }

    void Explode()
    {
        if (explosionEffectPrefab != null)
        {
            Instantiate(explosionEffectPrefab, transform.position, transform.rotation);
        }

        // 핵심 수정: enemyLayer에 해당하는 오브젝트만 감지합니다.
        Collider[] colliders = Physics.OverlapSphere(transform.position, explosionRadius, enemyLayer);

        foreach (Collider hitCollider in colliders)
        {
            IDamageable damageable = hitCollider.GetComponentInParent<IDamageable>();
            if (damageable != null)
            {
                damageable.TakeDamage(damage);
                Debug.Log($"[폭발 적중] {hitCollider.name}에게 {damage} 데미지!");
            }
        }

        Destroy(gameObject);
    }

    void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, explosionRadius);
    }
}