using Core.Domain;
using TMPro;
using UnityEngine;

namespace Infrastructure.Unity
{
    public class GameUiCoordinator : MonoBehaviour
    {
        [Header("References")]
        [SerializeField] private TMP_Text scoreText;
        [SerializeField] private TMP_Text highScoreText;
        [SerializeField] private GameObject gameOverUi;
        [SerializeField] private GameObject pauseUi;
        [SerializeField] private GameObject startScreenUi;

        private GameSession _session;
        private int _currentDisplayedScore;

        public void Subscribe(GameSession session)
        {
            _session = session;
            session.OnScoreChanged += UpdateScore;
            session.OnGameOver += ShowGameOverUi;
        }

        public void ShowStartScreen()
        {
            if (gameOverUi) gameOverUi.SetActive(false);
            if (startScreenUi) startScreenUi.SetActive(true);
        }

        public void HideStartScreen()
        {
            if (startScreenUi) startScreenUi.SetActive(false);
        }

        public void ShowGameOverUi()
        {
            if (gameOverUi) gameOverUi.SetActive(true);
        }

        public void ShowPauseUi()
        {
            if (pauseUi) pauseUi.SetActive(true);
        }

        public void HidePauseUi()
        {
            if (pauseUi) pauseUi.SetActive(false);
        }

        public void UpdateHighScore(int highScore)
        {
            if (highScoreText) highScoreText.text = $"BEST: {highScore}";
        }

        private void UpdateScore(int newScore)
        {
            if (!scoreText) return;

            LeanTween.cancel(scoreText.gameObject);
            scoreText.rectTransform.localScale = Vector3.one;
            LeanTween.scale(scoreText.rectTransform, Vector3.one * 1.5f, 0.5f).setEasePunch();

            LeanTween.value(scoreText.gameObject, (float val) =>
                {
                    var combo = _session?.ComboMultiplier ?? 1;
                    var comboText = combo > 1 ? $" <color=yellow>x{combo}</color>" : "";
                    scoreText.text = $"{Mathf.RoundToInt(val)}{comboText}";
                }, _currentDisplayedScore, newScore, 0.5f)
                .setEaseOutExpo();

            _currentDisplayedScore = newScore;

            if (highScoreText && _session != null)
                highScoreText.text = $"BEST: {_session.HighScore}";
        }
    }
}
