using UnityEngine;

public class BubbleSpawner : MonoBehaviour
{
    public static BubbleSpawner Instance { get; private set; } // Singleton instance
    public GameObject bubblePrefab;

    private float spawnInterval = 20f;
    private float spawnTimer;


     public float xMin = -8f; // Minimum value for X-axis range
    public float xMax = 8f;  // Maximum value for X-axis range
    public float yMin = -4f; // Minimum value for Y-axis range
    public float yMax = 4f;  // Maximum value for Y-axis range

    private void Awake()
    {
        // Ensure there's only one instance of BubbleSpawner
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
        }
        else
        {
            Instance = this;
        }
    }

    private void Start()
    {
        // Check assignments
        if (bubblePrefab == null) Debug.LogError("Bubble Prefab is not assigned!");

        spawnTimer = spawnInterval;

        // Spawn bubbles immediately at the start
        SpawnBubbles();
    }

    private void Update()
    {
        if (spawnTimer <= 0)
        {
            SpawnBubbles();
            spawnTimer = spawnInterval; // Reset spawn timer
        }

        spawnTimer -= Time.deltaTime;
    }

    private void SpawnBubbles()
    {
        for (int i = 0; i < 20; i++)  // Spawning 20 bubbles
        {
            Vector3 spawnPosition = new Vector3(
                Random.Range(xMin, xMax),
                Random.Range(yMin, yMax),
                0f
            );

            GameObject bubble = Instantiate(bubblePrefab, spawnPosition, Quaternion.identity);
            if (bubble.TryGetComponent(out BubbleMovement movement))
            {
                movement.SetSpeed(Random.Range(0.5f, 1.5f));
            }
        }
    }

    // Method to clear all bubbles when round ends
    public void ClearBubbles()
    {
        foreach (GameObject bubble in GameObject.FindGameObjectsWithTag("bubble"))
        {
            Destroy(bubble);
        }
    }
}