using UnityEngine;
using System.Collections.Generic;

public class AreaTowerAttack : MonoBehaviour
{
    [Header("Tower Settings")]
    public float range = 15f;          // 넓은 사거리
    public float fireRate = 0.5f;      // 발사 속도가 느림 (큰 데미지)
    public GameObject explosiveProjectilePrefab; // 새로운 폭발 투사체 프리팹
    public Transform firePoint;        // 투사체가 발사될 위치

    private float _fireCountdown = 0f;
    private Transform _target;

    void Update()
    {
        UpdateTarget(); // 가장 가까운 적 찾기

        if (_target == null) return;

        // 발사 간격 관리
        if (_fireCountdown <= 0f)
        {
            AreaShoot();
            _fireCountdown = 1f / fireRate;
        }

        _fireCountdown -= Time.deltaTime;
    }

    void UpdateTarget()
    {
        GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
        float shortestDistance = Mathf.Infinity;
        GameObject nearestEnemy = null;

        foreach (GameObject enemy in enemies)
        {
            float distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position);
            if (distanceToEnemy < shortestDistance)
            {
                shortestDistance = distanceToEnemy;
                nearestEnemy = enemy;
            }
        }

        if (nearestEnemy != null && shortestDistance <= range)
        {
            _target = nearestEnemy.transform;
        }
        else
        {
            _target = null;
        }
    }

    void AreaShoot()
    {
        // 타겟의 현재 위치를 폭발 투사체의 목표 지점으로 설정
        GameObject projectileGo = Instantiate(explosiveProjectilePrefab, firePoint.position, firePoint.rotation);
        ExplosiveProjectile explosiveProjectile = projectileGo.GetComponent<ExplosiveProjectile>();

        if (explosiveProjectile != null)
        {
            // 투사체에게 '목표 지점'을 전달 (추적 아님!)
            explosiveProjectile.SetTargetPosition(_target.position);
        }
    }

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