using com.al_arcade.mcq;
using DG.Tweening;
using UnityEngine;

public class McqCompetitor : MonoBehaviour
{

    private McqGameManager _manager;

    private float[] _lanes = new float[4] { -5.8f, -1.8f, 2.2f, 6.2f };
    private Transform[] _runners = new Transform[2];
    private float _initialSpeed;
    private float _currentSpeed;
    private bool _isRunning;
    private Vector3 _startPosition;
    private float timer = 1.5f;

    private void Awake()
    {
        _startPosition = transform.position;
        for (int i = 0; i < 2; i++)
        {
            _runners[i] = transform.GetChild(i);
            _runners[i].localPosition =
                new Vector3(_runners[i].localPosition.x, 0, Random.Range(2f,4f));
        }

        Invoke(nameof(SwitchLane), 4);
    }

    public void SetupManager(McqGameManager manager)
    {
        if (manager == null) print("Null manager");
        _manager = manager;
        manager.onAnswerGiven.AddListener(ChangeZLevel);
        manager.onGameOver.AddListener(Stop);
    }
    private void ChangeZLevel(bool correct)
    {
        PartialStop();
        foreach (Transform runner in _runners)
        {
            runner.DOKill();
            float targetZ = runner.position.z + Random.Range(4f, 10f) * (correct ? -1.5f : 1);
            runner.DOMoveZ(targetZ + _initialSpeed * timer, timer)
                .SetEase(Ease.OutQuad).OnComplete(() =>
                {
                    RunForward(_initialSpeed);
                });
        }
        Invoke(nameof(SwitchLane), 5);
    }

    public void SwitchLane()
    {
        foreach (Transform runner in _runners)
        {
            runner.DOKill();
            runner.DOLocalMoveX(_lanes[Random.Range(0, _lanes.Length)], 0.8f).SetEase(Ease.OutQuad);
        }
            
    }

    public void RunForward(float speed)
    {
        _initialSpeed = speed;
        _currentSpeed = speed;
        _isRunning = true;
    }

    private void PartialStop()
    {
        _currentSpeed = 0;
        _isRunning = false;
    }
    public void Stop()
    {
        foreach (Transform runner in _runners)
        {
            runner.GetComponentInChildren<Animator>().Play("closing");
        }
        _currentSpeed = 0;
        _isRunning = false;
    }

    public void ResetToStart()
    {
        //Stop();
        DOTween.Kill(transform);
        transform.position = _startPosition;
        transform.rotation = Quaternion.identity;
        transform.localScale = Vector3.one;
        foreach (Transform runner in _runners)
        {
            runner.DOKill();
            runner.transform.localPosition = new Vector3(runner.localPosition.x, 0, Random.Range(2f, 4f));
            runner.GetComponentInChildren<Animator>().Play("opening");
        }
        Invoke(nameof(SwitchLane), 4);
    }
    private void Update()
    {
        if (!_isRunning) return;

        transform.position += Vector3.forward * (_currentSpeed * Time.deltaTime);
    }
}
