using UnityEngine;
using TMPro;
using UnityEngine.SocialPlatforms.Impl;

public class ScoreManager : MonoBehaviour
{
    public static ScoreManager instance;
    // Creating An ScoreManager object called 'instance'
    public TextMeshProUGUI scoreText;
    // Creating a TextMeshProUGUI object called 'scoreText'
    private int score = 0;
    // Creating a private integer variable called 'score' and setting it to 0

    void Start()
    {
        TextMeshProUGUI newScoreText = FindObjectOfType<TextMeshProUGUI>();
        ScoreManager.instance.SetScoreText(newScoreText);
    }
    void OnEnable()
{
   if (scoreText == null)
    {
        scoreText = GameObject.Find("ScoreText")?.GetComponent<TextMeshProUGUI>();
        if (scoreText == null)
        {
            Debug.LogError("Score Text not found in the new scene.");
            return;
        }
    }

    UpdateScoreUI();
}
    private void Awake()
    {
        if (instance == null) //Checks if instance is null (indicating there is no score manager)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
            // If instance is null, it sets the instance to this and makes the game object not destroy
        }
        else
        {
            Destroy(gameObject);
            // If a ScoreManager GameObject already exists then it is destroyed.
        }
    }

    public void SetScoreText(TextMeshProUGUI newScoreText)
    {
        if (newScoreText != null)
    {
        scoreText = newScoreText;
        UpdateScoreUI();
    }
    else
    {
        Debug.LogError("Attempted to set a null score text.");
    }
    }


    public void AddScore(int points) //Function used to add points to player's score
    {
        score += points;
        UpdateScoreUI();
    }

    public void DeductScore(int points)
    {
        if (score >= points)
        {
            score -= points;
            UpdateScoreUI();
        }
        else
        {
            Debug.Log("Not enough points!");
        }
    }

    private void UpdateScoreUI() //Changes the UI Text image to display score
    {
        scoreText.text = "Score: " + score;
    }

}