using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace MajacloudSdk.Samples.Starter
{
    public sealed class StatusToast : MonoBehaviour
    {
        [SerializeField] private CanvasGroup group;
        [SerializeField] private TMP_Text label;
        [SerializeField] private Image background;
        [SerializeField] private float visibleSeconds = 2.5f;
        private static readonly Color Normal = new Color32(19, 33, 60, 255);
        private static readonly Color Error = new Color32(200, 48, 54, 255);
        private Coroutine _hide;

        public void Show(string message, bool isError = false)
        {
            if (label != null) label.text = message;
            if (background != null) background.color = isError ? Error : Normal;
            if (group != null) group.alpha = 1f;
            if (_hide != null) StopCoroutine(_hide);
            _hide = StartCoroutine(HideLater());
        }

        private IEnumerator HideLater()
        {
            yield return new WaitForSecondsRealtime(visibleSeconds);
            float t = 0f;
            while (t < 0.25f && group != null)
            {
                t += Time.unscaledDeltaTime;
                group.alpha = 1f - t / 0.25f;
                yield return null;
            }
            if (group != null) group.alpha = 0f;
        }
    }
}
