using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using TMPro;

public class UIManager : MonoBehaviour
{
    [Header("In-Game UI")]
    public TextMeshProUGUI coinText;

    [Header("Game Over UI")]
    public GameObject gameOverPanel;
    public TextMeshProUGUI finalScoreText;
    public TMP_InputField nameInputField;
    public Button saveButton;

    [Header("Scene Names")]
    public string mainMenuSceneName = "MainMenuScene"; // Имя сцены главного меню

    private const string HighScoreKey = "HighScores";

    void Start()
    {
        PlayerController.OnPlayerDied += ShowGameOverScreen;
        if (gameOverPanel != null) gameOverPanel.SetActive(false);
        if (saveButton != null) saveButton.onClick.AddListener(SaveScoreAndReturnToMenu);
    }

    void OnDestroy()
    {
        PlayerController.OnPlayerDied -= ShowGameOverScreen;
    }

    void Update()
    {
        if (coinText != null)
        {
            coinText.text = "Монеты: " + PlayerController.coinCount;
        }
    }

    void ShowGameOverScreen()
    {
        if (gameOverPanel != null && finalScoreText != null)
        {
            gameOverPanel.SetActive(true);
            finalScoreText.text = "Ваш результат: " + PlayerController.coinCount;
            if (nameInputField != null)
            {
                nameInputField.onValueChanged.AddListener(delegate { ValidateInput(); });
                saveButton.interactable = false;
            }
        }
    }

    void ValidateInput()
    {
        saveButton.interactable = !string.IsNullOrEmpty(nameInputField.text);
    }

    public void SaveScoreAndReturnToMenu()
    {
        string playerName = nameInputField.text;
        int score = PlayerController.coinCount;

        string json = PlayerPrefs.GetString(HighScoreKey, "{}");
        HighScoreList highScores = JsonUtility.FromJson<HighScoreList>(json);
        if (highScores.scores == null)
        {
            highScores.scores = new System.Collections.Generic.List<HighScoreEntry>();
        }

        highScores.scores.Add(new HighScoreEntry { playerName = playerName, score = score });

        string updatedJson = JsonUtility.ToJson(highScores);
        PlayerPrefs.SetString(HighScoreKey, updatedJson);
        PlayerPrefs.Save();

        Debug.Log("Результат сохранен. Возврат в главное меню.");

        // Возобновляем время и загружаем главное меню
        Time.timeScale = 1f;
        SceneManager.LoadScene(mainMenuSceneName);
    }
}
