using UnityEngine;
using TMPro;
using System.Collections;

/// <summary>
/// Simple message box UI manager.
/// Attach to a Canvas with a child panel containing a TMP_Text component.
/// Usage: MessageBoxController.Show("Your message here");
/// </summary>
public class MessageBoxController : MonoBehaviour
{
    public static MessageBoxController instance;

    [Header("UI References")]
    public GameObject messagePanel;
    public TMP_Text messageText;
    
    [Header("Settings")]
    public float defaultDisplayTime = 3f;
    public float fadeSpeed = 2f;

    private CanvasGroup canvasGroup;
    private Coroutine hideCoroutine;

    void Awake()
    {
        // Singleton pattern
        if (instance == null)
        {
            instance = this;
        }
        else
        {
            Destroy(gameObject);
            return;
        }

        // Get or add canvas group for fading
        if (messagePanel != null)
        {
            canvasGroup = messagePanel.GetComponent<CanvasGroup>();
            if (canvasGroup == null)
            {
                canvasGroup = messagePanel.AddComponent<CanvasGroup>();
            }
        }

        // Hide on start
        HideImmediate();
    }

    /// <summary>
    /// Show a message for a specified duration
    /// </summary>
    public void ShowMessage(string message, float duration = -1)
    {
        if (duration < 0) duration = defaultDisplayTime;

        if (messageText != null)
        {
            messageText.text = message;
        }

        if (messagePanel != null)
        {
            messagePanel.SetActive(true);
            if (canvasGroup != null)
            {
                canvasGroup.alpha = 1f;
            }
        }

        // Cancel any existing hide coroutine
        if (hideCoroutine != null)
        {
            StopCoroutine(hideCoroutine);
        }

        // Start new hide coroutine
        hideCoroutine = StartCoroutine(HideAfterDelay(duration));
    }

    private IEnumerator HideAfterDelay(float delay)
    {
        yield return new WaitForSeconds(delay);

        // Fade out
        if (canvasGroup != null)
        {
            while (canvasGroup.alpha > 0)
            {
                canvasGroup.alpha -= Time.deltaTime * fadeSpeed;
                yield return null;
            }
        }

        HideImmediate();
    }

    private void HideImmediate()
    {
        if (messagePanel != null)
        {
            messagePanel.SetActive(false);
        }
    }

    /// <summary>
    /// Static helper to show message from anywhere
    /// </summary>
    public static void Show(string message, float duration = -1)
    {
        if (instance != null)
        {
            instance.ShowMessage(message, duration);
        }
        else
        {
            Debug.Log($"[MessageBox] {message}");
        }
    }
}
