using System.Collections.Generic;
using UnityEngine;

namespace Shooter.Gameplay
{
    /// <summary>
    /// Непрерывный спавнер: по очереди создаёт врагов у точек с тегом «SpawnPoint»,
    /// пропуская те, что слишком близко к игроку, с короткой паузой между появлениями.
    /// Singleton — доступен через <see cref="Current"/>.
    /// </summary>
    public class SpawnControl : MonoBehaviour
    {
        public static SpawnControl Current;

        public GameObject[] m_EnemyPrefabs;
        [Tooltip("Предельное число одновременно живых врагов")]
        public int m_MaxEnemies = 100;
        [Tooltip("Ближе этой дистанции к игроку точка пропускается")]
        public float m_SpawnDistance = 30f;
        [Tooltip("Пауза между появлениями, сек")]
        public float m_SpawnDelay = .05f;

        [HideInInspector] public GameObject[] m_SpawnPoints;
        [HideInInspector] public List<GameObject> m_Enemies;
        [HideInInspector] public int SpawnCounter = 0;
        [HideInInspector] public int TotalSpawnCount = 0;
        [HideInInspector] public int CurrentEnemyCount = 0;
        [HideInInspector] public bool KeepSpawnning = true;
        [HideInInspector] public int TotalKillCount = 0;

        private bool m_DelayingSpawn = true;
        private int m_SpawnPointNumber = 0;

        void Awake()
        {
            Current = this;
            m_Enemies = new List<GameObject>();
            m_SpawnPoints = GameObject.FindGameObjectsWithTag("SpawnPoint");
        }

        void Start()
        {
            m_DelayingSpawn = false;
            SpawnCounter = 0;
            CurrentEnemyCount = 0;
            KeepSpawnning = true;
            TotalSpawnCount = 20;
        }

        void Update()
        {
            if (!KeepSpawnning || CurrentEnemyCount >= m_MaxEnemies || m_DelayingSpawn)
                return;

            Transform currentSpawnPoint = m_SpawnPoints[m_SpawnPointNumber].transform;
            if (Vector3.Distance(currentSpawnPoint.position, PlayerChar.m_Current.transform.position) <= m_SpawnDistance)
            {
                // Точка слишком близко к игроку — пропускаем её в этом кадре.
                m_SpawnPointNumber++;
            }
            else
            {
                GameObject obj = Instantiate(m_EnemyPrefabs[0]);
                Vector3 pos = m_SpawnPoints[m_SpawnPointNumber].transform.position;
                pos.y = 1;
                obj.transform.position = pos;
                AddEnemy();

                m_DelayingSpawn = true;
                if (SpawnCounter >= TotalSpawnCount)
                    KeepSpawnning = false;
                else
                    Invoke(nameof(EnableCanSpawnEnemy), m_SpawnDelay);

                m_SpawnPointNumber++;
            }

            // По кругу проходим список точек.
            if (m_SpawnPointNumber > m_SpawnPoints.Length - 1)
                m_SpawnPointNumber = 0;
        }

        private void EnableCanSpawnEnemy()
        {
            m_DelayingSpawn = false;
        }

        public void AddEnemy()
        {
            CurrentEnemyCount++;
        }

        public void RemoveEnemy()
        {
            CurrentEnemyCount--;
            TotalKillCount++;
        }
    }
}
