using System.Collections.Generic;
using UnityEngine;

public class CollectableManager : MonoBehaviour
{
    // List of cube prefabs
    public List<GameObject> CubePrefabs;

    // How many cubes to keep in front and behind the player
    public int CubeCountInFront = 1;
    public int CubeCountBehind = 0;

    // Player reference
    public GameObject player;

    // Pool of cubes (optional, not used yet)
    [SerializeField] private List<GameObject> CubePool = new List<GameObject>();

    // Active cubes in the scene
    [SerializeField] private List<GameObject> Cubes = new List<GameObject>();

    [SerializeField] private int numCubes = 0;

    private float CubeLenZ;
    private float nextCubePosZ;

    void Start()
    {
        if (CubePrefabs.Count == 0)
            Debug.LogError("No Cube Prefabs assigned to CollectableManager!");
        if (player == null)
            Debug.LogError("Player not assigned!");

        // Assume all cubes are the same size; get Z length from first prefab
        CubeLenZ = CubePrefabs[0].GetComponentInChildren<Renderer>().bounds.size.z;

        LayCubesAtBeginning();
    }

    // Spawn initial cubes in front and behind player
    void LayCubesAtBeginning()
    {
        nextCubePosZ = -CubeLenZ / 2 - (CubeCountBehind - 1) * CubeLenZ;

        for (int i = 0; i < CubeCountBehind + CubeCountInFront; i++)
        {
            AddACube();
        }
    }

    // Find the cube index player is on
    int PlayerOnCubeIndex()
    {
        return Mathf.FloorToInt(player.transform.position.z / CubeLenZ);
    }

    // Delete the cube at the back
    void DeleteEnd()
    {
        if (Cubes.Count > 0)
        {
            GameObject cubeToRemove = Cubes[0];
            Cubes.RemoveAt(0);
            Destroy(cubeToRemove);
        }
    }

    // Add a new cube at the next position
    void AddACube()
    {
        int randomIndex = Random.Range(0, CubePrefabs.Count);
        GameObject newCube = Instantiate(CubePrefabs[randomIndex]);

        newCube.transform.position = new Vector3(0f, 1f, nextCubePosZ);
        newCube.transform.parent = this.transform;

        numCubes++;
        newCube.name = numCubes.ToString() + "_" + newCube.name;

        Cubes.Add(newCube);

        nextCubePosZ += CubeLenZ;
    }

    // Called when the player collects a cube
    public void CubeAdjustment(GameObject ExitCube)
    {
        Debug.Log("Player collected cube at Z: " + ExitCube.transform.position.z);

        AddACube();

        if (Cubes.Contains(ExitCube))
        {
            Cubes.Remove(ExitCube);
            Destroy(ExitCube);
        }

        while (Cubes.Count > CubeCountBehind + CubeCountInFront)
        {
            DeleteEnd();
        }
    }
}
