using System.Collections.Generic;
using UnityEngine;

public class RoadManager : MonoBehaviour
{
    public static RoadManager Instance { get; private set; }

    public GameObject roadPrefab;
    public Transform playerTransform;
    public int initialRoads = 5;
    public float roadLength = 30.0f;
    
    [Header("Настройки удаления")]
    public float safeDistanceBehind = 60f;
    
    [Header("Координаты полос")]
    public float[] laneXPositions = new float[] { -3.5f, 0f, 3.5f };

    private Queue<GameObject> _activeRoads = new Queue<GameObject>();
    private float _spawnZ = 0;

    private void Awake()
    {
        if (Instance == null) Instance = this;
        else Destroy(gameObject);
    }

    void Start()
    {
        if (playerTransform == null) return;

        for (int i = 0; i < initialRoads; i++)
        {
            SpawnRoad();
        }
    }

    void Update()
    {
        if (playerTransform == null) return;
        
        float oldestRoadZ = _spawnZ - (_activeRoads.Count * roadLength);
        
        if (playerTransform.position.z - oldestRoadZ > safeDistanceBehind)
        {
            SpawnRoad(); 
            RecycleOldestRoad(); 
        }
    }

    private void SpawnRoad()
    {
        GameObject road = SimpleObjectPool.Instance.Get(roadPrefab, Vector3.forward * _spawnZ, Quaternion.identity);
        _activeRoads.Enqueue(road);
        _spawnZ += roadLength;
    }

    private void RecycleOldestRoad()
    {
        if (_activeRoads.Count > 0)
        {
            GameObject oldRoad = _activeRoads.Dequeue();
            SimpleObjectPool.Instance.ReturnToPool(roadPrefab, oldRoad);
        }
    }

    public float GetRandomLaneX()
    {
        return laneXPositions[Random.Range(0, laneXPositions.Length)];
    }
   
    public float GetRandomSideLaneX(float currentX)
    {
        if (currentX < 0)
        {
            return laneXPositions[Random.Range(0, 2)];
        }
        else
        {
            return laneXPositions[Random.Range(2, 4)];
        }
    }
    public int GetLanesCount() => laneXPositions.Length;
    public float GetLaneX(int index) => laneXPositions[Mathf.Clamp(index, 0, laneXPositions.Length - 1)];
}