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

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Gerencia a comparação contextual entre dois hotspots: abrir/fechar, trocar lados,
    /// preencher a partir da proposta (ProposalVisualHotspot, GuidedTourStep, DecisionSummary).
    /// </summary>
    public class QuestHotspotComparisonController : UnityEngine.MonoBehaviour
    {
        private QuestPresentationSession _session;

        /// <summary>Estado da comparação actual (pode ser null).</summary>
        public QuestHotspotComparisonState Current => _session?.CurrentHotspotComparison;

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

        /// <summary>Abre a comparação a partir do hotspot actual: esquerda = actual, direita = próximo ou primeiro da lista.</summary>
        /// <param name="source">Origem (ex.: "ContextPanel", "HotspotContext").</param>
        public void OpenComparisonFromCurrentHotspot(string source)
        {
            if (_session == null || _session.Hotspots == null || _session.Hotspots.Count == 0) return;
            var left = _session.CurrentHotspot;
            if (left == null) return;
            ProposalVisualHotspot right = null;
            if (_session.Hotspots.Count >= 2)
            {
                var nextIndex = _session.CurrentHotspotIndex + 1;
                if (nextIndex < _session.Hotspots.Count)
                    right = _session.Hotspots[nextIndex];
                else
                    right = _session.Hotspots[0];
            }
            else
                right = left;
            BuildAndSetComparison(left, right, source ?? "ContextPanel");
        }

        /// <summary>Fecha o painel de comparação (volta ao contexto ou micro narrativa).</summary>
        public void CloseComparison()
        {
            if (_session?.CurrentHotspotComparison == null) return;
            _session.CurrentHotspotComparison.IsComparisonOpen = false;
        }

        /// <summary>Troca os lados esquerdo e direito da comparação.</summary>
        public void SwapSides()
        {
            var comp = _session?.CurrentHotspotComparison;
            if (comp == null || !comp.IsComparisonOpen) return;
            var leftId = comp.LeftHotspotId;
            var rightId = comp.RightHotspotId;
            var leftTitle = comp.LeftTitle;
            var rightTitle = comp.RightTitle;
            var leftSales = comp.LeftSalesMessage;
            var rightSales = comp.RightSalesMessage;
            comp.LeftHotspotId = rightId;
            comp.RightHotspotId = leftId;
            comp.LeftTitle = rightTitle;
            comp.RightTitle = leftTitle;
            comp.LeftSalesMessage = rightSales;
            comp.RightSalesMessage = leftSales;
            SwapBetterFor(ref comp.BetterForExperience);
            SwapBetterFor(ref comp.BetterForUpsell);
            SwapBetterFor(ref comp.BetterForClarity);
        }

        private static void SwapBetterFor(ref string side)
        {
            if (side == "Left") side = "Right";
            else if (side == "Right") side = "Left";
        }

        private void BuildAndSetComparison(ProposalVisualHotspot left, ProposalVisualHotspot right, string source)
        {
            if (_session == null || left == null || right == null) return;

            var leftStep = GetRelatedStep(left);
            var rightStep = GetRelatedStep(right);
            var leftSales = BuildSalesMessage(left, leftStep);
            var rightSales = BuildSalesMessage(right, rightStep);

            var betterExp = left.SalesValueScore >= right.SalesValueScore ? "Left" : "Right";
            string betterUpsell = null;
            if (left.IsPremiumUpsell && !right.IsPremiumUpsell) betterUpsell = "Left";
            else if (right.IsPremiumUpsell && !left.IsPremiumUpsell) betterUpsell = "Right";
            else if (left.IsPremiumUpsell && right.IsPremiumUpsell) betterUpsell = "Left";
            var betterClarity = (!string.IsNullOrEmpty(left.Description) && string.IsNullOrEmpty(right.Description)) ? "Left"
                : (string.IsNullOrEmpty(left.Description) && !string.IsNullOrEmpty(right.Description)) ? "Right"
                : (!string.IsNullOrEmpty(left.Description) && !string.IsNullOrEmpty(right.Description)) ? (left.Description.Trim().Length >= right.Description.Trim().Length ? "Left" : "Right")
                : (string?)null;

            var summary = _session.DecisionSummary != null && !string.IsNullOrEmpty(_session.DecisionSummary.ExecutiveShortSummary)
                ? _session.DecisionSummary.ExecutiveShortSummary.Trim()
                : "Compare os dois pontos para reforçar a proposta.";

            _session.CurrentHotspotComparison = new QuestHotspotComparisonState
            {
                LeftHotspotId = left.Id,
                RightHotspotId = right.Id,
                LeftTitle = left.Title ?? left.Description ?? "—",
                RightTitle = right.Title ?? right.Description ?? "—",
                LeftSalesMessage = leftSales,
                RightSalesMessage = rightSales,
                BetterForExperience = betterExp,
                BetterForUpsell = betterUpsell,
                BetterForClarity = betterClarity,
                ComparisonSummary = summary,
                IsComparisonOpen = true,
                OpenedBySource = source
            };
            _session.ComparisonOpenCount++;
        }

        private ProposalGuidedTourStep GetRelatedStep(ProposalVisualHotspot hotspot)
        {
            if (string.IsNullOrEmpty(hotspot.RelatedGuidedTourStepId) || _session?.GuidedSteps == null) return null;
            return _session.GuidedSteps.FirstOrDefault(s => s.Id == hotspot.RelatedGuidedTourStepId);
        }

        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.";
            if (hotspot.SalesValueScore > 0)
                return "Elemento-chave para o impacto comercial.";
            return "Foco neste ponto para reforçar a narrativa de venda.";
        }
    }
}
