using UnityEngine;
using System.Collections.Generic;

public class DeepSeaSpawner : MonoBehaviour
{

    [SerializeField] GameObject bubblePrefab;
    [SerializeField] Transform[] bubbleSpawnPoints;
    [SerializeField] float bubbleInterval = 1.5f;

    [SerializeField] GameObject rockPrefab;
    [SerializeField] int initialRockCount = 10;
    [SerializeField] float spawnPadding = 0.5f; 

    private List<GameObject> spawnedObjects = new List<GameObject>();
    private Camera cam;

    void Start()
    {
        cam = Camera.main;
    }

    void OnEnable()
    {
        if (cam == null) cam = Camera.main;

        SpawnInitialRocks();
        InvokeRepeating(nameof(SpawnBubble), 0f, bubbleInterval);
    }

    void OnDisable()
    {
        CancelInvoke();
        CleanupObjects();
    }
    void SpawnInitialRocks()
    {
        Vector2 minScreen = cam.ViewportToWorldPoint(new Vector3(0, 0, 0));
        Vector2 maxScreen = cam.ViewportToWorldPoint(new Vector3(1, 1, 0));

        for (int i = 0; i < initialRockCount; i++)
        {
  
            float randomX = Random.Range(minScreen.x + spawnPadding, maxScreen.x - spawnPadding);
            float randomY = Random.Range(minScreen.y + spawnPadding, maxScreen.y - spawnPadding);
            Vector3 spawnPos = new Vector3(randomX, randomY, 0);
            GameObject rock = Instantiate(rockPrefab, spawnPos, Quaternion.identity);

            rock.transform.SetParent(this.transform);
            spawnedObjects.Add(rock);
        }
    }

    void SpawnBubble()
    {
        if (bubblePrefab == null || bubbleSpawnPoints.Length == 0) return;

        Transform spawnPoint = bubbleSpawnPoints[Random.Range(0, bubbleSpawnPoints.Length)];
        Vector3 spawnPos = spawnPoint.position + new Vector3(Random.Range(-0.2f, 0.2f), 0.5f, 0);

        GameObject bubble = Instantiate(bubblePrefab, spawnPos, Quaternion.identity);
        bubble.transform.SetParent(this.transform);
        spawnedObjects.Add(bubble);
    }

    void CleanupObjects()
    {
        foreach (GameObject obj in spawnedObjects)
        {
            if (obj != null) Destroy(obj);
        }
        spawnedObjects.Clear();
    }
}