using UnityEngine;
using System.Collections;

/// <summary>
/// MinimapMarkerManager - Automatically adds MinimapMarker components to all characters.
/// Works in BOTH Cash System mode AND Practice mode.
/// Attach to a manager object in the scene or it will be created automatically.
/// </summary>
public class MinimapMarkerManager : MonoBehaviour
{
    [Header("Settings")]
    [SerializeField] private bool autoSetupOnStart = true;
    [SerializeField] private float refreshInterval = 2f;
    
    private static MinimapMarkerManager instance;
    public static MinimapMarkerManager Instance => instance;
    
    private void Awake()
    {
        if (instance != null && instance != this)
        {
            Destroy(gameObject);
            return;
        }
        instance = this;
    }
    
    private void Start()
    {
        // REMOVED: Cash System only check - now works in ALL modes
        // This allows minimap markers in Practice mode too
        
        // Configure Main Camera to NOT render minimap layers
        ConfigureMainCamera();
        
        if (autoSetupOnStart)
        {
            StartCoroutine(SetupMarkersDelayed());
        }
        
        Debug.Log("[MinimapMarkerManager] Initialized - works in all game modes");
    }
    
    /// <summary>
    /// Configure Main Camera to exclude minimap marker layers
    /// </summary>
    private void ConfigureMainCamera()
    {
        Camera mainCam = Camera.main;
        if (mainCam == null) return;
        
        int minimapLayer = LayerMask.NameToLayer("Minimap");
        
        if (minimapLayer >= 0)
        {
            // Remove Minimap layer from main camera culling mask
            mainCam.cullingMask &= ~(1 << minimapLayer);
            Debug.Log($"[MinimapMarkerManager] Excluded 'Minimap' layer from Main Camera");
        }
        else
        {
            // Remove layer 31 (fallback) from main camera culling mask  
            mainCam.cullingMask &= ~(1 << 31);
            Debug.Log("[MinimapMarkerManager] Excluded layer 31 (fallback) from Main Camera");
        }
    }

    
    private IEnumerator SetupMarkersDelayed()
    {
        // Wait for characters to spawn
        yield return new WaitForSeconds(1.5f);
        
        SetupAllMarkers();
        
        // Periodic refresh for newly spawned characters
        while (enabled)
        {
            yield return new WaitForSeconds(refreshInterval);
            RefreshMarkers();
        }
    }
    
    /// <summary>
    /// Add MinimapMarker to all characters that don't have one
    /// </summary>
    public void SetupAllMarkers()
    {
        // Find all team members (characters)
        TeamMember[] allTeamMembers = FindObjectsOfType<TeamMember>();
        foreach (var member in allTeamMembers)
        {
            AddMarkerIfMissing(member.gameObject);
        }
        
        // Find all characters with HealthNew (covers AI enemies too)
        HealthNew[] allCharacters = FindObjectsOfType<HealthNew>();
        foreach (var character in allCharacters)
        {
            AddMarkerIfMissing(character.gameObject);
        }
        
        // Find all CashBags and add object markers (only relevant in Cash System)
        CashBag[] allCashBags = FindObjectsOfType<CashBag>();
        foreach (var cashBag in allCashBags)
        {
            AddObjectMarkerIfMissing(cashBag.gameObject);
        }
        
        // Find all TeamVaults and add object markers
        TeamVault[] allVaults = FindObjectsOfType<TeamVault>();
        foreach (var vault in allVaults)
        {
            AddObjectMarkerIfMissing(vault.gameObject);
        }
        
        Debug.Log($"[MinimapMarkerManager] Setup markers: {allTeamMembers.Length} characters, " +
            $"{allCashBags.Length} cashbags, {allVaults.Length} vaults");
    }
    
    /// <summary>
    /// Check for new characters and objects and add markers
    /// </summary>
    public void RefreshMarkers()
    {
        // Only add markers to NEW objects that don't have them yet
        // The "IfMissing" check prevents duplicates
        TeamMember[] allTeamMembers = FindObjectsOfType<TeamMember>();
        foreach (var member in allTeamMembers)
        {
            AddMarkerIfMissing(member.gameObject);
        }
        
        // NOTE: We intentionally skip HealthNew scan to avoid double-adding
        // to characters that already got a marker via TeamMember above.
        
        // Skip CashBag/Vault refresh — they get their marker once in SetupAllMarkers
        // and the component stays on the prefab/instance. Re-scanning caused duplicates.
        
        // Refresh colors on all markers
        MinimapMarker.RefreshAllMarkers();
    }
    
    private void AddObjectMarkerIfMissing(GameObject obj)
    {
        if (obj.GetComponent<MinimapObjectMarker>() == null)
        {
            obj.AddComponent<MinimapObjectMarker>();
            Debug.Log($"[MinimapMarkerManager] Added MinimapObjectMarker to {obj.name}");
        }
    }

    private void AddMarkerIfMissing(GameObject character)
    {
        if (character.GetComponent<MinimapMarker>() == null)
        {
            character.AddComponent<MinimapMarker>();
            Debug.Log($"[MinimapMarkerManager] Added MinimapMarker to {character.name}");
        }
    }
    
    /// <summary>
    /// Manually add marker to a specific character
    /// </summary>
    public void AddMarker(GameObject character)
    {
        AddMarkerIfMissing(character);
    }
    
    /// <summary>
    /// Static helper to ensure manager exists in scene
    /// </summary>
    public static void EnsureExists()
    {
        if (instance == null)
        {
            GameObject managerObj = new GameObject("MinimapMarkerManager");
            managerObj.AddComponent<MinimapMarkerManager>();
            Debug.Log("[MinimapMarkerManager] Created MinimapMarkerManager automatically");
        }
    }
}
