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

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Faixa de comparação de snapshots: direção atual, principal melhoria/regressão e timestamp.
    /// </summary>
    public class EventCycleSnapshotComparisonStripView : 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 data = WebRuntimeContext.DataService;
            if (data == null) return;
            var font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");

            var state = EventCycleSnapshotComparisonController.GetGlobalComparisonState();
            var go = new GameObject("Strip");
            go.transform.SetParent(_content, false);
            go.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 22);
            var text = go.AddComponent<Text>();
            text.font = font;
            text.fontSize = 12;

            if (state.TotalComparisons == 0 || state.LatestComparison == null)
            {
                text.text = "Comparação de snapshots: nenhuma comparação.";
                return;
            }

            var c = state.LatestComparison;
            text.text = $"Evolução: {c.OverallDirection} [{c.CycleId}] | + {c.MainImprovement ?? "—"} | − {c.MainRegression ?? "—"} | {(c.ComparedAt?.ToString("yyyy-MM-dd HH:mm") ?? "—")}";
        }

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

