using UnityEngine;

public class ShooterSpawner_1 : MonoBehaviour
{
    public GameObject shooterPrefab;  // Reference to the shooter prefab
    public Vector3 spawnPoint = new Vector3(0f, 0f, 0f);  // Reference to the spawn point (Vector3)
    public float spawnDelay = 3f;     // Time delay between spawns (in seconds)
    public string shooterTag = "Shooter1"; // Tag to assign to the spawned shooter

    private bool isShooterActive = false; // Flag to track if shooter is active
    private float spawnTimer = 0f;    // Timer to count down until spawn

    private void Start()
    {
        SpawnShooter();
    }

    private void Update()
    {
        // If a shooter is not active, start the spawn countdown after it's destroyed
        if (!isShooterActive)
        {
            spawnTimer += Time.deltaTime;  // Start counting time after the shooter is destroyed

            if (spawnTimer >= spawnDelay)  // Check if it's time to spawn a new shooter
            {
                SpawnShooter();  // Spawn the new shooter
                spawnTimer = 0f;  // Reset the timer
            }
        }
    }

    public void ShooterDestroyed()
    {
        // This function is called when the shooter is destroyed
        isShooterActive = false;  // Mark the shooter as inactive
    }

    private void SpawnShooter()
    {
        // Instantiate the shooter prefab at the spawn position with no rotation
        if (shooterPrefab != null)
        {
            GameObject shooter = Instantiate(shooterPrefab, spawnPoint, Quaternion.identity);
            shooter.tag = shooterTag;  // Assign the correct tag ("Shooter1")
            isShooterActive = true;  // Shooter is now active

            // Attach the destruction logic to the shooter
            ShooterExpload shooterExpload = shooter.GetComponent<ShooterExpload>();
            if (shooterExpload != null)
            {
                shooterExpload.onShooterDestroyed += ShooterDestroyed;  // Subscribe to the event
            }
            else
            {
                Debug.LogError("Shooter prefab doesn't have ShooterExpload attached!");
            }
        }
        else
        {
            Debug.LogError("Shooter Prefab is not assigned in the Inspector!");
        }
    }
}
