using Player;
using UnityEngine;

public class PauseMenuController : MonoBehaviour
{
    [Header("References")]
    [SerializeField] private GameObject pauseMenuPanel;
    [SerializeField] private GameObject settingsPanel;
    [SerializeField] private PlayerController playerController;

    private bool isPaused = false;

    private void Start()
    {
        pauseMenuPanel.SetActive(false);
        settingsPanel.SetActive(false);
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            // If settings are open, the first Escape press should close them
            if (settingsPanel.activeSelf)
            {
                CloseSettings();
            }
            // If only the pause menu is open, Escape should resume the game
            else if (isPaused)
            {
                ResumeGame();
            }
            // If not paused, Escape should pause the game
            else
            {
                PauseGame();
            }
        }
    }

    public void PauseGame()
    {
        isPaused = true;
        Time.timeScale = 0f;
        pauseMenuPanel.SetActive(true);
        settingsPanel.SetActive(false); // Ensure settings are closed initially

        Cursor.lockState = CursorLockMode.None;
        Cursor.visible = true;
        if (playerController != null) playerController.inputLocked = true;
    }

    public void ResumeGame()
    {
        isPaused = false;
        Time.timeScale = 1f;
        pauseMenuPanel.SetActive(false);
        settingsPanel.SetActive(false);

        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
        if (playerController != null) playerController.inputLocked = false;
    }

    // --- Button Methods ---

    public void OnResumeButtonClicked()
    {
        ResumeGame();
    }

    public void OpenSettings()
    {
        pauseMenuPanel.SetActive(false);
        settingsPanel.SetActive(true);
    }

    public void CloseSettings()
    {
        settingsPanel.SetActive(false);
        pauseMenuPanel.SetActive(true);
    }

    public void OnExitButtonClicked()
    {
        Debug.Log("Exiting application...");
        Application.Quit();
    }
}