using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using System.Linq;
using EventsAppQuest.Web.Application;
using EventsAppQuest.Web.Domain;

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Faixa de indicadores simples: sessão pronta para follow-up, alta intenção, proposta em risco, pronta para fechamento.
    /// </summary>
    public class CRMMetricsStripView : 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;
            var indicators = WebRuntimeContext.IndicatorsService;
            if (data == null || indicators == null) return;
            var font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");

            var allLabels = new HashSet<string>();
            foreach (var opp in data.GetOpportunities())
            {
                SessionRecord session = null;
                if (!string.IsNullOrEmpty(opp.SessionRecordId))
                    session = data.GetSessions().FirstOrDefault(s => s.Id == opp.SessionRecordId);
                ProposalRecord proposal = null;
                if (!string.IsNullOrEmpty(opp.ProposalRecordId))
                    proposal = data.GetProposals().FirstOrDefault(p => p.Id == opp.ProposalRecordId);
                foreach (var label in indicators.GetIndicatorsForOpportunity(opp, session, proposal))
                    allLabels.Add(label);
                if (proposal != null)
                    foreach (var label in indicators.GetIndicatorsForProposal(proposal, opp))
                        allLabels.Add(label);
            }

            var go = new GameObject("MetricsStrip");
            go.transform.SetParent(_content, false);
            var rt = go.AddComponent<RectTransform>();
            rt.sizeDelta = new Vector2(0, 24);
            var text = go.AddComponent<Text>();
            text.text = "Indicadores: " + (allLabels.Count > 0 ? string.Join(" · ", allLabels) : "—");
            text.font = font;
            text.fontSize = 13;
        }

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