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

namespace NeoriginPCSDK
{
    public class NeoriginSDKToastManager : MonoBehaviour
    {
        private const float PanelHeight = 80f;
        private const float MinPanelWidth = 360f;
        private const float MaxPanelWidthRatio = 0.92f;
        private const float HorizontalPadding = 40f;

        private static NeoriginSDKToastManager _instance;
        private Coroutine _currentToastRoutine;
        
        // 缓存UI组件引用
        private CanvasGroup _panelCanvasGroup;
        private Text _toastText;
        private GameObject _panel;

        public static NeoriginSDKToastManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    SetupManager();
                }
                return _instance;
            }
        }

        private static void SetupManager()
        {
            GameObject managerObj = new GameObject("NeoriginSDKToastManager");
            _instance = managerObj.AddComponent<NeoriginSDKToastManager>();
            DontDestroyOnLoad(managerObj);
            _instance.CreateToastSystem(); // 初始化UI
        }

        public void Show(string message, float duration = 3f)
        {
            if (_currentToastRoutine != null)
            {
                StopCoroutine(_currentToastRoutine);
            }
            _currentToastRoutine = StartCoroutine(ShowToastRoutine(message, duration));
        }

        private IEnumerator ShowToastRoutine(string message, float duration)
        {
            if (_panel == null || _toastText == null)
            {
                Debug.LogError("[SDK] Toast system not initialized!");
                yield break;
            }

            _toastText.text = message;
            AdjustPanelWidthForMessage();
            _panel.SetActive(true);

            // 淡入动画
            float fadeTime = 0.2f;
            float elapsed = 0;

            while (elapsed < fadeTime)
            {
                _panelCanvasGroup.alpha = Mathf.Lerp(0, 1, elapsed / fadeTime);
                elapsed += Time.deltaTime;
                yield return null;
            }
            _panelCanvasGroup.alpha = 1;

            // 等待显示时间
            yield return new WaitForSeconds(duration);

            // 淡出动画
            elapsed = 0;
            while (elapsed < fadeTime)
            {
                _panelCanvasGroup.alpha = Mathf.Lerp(1, 0, elapsed / fadeTime);
                elapsed += Time.deltaTime;
                yield return null;
            }

            _panel.SetActive(false);
            _currentToastRoutine = null;
        }

        private void AdjustPanelWidthForMessage()
        {
            if (_panel == null || _toastText == null)
            {
                return;
            }

            RectTransform panelRT = _panel.GetComponent<RectTransform>();
            RectTransform canvasRT = _panel.transform.parent as RectTransform;
            if (panelRT == null)
            {
                return;
            }

            float canvasWidth = canvasRT != null ? canvasRT.rect.width : 0f;
            if (canvasWidth <= 0f)
            {
                canvasWidth = 1920f;
            }

            float maxWidth = canvasWidth * MaxPanelWidthRatio;
            float preferredWidth = _toastText.preferredWidth + HorizontalPadding;
            float targetWidth = Mathf.Clamp(preferredWidth, MinPanelWidth, maxWidth);
            panelRT.sizeDelta = new Vector2(targetWidth, PanelHeight);
        }

        private void CreateToastSystem()
        {
            // 创建Canvas
            var toastCanvas = new GameObject("NeoriginSDKToastCanvas", 
                typeof(Canvas), 
                typeof(CanvasScaler), 
                typeof(GraphicRaycaster));
            
            var canvas = toastCanvas.GetComponent<Canvas>();
            canvas.renderMode = RenderMode.ScreenSpaceOverlay;
            canvas.sortingOrder = 9999;

            // Canvas缩放设置
            var scaler = toastCanvas.GetComponent<CanvasScaler>();
            scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
            scaler.referenceResolution = new Vector2(1920, 1080);

            // 创建Toast面板
            _panel = new GameObject("NeoriginSDKToastPanel", 
                typeof(RectTransform), 
                typeof(Image), 
                typeof(CanvasGroup));
            
            _panel.transform.SetParent(toastCanvas.transform);
            
            var panelRT = _panel.GetComponent<RectTransform>();
            panelRT.anchorMin = new Vector2(0.5f, 1f);
            panelRT.anchorMax = new Vector2(0.5f, 1f);
            panelRT.pivot = new Vector2(0.5f, 1f);
            panelRT.anchoredPosition = new Vector2(0, -100);
            panelRT.sizeDelta = new Vector2(600, PanelHeight);

            // 背景设置
            var bg = _panel.GetComponent<Image>();
            bg.color = new Color(0.1f, 0.1f, 0.1f, 0.85f);
            _panelCanvasGroup = _panel.GetComponent<CanvasGroup>();
            _panelCanvasGroup.alpha = 0;

            // 创建文本
            var textObj = new GameObject("NeoriginSDKToastText", 
                typeof(RectTransform), 
                typeof(Text));
            
            textObj.transform.SetParent(_panel.transform);
            
            var textRT = textObj.GetComponent<RectTransform>();
            textRT.anchorMin = Vector2.zero;
            textRT.anchorMax = Vector2.one;
            textRT.offsetMin = new Vector2(20, 10);
            textRT.offsetMax = new Vector2(-20, -10);

            _toastText = textObj.GetComponent<Text>();
#if UNITY_2022_1_OR_NEWER
            _toastText.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
#else
            // Unity 2021及更早版本使用Arial
            _toastText.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
#endif
            _toastText.fontSize = 28;
            _toastText.resizeTextForBestFit = true;
            _toastText.resizeTextMaxSize = 28;
            _toastText.resizeTextMinSize = 16;
            _toastText.color = Color.white;
            _toastText.alignment = TextAnchor.MiddleCenter;
            _toastText.supportRichText = true;
            _toastText.horizontalOverflow = HorizontalWrapMode.Overflow;
            _toastText.verticalOverflow = VerticalWrapMode.Truncate;

            // 初始隐藏
            _panel.SetActive(false);
            DontDestroyOnLoad(toastCanvas);
        }
    }
}
