using UnityEngine;
using UnityEngine.UI;
using EventsAppQuest.Core;

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Controlador da camada visual de cursor e alvo no mundo: retículo simples e label do alvo apontado.
    /// Usado na UI espacial Quest; preparado para futura posição por raycast/gaze.
    /// </summary>
    public class QuestWorldCursorController : MonoBehaviour
    {
        private RectTransform _reticleRoot;
        private Image _reticleImage;
        private Text _cursorLabelText;
        private bool _built;

        /// <summary>Cor do retículo (alvo apontado/hover).</summary>
        public static readonly Color PointedReticleColor = new Color(0.95f, 0.75f, 0.2f, 0.9f);

        /// <summary>Constrói o cursor no mundo: retículo central e label com nome do alvo.</summary>
        /// <param name="worldCanvasParent">Transform do canvas World Space (ex.: do QuestWorldUIPanelLayout).</param>
        /// <param name="font">Fonte para o label.</param>
        public void Build(Transform worldCanvasParent, Font font)
        {
            if (worldCanvasParent == null || font == null) return;

            var cursorRoot = new GameObject("QuestWorldCursor");
            cursorRoot.transform.SetParent(worldCanvasParent, false);

            _reticleRoot = cursorRoot.AddComponent<RectTransform>();
            _reticleRoot.anchorMin = new Vector2(0.5f, 0.5f);
            _reticleRoot.anchorMax = new Vector2(0.5f, 0.5f);
            _reticleRoot.pivot = new Vector2(0.5f, 0.5f);
            _reticleRoot.anchoredPosition = Vector2.zero;
            _reticleRoot.sizeDelta = new Vector2(80f, 80f);

            var reticleGo = new GameObject("Reticle");
            reticleGo.transform.SetParent(_reticleRoot, false);
            var reticleRt = reticleGo.AddComponent<RectTransform>();
            reticleRt.anchorMin = new Vector2(0.5f, 0.5f);
            reticleRt.anchorMax = new Vector2(0.5f, 0.5f);
            reticleRt.pivot = new Vector2(0.5f, 0.5f);
            reticleRt.anchoredPosition = Vector2.zero;
            reticleRt.sizeDelta = new Vector2(24f, 24f);
            _reticleImage = reticleGo.AddComponent<Image>();
            _reticleImage.color = PointedReticleColor;
            _reticleImage.sprite = CreateCircleSprite();

            var labelGo = new GameObject("CursorLabel");
            labelGo.transform.SetParent(_reticleRoot, false);
            var labelRt = labelGo.AddComponent<RectTransform>();
            labelRt.anchorMin = new Vector2(0.5f, 0.5f);
            labelRt.anchorMax = new Vector2(0.5f, 0.5f);
            labelRt.pivot = new Vector2(0.5f, 0.5f);
            labelRt.anchoredPosition = new Vector2(0f, -36f);
            labelRt.sizeDelta = new Vector2(400f, 24f);
            _cursorLabelText = labelGo.AddComponent<Text>();
            _cursorLabelText.font = font;
            _cursorLabelText.fontSize = 18;
            _cursorLabelText.alignment = TextAnchor.MiddleCenter;
            _cursorLabelText.color = new Color(0.95f, 0.85f, 0.5f, 1f);
            _cursorLabelText.text = "—";

            _built = true;
        }

        /// <summary>Atualiza o indicador visual com o alvo apontado atual e opcionalmente estado de dwell.</summary>
        public void Refresh(QuestPointableTarget pointedTarget, QuestHoverDwellController hoverDwellController = null)
        {
            if (!_built) return;

            if (_reticleImage != null)
                _reticleImage.enabled = pointedTarget != null;

            if (_cursorLabelText != null)
            {
                var baseLabel = pointedTarget != null ? pointedTarget.HoverHint : "—";
                if (pointedTarget != null && hoverDwellController != null)
                {
                    var p = hoverDwellController.GetDwellProgressNormalized();
                    var ready = hoverDwellController.CurrentState != null && hoverDwellController.CurrentState.IsDwellReady;
                    if (ready)
                        baseLabel += "  (pronto)";
                    else if (p > 0f)
                        baseLabel += "  " + string.Format("{0:P0}", p);
                }
                _cursorLabelText.text = baseLabel;
            }
        }

        /// <summary>Mostra ou oculta o cursor (ex.: quando a UI espacial está desligada).</summary>
        public void SetVisible(bool visible)
        {
            if (_reticleRoot != null)
                _reticleRoot.gameObject.SetActive(visible);
        }

        public bool IsBuilt => _built;

        private static Sprite CreateCircleSprite()
        {
            const int size = 32;
            var tex = new Texture2D(size, size);
            var center = new Vector2(size * 0.5f, size * 0.5f);
            var radius = size * 0.45f;
            for (int y = 0; y < size; y++)
                for (int x = 0; x < size; x++)
                {
                    var d = Vector2.Distance(new Vector2(x, y), center);
                    tex.SetPixel(x, y, d <= radius ? Color.white : Color.clear);
                }
            tex.Apply();
            return Sprite.Create(tex, new Rect(0, 0, size, size), new Vector2(0.5f, 0.5f));
        }
    }
}
