
using UnityEngine;

namespace Obstacle
{
    public class ObstacleSpawner : MonoBehaviour
    {
        [Header("Настройки спавна")]
    public float spawnDistance = 150f;
    
    [Header("Статические препятствия")]
    public GameObject[] staticObstaclePrefabs; 
    
    [HideInInspector] public float currentSpawnInterval = 1f;
    [HideInInspector] public float currentObstacleChance = 0.2f;

    private Transform _playerTransform;
    private RoadManager _roadManager;
    private float _timer;

    void Start()
    {
        _playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
        _roadManager = RoadManager.Instance;
    }

    void Update()
    {
        if (_playerTransform == null) return;

        _timer += Time.deltaTime;
        
        if (_timer >= currentSpawnInterval)
        {
            _timer = 0f;
            SpawnObject();
        }
    }

    private void SpawnObject()
    {
        float spawnX = _roadManager.GetRandomLaneX();
        float spawnZ = _playerTransform.position.z + spawnDistance;
        Vector3 spawnPos = new Vector3(spawnX, 0f, spawnZ);
        
        if (staticObstaclePrefabs.Length > 0 && Random.value < currentObstacleChance)
        {
            GameObject prefab = staticObstaclePrefabs[Random.Range(0, staticObstaclePrefabs.Length)];
            
            spawnPos.y = prefab.transform.position.y;
  
            GameObject obstacle = SimpleObjectPool.Instance.Get(prefab, spawnPos, prefab.transform.rotation);
            
            StaticObstacle obsScript = obstacle.GetComponent<StaticObstacle>();
            if (obsScript == null) obsScript = obstacle.AddComponent<StaticObstacle>();
            
            obsScript.Init(_playerTransform, prefab);
        }
        else 
        {
                TrafficCar car = TrafficPool.Instance.GetCar();
                if (car != null)
                {
                    car.Init(_playerTransform, _roadManager);
                    spawnPos.y = car.transform.position.y;
                    car.SetStartPosition(spawnPos);

                    car.transform.rotation = Quaternion.Euler(0, spawnX < 0 ? 180 : 0, 0);

                    if (Random.value < 0.5f)
                        car.SetBehavior(RandomLaneChangingBehavior.Instance);
                    else
                        car.SetBehavior(SimpleLaneFollowingBehavior.Instance);
                
                    car.gameObject.SetActive(true);
                }
        }
    }
    }
}