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

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Exibe o passo atual do roteiro guiado: título, descrição e mensagem comercial.
    /// </summary>
    public class QuestGuidedStepView : MonoBehaviour
    {
        private Text _titleText;
        private Text _descriptionText;
        private Text _salesMessageText;

        public void Build(Transform parent, Font font)
        {
            var go = new GameObject("QuestGuidedStepView");
            go.transform.SetParent(parent, false);
            go.AddComponent<LayoutElement>().preferredHeight = 140;
            var vlg = go.AddComponent<VerticalLayoutGroup>();
            vlg.spacing = 8;
            vlg.padding = new RectOffset(20, 12, 20, 12);
            vlg.childForceExpandHeight = false;

            var titleGo = new GameObject("Title");
            titleGo.transform.SetParent(go.transform, false);
            titleGo.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 24);
            _titleText = titleGo.AddComponent<Text>();
            _titleText.font = font;
            _titleText.fontSize = 18;
            _titleText.fontStyle = FontStyle.Bold;
            _titleText.text = "Passo atual";

            _descriptionText = AddLabel(go.transform, "", 14, font);
            _salesMessageText = AddLabel(go.transform, "", 14, font);
        }

        public void Refresh(QuestPresentationSession session)
        {
            var step = session?.CurrentStep;
            if (step != null)
            {
                _titleText.text = string.IsNullOrEmpty(step.Title) ? "Passo " + (session.CurrentGuidedStepIndex + 1) : step.Title;
                _descriptionText.text = step.Description ?? "";
                _descriptionText.gameObject.SetActive(!string.IsNullOrEmpty(step.Description));
                _salesMessageText.text = step.SalesMessage ?? "";
                _salesMessageText.gameObject.SetActive(!string.IsNullOrEmpty(step.SalesMessage));
            }
            else
            {
                _titleText.text = "Nenhum passo";
                _descriptionText.text = "";
                _descriptionText.gameObject.SetActive(false);
                _salesMessageText.text = "";
                _salesMessageText.gameObject.SetActive(false);
            }
        }

        private static Text AddLabel(Transform parent, string text, int fontSize, Font font)
        {
            var go = new GameObject("Label");
            go.transform.SetParent(parent, false);
            go.AddComponent<RectTransform>().sizeDelta = new Vector2(0, fontSize + 6);
            var t = go.AddComponent<Text>();
            t.text = text;
            t.font = font;
            t.fontSize = fontSize;
            return t;
        }
    }
}
