using System.Linq;
using EventsAppQuest.Core;
using EventsAppQuest.Domain.Models;

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Gerencia o estado contextual de hotspot: abrir/fechar e alternar contexto usando dados reais da proposta
    /// (ProposalVisualHotspot, GuidedTourStep, SceneState, DecisionSummary). Base para pontos de venda imersivos no Quest.
    /// </summary>
    public class QuestHotspotContextController : UnityEngine.MonoBehaviour
    {
        private QuestPresentationSession _session;

        /// <summary>Estado contextual actual (pode ser null).</summary>
        public QuestHotspotContextState Current => _session?.CurrentHotspotContext;

        /// <summary>Liga o controlador à sessão.</summary>
        public void Bind(QuestPresentationSession session)
        {
            _session = session;
        }

        /// <summary>Abre ou alterna o contexto para o hotspot actual da sessão. Se já estiver aberto para o mesmo hotspot, fecha.</summary>
        /// <param name="source">Origem da acção (ex.: "Selection", "Dwell", "ExplicitAction").</param>
        public void OpenOrToggleForCurrentHotspot(string source)
        {
            if (_session == null) return;
            var hotspot = _session.CurrentHotspot;
            if (hotspot == null)
            {
                CloseContext();
                return;
            }
            if (_session.CurrentHotspotContext != null
                && _session.CurrentHotspotContext.IsContextOpen
                && _session.CurrentHotspotContext.HotspotId == hotspot.Id)
            {
                CloseContext();
                return;
            }
            OpenContextForHotspot(hotspot, source);
        }

        /// <summary>Abre o contexto para o hotspot indicado, preenchendo a partir da proposta.</summary>
        public void OpenContextForHotspot(ProposalVisualHotspot hotspot, string source)
        {
            if (_session == null || hotspot == null) return;

            ProposalGuidedTourStep relatedStep = null;
            if (!string.IsNullOrEmpty(hotspot.RelatedGuidedTourStepId) && _session.GuidedSteps != null)
                relatedStep = _session.GuidedSteps.FirstOrDefault(s => s.Id == hotspot.RelatedGuidedTourStepId);

            ProposalSceneState relatedState = null;
            if (_session.SceneStates != null && _session.SceneStates.Count > 0)
            {
                var withHotspot = _session.SceneStates.FirstOrDefault(s =>
                    s.PrimaryHotspotIds != null && s.PrimaryHotspotIds.Contains(hotspot.Id));
                if (withHotspot != null) relatedState = withHotspot;
            }

            var summary = BuildContextSummary(hotspot, relatedStep, relatedState);
            var salesMessage = BuildSalesMessage(hotspot, relatedStep);

            _session.CurrentHotspotContext = new QuestHotspotContextState
            {
                HotspotId = hotspot.Id,
                IsContextOpen = true,
                ContextTitle = hotspot.Title ?? hotspot.Description ?? "Ponto de destaque",
                ContextSummary = summary,
                SalesMessage = salesMessage,
                RelatedGuidedStepId = relatedStep?.Id,
                RelatedSceneStateId = relatedState?.Id,
                IsPremiumUpsell = hotspot.IsPremiumUpsell,
                PriorityLevel = hotspot.HighlightPriority,
                OpenedBySource = source ?? "Selection"
            };
            _session.HotspotContextOpenCount++;
        }

        /// <summary>Fecha o contexto do hotspot (painel contextual escondido).</summary>
        public void CloseContext()
        {
            if (_session?.CurrentHotspotContext == null) return;
            _session.CurrentHotspotContext.IsContextOpen = false;
        }

        private static string BuildContextSummary(ProposalVisualHotspot hotspot,
            ProposalGuidedTourStep relatedStep,
            ProposalSceneState relatedState)
        {
            var parts = new System.Collections.Generic.List<string>();
            if (!string.IsNullOrEmpty(hotspot.Description))
                parts.Add(hotspot.Description.Trim());
            if (relatedStep != null && !string.IsNullOrEmpty(relatedStep.Description))
                parts.Add(relatedStep.Description.Trim());
            if (relatedState != null && !string.IsNullOrEmpty(relatedState.Description))
                parts.Add(relatedState.Description.Trim());
            if (parts.Count == 0)
                return "Ponto de destaque da proposta. Foco comercial neste elemento.";
            return string.Join(" ", parts.Take(2));
        }

        private static string BuildSalesMessage(ProposalVisualHotspot hotspot, ProposalGuidedTourStep relatedStep)
        {
            if (!string.IsNullOrEmpty(relatedStep?.SalesMessage))
                return relatedStep.SalesMessage.Trim();
            if (hotspot.IsPremiumUpsell)
                return "Oportunidade de valor acrescido. Destaque premium na experiência.";
            if (hotspot.SalesValueScore > 0)
                return "Elemento-chave para o impacto comercial da proposta.";
            return "Foco neste ponto para reforçar a narrativa de venda.";
        }
    }
}
