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

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Vista de sessões Quest na Web: SessionId, recomendação, CTA, próxima ação, prioridade, artefactos e timestamp.
    /// </summary>
    public class SessionRecordView : 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 sess in service.GetSessions())
            {
                var go = new GameObject("SessionRow");
                go.transform.SetParent(_content, false);
                var rt = go.AddComponent<RectTransform>();
                rt.sizeDelta = new Vector2(0, 58);
                var text = go.AddComponent<Text>();
                var sessionId = sess.SessionId ?? sess.Id;
                var ts = sess.LastSessionTimestamp ?? sess.HeldAt ?? sess.CreatedAt;
                var tsStr = ts.HasValue ? ts.Value.ToString("g") : "—";
                text.text = $"{sessionId} | {sess.FinalDecisionState}\n";
                text.text += $"Recom.: {sess.RecommendedProposalId ?? "—"} | Sel.: {sess.SelectedProposalId ?? "—"} | CTA: {sess.ConfirmedCTA ?? "—"}\n";
                text.text += $"Próx. ação: {sess.SuggestedNextAction ?? "—"} | Prioridade: {sess.FollowUpPriority} | Última sessão: {tsStr}\n";
                text.text += $"Resumo: {sess.OutcomeSummary ?? "—"} | Confiança: {sess.ConfidenceLevel ?? "—"} | Engajamento: {sess.EngagementLabel ?? "—"} | Qualidade: {sess.QualityLabel ?? "—"}\n";
                text.text += $"Export:{Bool(sess.HasExportPayload)} Handoff:{Bool(sess.HasHandoffReport)} Summary:{Bool(sess.HasShareableSummary)} Quality:{Bool(sess.HasQualityAssessment)} ImprovementPlan:{Bool(sess.HasImprovementPlan)}";
                text.font = font;
                text.fontSize = 10;
            }
        }

        private static string Bool(bool v) => v ? "✓" : "—";

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