using UnityEngine;
using UnityEngine.UIElements;
using System.Collections.Generic;
using System.Collections;
using Unity.VisualScripting;
using System;

public class ActiveQuestUI : MonoBehaviour, IClickBlocker
{
    [Header("UI References")]
    public UIDocument uiDocument;

    // Main UI elements
    private VisualElement questTracker;
    private Label trackerTitle;
    private Button questLogButton;
    private Button toggleTrackerButton;
    private ScrollView activeQuestsList;
    private Label noQuestsMessage;
    private VisualElement quickActions;
    private Button showAllButton;
    private Button trackLocationButton;
    private Button abandonQuestButton;

    // Popup elements
    private VisualElement questDetailsPopup;
    private VisualElement popupContent;
    private Label popupTitle;
    private Button closePopupButton;
    private VisualElement popupDetails;
    private VisualElement questInfo;
    private VisualElement objectivesList;
    private VisualElement rewardsList;
    private VisualElement popupActions;
    private Button trackButton;
    private Button navigateButton;

    // Notification elements
    private VisualElement completionNotification;
    private VisualElement progressNotification;

    // Exposed flag other systems can check to know UI is capturing pointer

    // State
    private ActiveQuest selectedQuest;
    private bool isUIVisible = false;
    private List<VisualElement> questEntries = new List<VisualElement>();
    [System.NonSerialized]
    private bool recentlyHandledClick = false; // Flag to prevent map clicks when UI handles them

    public bool IsVisible => isUIVisible;

    void OnEnable()
    {
        ClickBlockingHelper.RegisterWithClickManager(this);

        // Refresh quest list when returning from scenes (like settlements)
        // Use a coroutine to ensure other systems are ready
        StartCoroutine(RefreshOnEnable());
    }

    void OnDisable() => ClickBlockingHelper.UnregisterWithClickManager(this);

    private IEnumerator RefreshOnEnable()
    {
        // Wait a frame to ensure other systems are initialized
        yield return new WaitForEndOfFrame();

        // Check if we need to refresh the quest list
        if (QuestManager.Instance != null)
        {
            Debug.Log("ActiveQuestUI: OnEnable refresh - updating quest list");
            RefreshQuestList();
        }
    }

    /// <summary>
    /// Sets a temporary flag to block travel system clicks when UI handles a click event.
    /// This is much more reliable than trying to calculate coordinates manually.
    /// </summary>
    private void SetClickFlag()
    {
        ClickBlockingHelper.SetClickFlag("ActiveQuestUI", this, (flag) => recentlyHandledClick = flag);
    }

    private void Start()
    {
        Debug.Log("ActiveQuestUI: Start called");
        InitializeUI();
        SubscribeToEvents();

        // Delay quest refresh to ensure QuestManager is fully initialized
        StartCoroutine(DelayedQuestRefresh());
    }

    private IEnumerator DelayedQuestRefresh()
    {
        yield return new WaitForEndOfFrame();
        Debug.Log("ActiveQuestUI: Performing delayed quest refresh");
        RefreshQuestList();
    }


    private void InitializeUI()
    {
        if (uiDocument == null)
            uiDocument = GetComponent<UIDocument>();
        var root = uiDocument.rootVisualElement;
        if (root == null)
        {
            return;
        }

        // Ensure root doesn't block other UI - set to ignore picking
        root.pickingMode = PickingMode.Ignore;

        // Ensure this UI has proper sorting order to be above map but below modals
        if (uiDocument.sortingOrder == 0)
        {
            uiDocument.sortingOrder = 10; // Above map, below modals like TravelUI
        }

        // Get main elements
        questTracker = root.Q<VisualElement>("quest-tracker");
        trackerTitle = root.Q<Label>("tracker-title");
        questLogButton = root.Q<Button>("quest-log-button");
        toggleTrackerButton = root.Q<Button>("toggle-tracker-button");
        activeQuestsList = root.Q<ScrollView>("active-quests-list");
        noQuestsMessage = root.Q<Label>("no-quests-message");
        quickActions = root.Q<VisualElement>("quick-actions");
        showAllButton = root.Q<Button>("show-all-button");
        trackLocationButton = root.Q<Button>("track-location-button");
        abandonQuestButton = root.Q<Button>("abandon-quest-button");

        // Get popup elements
        questDetailsPopup = root.Q<VisualElement>("quest-details-popup");
        popupContent = root.Q<VisualElement>("popup-content");
        popupTitle = root.Q<Label>("popup-title");
        closePopupButton = root.Q<Button>("close-popup-button");
        popupDetails = root.Q<VisualElement>("popup-details");
        questInfo = root.Q<VisualElement>("quest-info");
        objectivesList = root.Q<VisualElement>("objectives-list");
        rewardsList = root.Q<VisualElement>("rewards-list");
        popupActions = root.Q<VisualElement>("popup-actions");
        trackButton = root.Q<Button>("track-button");
        navigateButton = root.Q<Button>("navigate-button");

        // Get notification elements
        completionNotification = root.Q<VisualElement>("completion-notification");
        progressNotification = root.Q<VisualElement>("progress-notification");

        // Set up event handlers
        questLogButton.clicked += () => OpenFullQuestLog();
        toggleTrackerButton.clicked += () => ToggleQuestTracker();
        showAllButton.clicked += () => OpenFullQuestLog();
        trackLocationButton.clicked += () => TrackSelectedQuest();
        abandonQuestButton.clicked += () => AbandonSelectedQuest();

        closePopupButton.clicked += () => CloseQuestDetails();
        trackButton.clicked += () => TrackSelectedQuest();
        navigateButton.clicked += () => NavigateToQuest();

        // Initially hide popup and notifications
        if (questDetailsPopup != null)
            questDetailsPopup.style.display = DisplayStyle.None;
        if (completionNotification != null)
            completionNotification.style.display = DisplayStyle.None;
        if (progressNotification != null)
            progressNotification.style.display = DisplayStyle.None;

        // Update tracker title with count
        UpdateTrackerTitle();

        isUIVisible = true;
    }

    private bool isTrackerMinimized = false;

    private void ToggleQuestTracker()
    {
        isTrackerMinimized = !isTrackerMinimized;

        if (isTrackerMinimized)
        {
            // Hide the quest list and actions, only show header
            if (activeQuestsList != null)
                activeQuestsList.style.display = DisplayStyle.None;
            if (quickActions != null)
                quickActions.style.display = DisplayStyle.None;
            if (noQuestsMessage != null)
                noQuestsMessage.style.display = DisplayStyle.None;

            // Change button text to show expand option
            if (toggleTrackerButton != null)
                toggleTrackerButton.text = "+";

            // Make tracker smaller
            if (questTracker != null)
            {
                questTracker.style.height = 40;
                questTracker.style.maxHeight = 40;
            }
        }
        else
        {
            // Show everything again
            if (activeQuestsList != null)
                activeQuestsList.style.display = DisplayStyle.Flex;
            if (quickActions != null)
                quickActions.style.display = DisplayStyle.Flex;

            // Show no quests message if needed
            var activeQuests = QuestManager.Instance?.GetActiveQuests();
            if (activeQuests == null || activeQuests.Count == 0)
            {
                if (noQuestsMessage != null)
                    noQuestsMessage.style.display = DisplayStyle.Flex;
            }

            // Change button text back
            if (toggleTrackerButton != null)
                toggleTrackerButton.text = "−";

            // Restore tracker size
            if (questTracker != null)
            {
                questTracker.style.height = StyleKeyword.Auto;
                questTracker.style.maxHeight = 350;
            }
        }
    }

    private void SubscribeToEvents()
    {
        Debug.Log("ActiveQuestUI: SubscribeToEvents called");

        if (QuestManager.Instance != null)
        {
            Debug.Log("ActiveQuestUI: QuestManager found, subscribing to events");
            QuestManager.Instance.OnQuestAccepted += HandleQuestAccepted;
            QuestManager.Instance.OnQuestCompleted += HandleQuestCompleted;
            QuestManager.Instance.OnQuestAbandoned += HandleQuestAbandoned;
            QuestManager.Instance.OnQuestFailed += HandleQuestFailed;
        }
        else
        {
            Debug.LogWarning("ActiveQuestUI: QuestManager.Instance is null during SubscribeToEvents!");
        }
    }

    private void OnDestroy()
    {
        // Unregister from ClickManager
        ClickBlockingHelper.UnregisterWithClickManager(this);

        // Unregister from QuestManager events
        if (QuestManager.Instance != null)
        {
            QuestManager.Instance.OnQuestAccepted -= HandleQuestAccepted;
            QuestManager.Instance.OnQuestCompleted -= HandleQuestCompleted;
            QuestManager.Instance.OnQuestAbandoned -= HandleQuestAbandoned;
            QuestManager.Instance.OnQuestFailed -= HandleQuestFailed;
        }
    }

    #region Quest List Management

    private void RefreshQuestList()
    {
        Debug.Log("ActiveQuestUI: RefreshQuestList called");
        ClearQuestList();

        if (QuestManager.Instance == null)
        {
            Debug.LogWarning("ActiveQuestUI: QuestManager.Instance is null");
            ShowNoQuestsMessage();
            return;
        }

        var activeQuests = QuestManager.Instance.GetActiveQuests();
        Debug.Log($"ActiveQuestUI: Found {activeQuests.Count} active quests");

        if (activeQuests.Count == 0)
        {
            Debug.Log("ActiveQuestUI: No active quests found, showing no quests message");
            ShowNoQuestsMessage();
            return;
        }

        Debug.Log("ActiveQuestUI: Creating quest entries");
        HideNoQuestsMessage();

        foreach (var quest in activeQuests)
        {
            Debug.Log($"ActiveQuestUI: Creating entry for quest: {quest.questData.questTitle}");
            CreateQuestEntry(quest);
        }

        UpdateTrackerTitle();
        UpdateQuickActions();
    }

    private void ClearQuestList()
    {
        questEntries.Clear();
        activeQuestsList?.Clear();
    }

    private void ShowNoQuestsMessage()
    {
        if (noQuestsMessage != null)
            noQuestsMessage.style.display = DisplayStyle.Flex;
        if (quickActions != null)
            quickActions.style.display = DisplayStyle.None;
    }

    private void HideNoQuestsMessage()
    {
        if (noQuestsMessage != null)
            noQuestsMessage.style.display = DisplayStyle.None;
        if (quickActions != null)
            quickActions.style.display = DisplayStyle.Flex;
    }

    private void CreateQuestEntry(ActiveQuest quest)
    {
        var entry = new VisualElement();
        entry.AddToClassList("quest-entry-compact");

        // Header with title and urgency
        var header = new VisualElement();
        header.AddToClassList("quest-compact-header");

        var title = new Label(quest.questData.questTitle);
        title.AddToClassList("quest-compact-title");

        var urgency = new VisualElement();
        urgency.AddToClassList("quest-compact-urgency");
        urgency.AddToClassList(GetUrgencyClass(quest.GetUrgencyLevel()));

        header.Add(title);
        header.Add(urgency);

        // Info row with progress and time
        var info = new VisualElement();
        info.AddToClassList("quest-compact-info");

        var progress = new Label($"{quest.GetCompletedObjectivesCount()}/{quest.questData.goals.Count} objectives");
        progress.AddToClassList("quest-compact-progress"); var timeRemaining = new Label(GetTimeRemainingText(quest));
        timeRemaining.AddToClassList("quest-compact-time");

        info.Add(progress);
        info.Add(timeRemaining);

        entry.Add(header);
        entry.Add(info);

        // Click handler
        entry.RegisterCallback<ClickEvent>(evt => SelectQuest(quest, entry));

        activeQuestsList.Add(entry);
        questEntries.Add(entry);
    }

    private string GetUrgencyClass(QuestUrgency urgency)
    {
        switch (urgency)
        {
            case QuestUrgency.Low: return "urgency-low";
            case QuestUrgency.Medium: return "urgency-medium";
            case QuestUrgency.High: return "urgency-high";
            case QuestUrgency.Critical: return "urgency-critical";
            default: return "urgency-low";
        }
    }

    private string GetTimeRemainingText(ActiveQuest quest)
    {
        if (quest.questData.timeLimit <= 0)
            return "No time limit";

        float remaining = quest.GetTimeRemaining();

        if (remaining <= 0)
            return "EXPIRED";

        if (remaining < 1f)
            return "< 1 hour";

        if (remaining < 24f)
            return $"{Mathf.CeilToInt(remaining)}h";

        return $"{Mathf.CeilToInt(remaining / 24f)}d";
    }

    private void UpdateTrackerTitle()
    {
        Debug.Log("UpdateTrackerTitle called");

        if (trackerTitle == null)
        {
            Debug.LogWarning("trackerTitle is null!");
            return;
        }

        int activeCount = QuestManager.Instance?.GetActiveQuests().Count ?? 0;
        string newTitle = $"Active Quests ({activeCount})";

        Debug.Log($"Setting tracker title to: '{newTitle}'");
        trackerTitle.text = newTitle;

        // Force update the display
        if (questTracker != null)
        {
            questTracker.style.display = DisplayStyle.Flex;
            Debug.Log("Ensured questTracker is visible");
        }
    }

    #endregion

    #region Selection and Actions

    private void SelectQuest(ActiveQuest quest, VisualElement entry)
    {
        // Deselect previous
        foreach (var questEntry in questEntries)
        {
            questEntry.RemoveFromClassList("selected");
        }

        // Select new
        entry.AddToClassList("selected");
        selectedQuest = quest;

        UpdateQuickActions();
    }

    private void UpdateQuickActions()
    {
        if (quickActions == null) return;

        bool hasSelection = selectedQuest != null;

        trackLocationButton?.SetEnabled(hasSelection);
        abandonQuestButton?.SetEnabled(hasSelection);
    }

    private void TrackSelectedQuest()
    {
        if (selectedQuest == null) return;

        // Focus camera on quest location
        var questMapMarkerManager = FindFirstObjectByType<QuestMapMarkerManager>();
        if (questMapMarkerManager != null)
        {
            questMapMarkerManager.FocusOnQuest(selectedQuest);
            Debug.Log($"Tracking quest: {selectedQuest.questData.questTitle}");
        }

        // Show quest details popup
        ShowQuestDetails(selectedQuest);
    }

    private void AbandonSelectedQuest()
    {
        if (selectedQuest == null) return;

        // Show confirmation dialog (simplified for now)
        if (QuestManager.Instance != null)
        {
            QuestManager.Instance.AbandonQuest(selectedQuest.questId);
        }
    }

    private void OpenFullQuestLog()
    {
        if (selectedQuest != null)
        {
            ShowQuestDetails(selectedQuest);
        }
        else
        {
            // Open the Adventures Guild UI or a quest log scene
            Debug.Log("Opening full quest log...");
        }
    }

    private void NavigateToQuest()
    {
        if (selectedQuest == null) return;

        // Set travel destination to quest location
        // var travelSystem = FindFirstObjectByType<TravelSystem>();
        // if (travelSystem != null)
        // {
        //     Vector2 questLocation = new Vector2(selectedQuest.questData.targetLocationX, selectedQuest.questData.targetLocationY);
        //     travelSystem.SetDestination(questLocation);
        //     Debug.Log($"Navigating to quest at {questLocation}");
        // }

        Vector2 questLocation = new Vector2(selectedQuest.questData.targetLocationX, selectedQuest.questData.targetLocationY);
        Debug.Log($"Navigating to quest at {questLocation}");
    }

    #endregion

    #region Quest Details Popup

    private void ShowQuestDetails(ActiveQuest quest)
    {
        if (questDetailsPopup == null) return;

        // Populate quest info
        PopulateQuestDetails(quest);

        // Show popup
        if (questDetailsPopup != null)
            questDetailsPopup.style.display = DisplayStyle.Flex;
    }

    private void CloseQuestDetails()
    {
        if (questDetailsPopup != null)
            questDetailsPopup.style.display = DisplayStyle.None;
    }


    private void PopulateQuestDetails(ActiveQuest quest)
    {
        if (popupTitle != null)
            popupTitle.text = quest.questData.questTitle;

        if (questInfo == null) return;

        questInfo.Clear();

        // Title and difficulty
        var title = new Label(quest.questData.questTitle);
        title.AddToClassList("quest-title");
        questInfo.Add(title);

        var difficulty = new Label(quest.questData.difficulty.ToString().ToUpper());
        difficulty.AddToClassList("quest-difficulty");
        difficulty.AddToClassList($"difficulty-{quest.questData.difficulty.ToString().ToLower()}");
        questInfo.Add(difficulty);

        // Status bar
        var status = new VisualElement();
        status.AddToClassList("quest-status");

        var timeLabel = new Label(GetDetailedTimeText(quest));
        timeLabel.AddToClassList("time-remaining");

        var locationLabel = new Label($"Location: {quest.questData.targetLocationName}");
        locationLabel.AddToClassList("quest-location");

        status.Add(timeLabel);
        status.Add(locationLabel);
        questInfo.Add(status);

        // Description
        var descSection = new VisualElement();
        descSection.AddToClassList("section");

        var descHeader = new Label("Description");
        descHeader.AddToClassList("section-header");
        descSection.Add(descHeader);

        var description = new Label(quest.questData.description);
        description.AddToClassList("quest-description");
        descSection.Add(description);

        questInfo.Add(descSection);

        // Objectives
        PopulateObjectives(quest);

        // Rewards
        PopulateRewards(quest);
    }

    private void PopulateObjectives(ActiveQuest quest)
    {
        if (objectivesList == null) return;

        objectivesList.Clear();

        var section = new VisualElement();
        section.AddToClassList("section");

        var header = new Label("Objectives");
        header.AddToClassList("section-header");
        section.Add(header);

        // Progress bar
        var progressContainer = new VisualElement();
        progressContainer.AddToClassList("progress-container");

        var progressBar = new VisualElement();
        progressBar.AddToClassList("progress-bar");

        var progressFill = new VisualElement();
        progressFill.AddToClassList("progress-fill");

        int completed = quest.GetCompletedObjectivesCount();
        int total = quest.questData.objectives.Count;
        float percentage = total > 0 ? (float)completed / total * 100f : 0f;

        progressFill.style.width = new Length(percentage, LengthUnit.Percent);
        progressBar.Add(progressFill);

        var progressText = new Label($"{completed}/{total}");
        progressText.AddToClassList("progress-text");

        progressContainer.Add(progressBar);
        progressContainer.Add(progressText);
        section.Add(progressContainer);

        // Objective list
        var objList = new VisualElement();
        objList.AddToClassList("objectives-list");

        for (int i = 0; i < quest.questData.objectives.Count; i++)
        {
            var objective = quest.questData.objectives[i];
            bool isCompleted = quest.GetObjectiveProgress(i) >= objective.targetAmount;

            var objItem = new VisualElement();
            objItem.AddToClassList("objective-item-popup");

            var status = new VisualElement();
            status.AddToClassList("objective-status-popup");
            if (isCompleted)
                status.AddToClassList("objective-completed-popup");

            var text = new Label(objective.description);
            text.AddToClassList("objective-text-popup");

            var progress = new Label($"{quest.GetObjectiveProgress(i)}/{objective.targetAmount}");
            progress.AddToClassList("objective-progress-popup");

            objItem.Add(status);
            objItem.Add(text);
            objItem.Add(progress);

            objList.Add(objItem);
        }

        section.Add(objList);
        objectivesList.Add(section);
    }

    private void PopulateRewards(ActiveQuest quest)
    {
        if (rewardsList == null) return;

        rewardsList.Clear();

        var section = new VisualElement();
        section.AddToClassList("section");

        var header = new Label("Rewards");
        header.AddToClassList("section-header");
        section.Add(header);

        var rewards = new VisualElement();
        rewards.AddToClassList("rewards-list");

        if (quest.questData.goldReward > 0)
        {
            var goldReward = new Label($"🪙 {quest.questData.goldReward} Gold");
            goldReward.AddToClassList("reward-item");
            rewards.Add(goldReward);
        }

        if (quest.questData.renownReward > 0)
        {
            var renownReward = new Label($"⭐ {quest.questData.renownReward} Renown");
            renownReward.AddToClassList("reward-item");
            rewards.Add(renownReward);
        }

        foreach (var item in quest.questData.itemRewards)
        {
            if (item != null)
            {
                var itemReward = new Label($"📦 {item}");
                itemReward.AddToClassList("reward-item");
                rewards.Add(itemReward);
            }
        }

        section.Add(rewards);
        rewardsList.Add(section);
    }

    private string GetDetailedTimeText(ActiveQuest quest)
    {
        if (quest.questData.timeLimit <= 0)
            return "No time limit";

        float remaining = quest.GetTimeRemaining();

        if (remaining <= 0)
            return "QUEST EXPIRED";

        if (remaining < 1f)
            return $"{Mathf.RoundToInt(remaining * 60f)} minutes remaining";

        if (remaining < 24f)
            return $"{Mathf.RoundToInt(remaining)} hours remaining";

        int days = Mathf.FloorToInt(remaining / 24f);
        int hours = Mathf.RoundToInt(remaining % 24f);

        return $"{days}d {hours}h remaining";
    }

    #endregion

    #region Event Handlers

    private void HandleQuestAccepted(ActiveQuest quest)
    {
        Debug.Log($"ActiveQuestUI: HandleQuestAccepted called for quest {quest.questData.questTitle}");
        RefreshQuestList();
    }

    private void HandleQuestCompleted(ActiveQuest quest, List<QuestReward> rewards)
    {
        Debug.Log($"ActiveQuestUI: HandleQuestCompleted called for quest {quest.questData.questTitle}");
        ShowCompletionNotification(quest, rewards);
        RefreshQuestList();
    }

    private void HandleQuestAbandoned(ActiveQuest quest)
    {
        Debug.Log($"ActiveQuestUI: HandleQuestAbandoned called for quest {quest.questData.questTitle}");
        if (selectedQuest?.questData == quest.questData)
            selectedQuest = null;

        RefreshQuestList();
    }

    private void HandleQuestFailed(ActiveQuest quest)
    {
        Debug.Log($"ActiveQuestUI: HandleQuestFailed called for quest {quest.questData.questTitle}");
        if (selectedQuest?.questData == quest.questData)
            selectedQuest = null;

        RefreshQuestList();
    }

    private void HandleQuestProgress(ActiveQuest quest, int objectiveIndex, int newProgress)
    {
        // Update the specific quest entry
        RefreshQuestList();

        // Show progress notification if objective completed
        if (quest.questData.objectives[objectiveIndex].targetAmount <= newProgress)
        {
            ShowProgressNotification(quest, objectiveIndex);
        }
    }

    #endregion

    #region Notifications

    private void ShowCompletionNotification(ActiveQuest quest, List<QuestReward> rewards)
    {
        if (completionNotification == null) return;

        var content = completionNotification.Q<VisualElement>("notification-content");
        if (content == null) return;

        content.Clear();

        var icon = new Label("✅");
        icon.AddToClassList("completion-icon");
        content.Add(icon);

        var title = new Label("Quest Completed!");
        title.AddToClassList("completion-title");
        content.Add(title);

        var questTitle = new Label(quest.questData.questTitle);
        questTitle.AddToClassList("completed-quest-title");
        content.Add(questTitle);

        var rewardsText = new Label("Rewards: " + GetRewardsText(rewards));
        rewardsText.AddToClassList("completion-rewards");
        content.Add(rewardsText);

        if (completionNotification != null)
            completionNotification.style.display = DisplayStyle.Flex;

        // Auto-hide after 5 seconds
        StartCoroutine(HideNotificationAfterDelay(completionNotification, 5f));
    }

    private void ShowProgressNotification(ActiveQuest quest, int objectiveIndex)
    {
        if (progressNotification == null) return;

        var content = progressNotification.Q<VisualElement>("progress-notification-content");
        if (content == null) return;

        content.Clear();

        var icon = new Label("🎯");
        icon.AddToClassList("progress-icon");
        content.Add(icon);

        var title = new Label("Objective Complete!");
        title.AddToClassList("progress-title");
        content.Add(title);

        var objective = new Label(quest.questData.objectives[objectiveIndex].description);
        objective.AddToClassList("completed-objective");
        content.Add(objective);

        if (progressNotification != null)
            progressNotification.style.display = DisplayStyle.Flex;

        // Auto-hide after 3 seconds
        StartCoroutine(HideNotificationAfterDelay(progressNotification, 3f));
    }

    private IEnumerator HideNotificationAfterDelay(VisualElement notification, float delay)
    {
        yield return new WaitForSeconds(delay);
        if (notification != null)
            notification.style.display = DisplayStyle.None;
    }

    private string GetRewardsText(List<QuestReward> rewards)
    {
        var rewardTexts = new List<string>();

        foreach (var reward in rewards)
        {
            switch (reward.type)
            {
                case QuestRewardType.Gold:
                    rewardTexts.Add($"{reward.amount} Gold");
                    break;
                case QuestRewardType.Renown:
                    rewardTexts.Add($"{reward.amount} Renown");
                    break;
                case QuestRewardType.Item:
                    if (reward.item != null)
                        rewardTexts.Add(reward.item.name);
                    break;
            }
        }

        return string.Join(", ", rewardTexts);
    }

    #endregion

    public bool IsBlockingClick(Vector2 screenPosition)
    {
        // Primary method: Check if we recently handled a UI click
        if (recentlyHandledClick)
        {
            Debug.Log("🚫 ActiveQuestUI: Blocking click due to recent UI interaction");
            return true;
        }

        // If UI is not visible, don't block anything
        if (!isUIVisible)
        {
            return false;
        }

        // Dynamic coordinate-based approach: Block clicks in the quest tracker area
        // This needs to account for the expanded quest panel when it shows more options

        float questPanelWidth = 320f;  // Approximate width of quest panel
        float questPanelHeight = 250f; // Larger height to cover expanded panel (was 120f)
        float questPanelX = 20f;       // Left edge
        float questPanelY = Screen.height - questPanelHeight - 20f; // Top edge (converted to screen coords)

        // Alternative: Try to get actual bounds from the quest tracker if available
        if (questTracker != null)
        {
            try
            {
                // Try to use the actual UI element bounds if possible
                var bounds = questTracker.worldBound;
                if (bounds.width > 0 && bounds.height > 0)
                {
                    // Convert UI bounds to screen coordinates
                    questPanelX = bounds.x;
                    questPanelY = Screen.height - bounds.y - bounds.height;
                    questPanelWidth = bounds.width;
                    questPanelHeight = bounds.height;

                    Debug.Log($"🔍 Using actual UI bounds: x={questPanelX}, y={questPanelY}, w={questPanelWidth}, h={questPanelHeight}");
                }
            }
            catch (System.Exception e)
            {
                Debug.LogWarning($"Failed to get UI bounds, using fallback: {e.Message}");
            }
        }

        bool inQuestArea = screenPosition.x >= questPanelX &&
                          screenPosition.x <= questPanelX + questPanelWidth &&
                          screenPosition.y >= questPanelY &&
                          screenPosition.y <= questPanelY + questPanelHeight;

        if (inQuestArea)
        {
            Debug.Log($"🛡️ ActiveQuestUI: Blocking click in quest area at {screenPosition} (quest area: {questPanelX}-{questPanelX + questPanelWidth}, {questPanelY}-{questPanelY + questPanelHeight})");
            return true;
        }

        // Don't block clicks outside the quest area
        return false;
    }

}
