using UnityEngine;
using System.Collections.Generic;

public class Spawner : MonoBehaviour
{
    [Header("Spawner Settings")]
    public bool active;
    public int life = 100;               
    public int maxEnemies = 4;           
    public float detection = 10f;        
    public float spawnCooldown = 5f;     

    [Header("References")]
    public GameObject enemyPrefab;       

    private List<GameObject> enemies = new List<GameObject>();
    private Transform player;
    private float cooldownTimer;

    void Start()
    {
        player = GameObject.Find("Player").transform;
    }

    void Update()
    {
        enemies.RemoveAll(e => e == null);

        float distance = Vector3.Distance(transform.position, player.position);
        if (distance >= detection) return;

        if (!active)
        {
            SpawnInitialWave();
            active = true;
            return;
        }

        if (enemies.Count < maxEnemies)
        {
            cooldownTimer -= Time.deltaTime;
            if (cooldownTimer <= 0f)
            {
                SpawnEnemy();
                cooldownTimer = spawnCooldown;
            }
        }
    }

    private void SpawnInitialWave()
    {
        for (int i = 0; i < maxEnemies; i++)
        {
            SpawnEnemy();
        }
    }

    private void SpawnEnemy()
    {
        Vector2 randomCircle = Random.insideUnitCircle * detection;
        Vector3 spawnPos = new Vector3(
            transform.position.x + randomCircle.x,
            transform.position.y,
            transform.position.z + randomCircle.y
        );

        GameObject newEnemy = Instantiate(enemyPrefab, spawnPos, Quaternion.identity);
        enemies.Add(newEnemy);
    }

    public void ReceiveDamage(int received)
    {
        life -= received;
        if (life <= 0)
        {
            Destroy(gameObject);
        }
    }
}
