using UnityEngine;
using UnityEngine.UI;
using EventsAppQuest.Web.Application;
using EventsAppQuest.Web.Domain;

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Quadro mock de oportunidades por estágio (camada Web).
    /// </summary>
    public class OpportunityBoardView : MonoBehaviour, IWebContentRoot
    {
        private Transform _content;

        public void SetContentRoot(Transform contentRoot) => _content = contentRoot;

        private void Start()
        {
            Refresh();
            WebRuntimeContext.OnDataChanged += Refresh;
        }
        private void OnDestroy() => WebRuntimeContext.OnDataChanged -= Refresh;

        public void Refresh()
        {
            if (_content == null) return;
            ClearContent(_content);
            var service = WebRuntimeContext.DataService;
            if (service == null) return;
            var font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
            foreach (var opp in service.GetOpportunities())
                CreateRow(_content, opp, font);
        }

        private static void ClearContent(Transform content)
        {
            for (var i = content.childCount - 1; i >= 0; i--)
                Destroy(content.GetChild(i).gameObject);
        }

        private static void CreateRow(Transform parent, SalesOpportunity opp, Font font)
        {
            var go = new GameObject("OppRow");
            go.transform.SetParent(parent, false);
            var rt = go.AddComponent<RectTransform>();
            rt.sizeDelta = new Vector2(0, 36);
            var text = go.AddComponent<Text>();
            text.text = $"{opp.Title} | {opp.Stage} | €{opp.Value:N0} | Prioridade: {opp.CommercialPriority}\n  Próx. ação: {opp.SuggestedNextAction ?? "—"}";
            text.font = font;
            text.fontSize = 12;
        }
    }
}
