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

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Lista mock de leads da camada Web.
    /// </summary>
    public class LeadListView : 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 lead in service.GetLeads())
                CreateRow(_content, lead, 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, WebLead lead, Font font)
        {
            var go = new GameObject("LeadRow");
            go.transform.SetParent(parent, false);
            var rt = go.AddComponent<RectTransform>();
            rt.sizeDelta = new Vector2(0, 22);
            var text = go.AddComponent<Text>();
            text.text = $"{lead.Name} | {lead.Company} | {lead.Status}";
            text.font = font;
            text.fontSize = 14;
        }
    }
}
