using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class BallSpawner : MonoBehaviour
{
    public GameObject basicBallPrefab;

    public GameObject nuclearBallPrefab;

    public GameObject glassBallPrefab;

    public GameObject eyeBallPrefab;

    public GameObject oozeBallPrefab;

    public GameObject fruitBallPrefab;

    public GameObject gameBoard;

    private static WaitForSeconds _waitForSeconds0_5 = new WaitForSeconds(0.5f);

    private Queue<System.Action> ballQueue = new Queue<System.Action>();

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        int currentLevel = PlayerPrefs.GetInt("CurrentLevel");

        ballQueue.Enqueue(() => SpawnBasicBall());
        ballQueue.Enqueue(() => SpawnBasicBall());
        ballQueue.Enqueue(() => SpawnBasicBall());
        ballQueue.Enqueue(() => SpawnBasicBall());

        StartCoroutine(SpawnBalls());
    }

    private void SpawnBasicBall()
    {
        if (basicBallPrefab == null || gameBoard == null)
        {
            Debug.LogWarning("BallSpawner: Missing basicBallPrefab or gameBoard reference.");
            return;
        }

        Vector3 spawnPosition = GetRandomPositionInsideGameBoard();
        Instantiate(basicBallPrefab, spawnPosition, Quaternion.identity);
    }

    private Vector3 GetRandomPositionInsideGameBoard()
    {
        Bounds bounds;

        Collider2D collider2D = gameBoard.GetComponent<Collider2D>();
        if (collider2D != null)
        {
            bounds = collider2D.bounds;
        }
        else
        {
            Renderer boardRenderer = gameBoard.GetComponent<Renderer>();
            if (boardRenderer == null)
            {
                Debug.LogWarning("BallSpawner: gameBoard needs a Collider2D or Renderer to read bounds.");
                return gameBoard.transform.position;
            }

            bounds = boardRenderer.bounds;
        }

        float randomX = Random.Range(bounds.min.x, bounds.max.x);
        float randomY = Random.Range(bounds.min.y, bounds.max.y);

        return new Vector3(randomX, randomY, gameBoard.transform.position.z);
    }

    private IEnumerator SpawnBalls()
    {
        while (ballQueue.Count > 0)
        {
            System.Action spawnAction = ballQueue.Dequeue();
            spawnAction.Invoke();
            yield return _waitForSeconds0_5;
        }
    }
}
