using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;

public class PauseManager : MonoBehaviour
{
    public static PauseManager Instance;

    [Header("Input")]
    [SerializeField] private InputActionReference pauseAction;

    [Header("UI")]
    [SerializeField] private GameObject pauseMenuRoot;
    [SerializeField] private Button resumeButton;
    [SerializeField] private Button quitButton;

    private bool isPaused;

    private void Awake()
    {
        Instance = this;

        // Subscribe UI buttons
        if (resumeButton != null)
            resumeButton.onClick.AddListener(Resume);

        if (quitButton != null)
            quitButton.onClick.AddListener(QuitGame);
    }

    private void OnDestroy()
    {
        // Unsubscribe UI buttons
        if (resumeButton != null)
            resumeButton.onClick.RemoveListener(Resume);

        if (quitButton != null)
            quitButton.onClick.RemoveListener(QuitGame);
    }

    private void OnEnable()
    {
        if (pauseAction == null) return;

        pauseAction.action.performed += OnPause;
        pauseAction.action.Enable();
    }

    private void OnDisable()
    {
        if (pauseAction == null) return;

        pauseAction.action.performed -= OnPause;
        pauseAction.action.Disable();
    }

    private void OnPause(InputAction.CallbackContext ctx)
    {
        if (!isPaused || pauseMenuRoot.activeSelf)
        {
            TogglePause(false);
        }
    }

    public void TogglePause(bool hideMenu)
    {
        isPaused = !isPaused;
        ApplyPauseState(isPaused);

        if (hideMenu && isPaused)
        {
            pauseMenuRoot.SetActive(false);
        }
    }

    public void Resume()
    {
        if (!isPaused) return;
        TogglePause(false);
    }

    private void ApplyPauseState(bool pause)
    {
        Time.timeScale = pause ? 0f : 1f;

        if (pauseMenuRoot != null)
            pauseMenuRoot.SetActive(pause);

        Cursor.lockState = pause ? CursorLockMode.None : CursorLockMode.Locked;
        Cursor.visible = pause;

#if UNITY_EDITOR
        Debug.Log(pause ? "[Pause] Game Paused" : "[Pause] Game Resumed");
#endif
    }

    // ─────────────────────────────
    // QUIT
    // ─────────────────────────────

    public void QuitGame()
    {
        Time.timeScale = 1f;

#if UNITY_EDITOR
        Debug.Log("[Pause] Quit Game");
        UnityEditor.EditorApplication.isPlaying = false;
#else
        Application.Quit();
#endif
    }

    public bool IsPaused()
    {
        return isPaused;
    }
}
