using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// Global click manager that handles click propagation between UI elements and the game world.
/// UI components register themselves as click blockers to prevent map interaction when appropriate.
/// </summary>
public class ClickManager : MonoBehaviour
{
    private static ClickManager _instance;
    public static ClickManager Instance
    {
        get
        {
            if (_instance == null)
            {
                // Try to find existing instance first
                _instance = FindFirstObjectByType<ClickManager>();

                if (_instance == null)
                {
                    // Create a new ClickManager GameObject if none exists
                    GameObject clickManagerObj = new GameObject("ClickManager");
                    _instance = clickManagerObj.AddComponent<ClickManager>();
                    DontDestroyOnLoad(clickManagerObj);

                    Debug.Log("✅ ClickManager auto-created");
                }
            }
            return _instance;
        }
    }

    private readonly HashSet<IClickBlocker> clickBlockers = new HashSet<IClickBlocker>();

    [Header("Debug")]
    public bool showDebugLogs = false;

    void Awake()
    {
        if (_instance == null)
        {
            _instance = this;
            DontDestroyOnLoad(gameObject);

            if (showDebugLogs)
            {
                Debug.Log("✅ ClickManager instance created");
            }
        }
        else
        {
            if (showDebugLogs)
            {
                Debug.LogWarning("Multiple ClickManager instances found. Destroying this one.");
            }
            Destroy(gameObject);
        }
    }

    /// <summary>
    /// Registers a UI component that can block clicks.
    /// </summary>
    public void RegisterClickBlocker(IClickBlocker blocker)
    {
        if (blocker != null)
        {
            clickBlockers.Add(blocker);

            if (showDebugLogs)
            {
                Debug.Log($"📝 Registered click blocker: {blocker.GetType().Name}");
            }
        }
    }

    /// <summary>
    /// Unregisters a UI component.
    /// </summary>
    public void UnregisterClickBlocker(IClickBlocker blocker)
    {
        if (blocker != null)
        {
            clickBlockers.Remove(blocker);

            if (showDebugLogs)
            {
                Debug.Log($"❌ Unregistered click blocker: {blocker.GetType().Name}");
            }
        }
    }

    /// <summary>
    /// Checks if any registered UI component is blocking clicks at the given screen position.
    /// </summary>
    public bool IsClickBlocked(Vector2 screenPosition)
    {
        foreach (var blocker in clickBlockers)
        {
            if (blocker != null && blocker.IsBlockingClick(screenPosition))
            {
                if (showDebugLogs)
                {
                    Debug.Log($"🚫 Click blocked by: {blocker.GetType().Name} at position {screenPosition}");
                }
                return true;
            }
        }

        if (showDebugLogs)
        {
            Debug.Log($"✅ Click allowed at position {screenPosition} (checked {clickBlockers.Count} blockers)");
        }

        return false;
    }

    /// <summary>
    /// Gets the number of currently registered click blockers (for debugging)
    /// </summary>
    public int GetRegisteredBlockersCount()
    {
        return clickBlockers.Count;
    }

    /// <summary>
    /// Lists all registered click blockers (for debugging)
    /// </summary>
    public void ListRegisteredBlockers()
    {
        Debug.Log($"📋 Registered Click Blockers ({clickBlockers.Count}):");
        foreach (var blocker in clickBlockers)
        {
            Debug.Log($"   - {blocker?.GetType().Name ?? "NULL"}");
        }
    }
}
