using Unity.VisualScripting;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    [SerializeField]
    private TMPro.TMP_Text m_timer;

    public static GameManager Instance => instance;
    private static GameManager instance;

    public PlayerMovement Player => m_player;
    private PlayerMovement m_player;

    public bool RunTimer => m_runTimer;
    private float m_currentTimer = 0f;
    private bool m_runTimer = false;
    private bool m_runGame = false;

    private void Awake()
    {
        Application.runInBackground = true;
        instance = this;
        m_player = Object.FindFirstObjectByType<PlayerMovement>();
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape) && m_runGame)
        {
            m_runTimer = false;
            m_player.SetPlayerActive(false);
            MenuManager.Instance.OpenMenu("CONTINUE");
            EnemySpawner.Instance.SetSpawnerEnabled(false);
        }

        if (m_runTimer)
        {
            m_currentTimer += Time.deltaTime;
        }

        RunTimerFunc();
    }

    private void RunTimerFunc()
    {
        var _minutes = Mathf.FloorToInt(m_currentTimer / 60f);
        var _seconds = Mathf.FloorToInt(m_currentTimer - (_minutes * 60f));

        var _minString = _minutes.ToString();
        if (_minutes < 10)
            _minString = "0" + _minutes;

        var _secString = _seconds.ToString();
        if (_seconds < 10)
            _secString = "0" + _seconds;


        m_timer.text = $"{_minString}:{_secString}";
    }


    public void StartOrContinue()
    {
        m_player.SetPlayerActive(true);
        m_runTimer = true;

        if (m_runGame)
            EnemySpawner.Instance.SetSpawnerEnabled(true);
        else
            EnemySpawner.Instance.CleanUpEnemies();

        m_runGame = true;
    }

    public void KillPlayer()
    {
        m_runTimer = false;
        m_runGame = false;
        m_player.SetPlayerActive(false);
        MenuManager.Instance.OpenMenu("RESTART");
        EnemySpawner.Instance.SetSpawnerEnabled(false);

        Cursor.lockState = CursorLockMode.None;
        Cursor.visible = true;
    }
}
