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

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Vista mock de propostas (camada Web).
    /// </summary>
    public class ProposalRecordView : 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 prop in service.GetProposals())
            {
                var go = new GameObject("PropRow");
                go.transform.SetParent(_content, false);
                var rt = go.AddComponent<RectTransform>();
                rt.sizeDelta = new Vector2(0, 22);
                var text = go.AddComponent<Text>();
                text.text = $"{prop.Name} | {prop.Status}";
                text.font = font;
                text.fontSize = 14;
            }
        }

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