using UnityEngine;

/// <summary>
/// Temporary fix to force settlement detection to work
/// This patches the coordinate conversion issue
/// </summary>
public class SettlementDetectionHotfix : MonoBehaviour
{
    [Header("Settlement Detection Hotfix")]
    [Tooltip("Force settlement detection to work by improving coordinate conversion")]
    public bool enableHotfix = true;

    private SettlementInteractionManager settlementManager;

    void Start()
    {
        settlementManager = FindFirstObjectByType<SettlementInteractionManager>();
        if (settlementManager != null && enableHotfix)
        {
            Debug.Log("[Hotfix] Settlement detection hotfix enabled");
        }
    }

    void Update()
    {
        if (!enableHotfix || settlementManager == null) return;

        // Check if we should manually trigger settlement detection
        var teamMarker = GameObject.Find("TeamMarker");
        if (teamMarker == null) return;

        Vector3 teamPos = teamMarker.transform.position;
        Vector2Int mapPos = new Vector2Int(
            Mathf.RoundToInt(teamPos.x),
            Mathf.RoundToInt(teamPos.z)
        );

        // Force check the exact coordinate and nearby coordinates
        var mapMaker = FindFirstObjectByType<MapMaker2>();
        if (mapMaker?.GetMapData() != null)
        {
            var mapData = mapMaker.GetMapData();

            // Check current position and all adjacent positions
            Settlement foundSettlement = null;

            for (int dx = -1; dx <= 1; dx++)
            {
                for (int dy = -1; dy <= 1; dy++)
                {
                    Vector2Int checkPos = new Vector2Int(mapPos.x + dx, mapPos.y + dy);
                    var settlement = mapData.GetSettlementAt(checkPos, 0.1f); // Very tight tolerance

                    if (settlement != null)
                    {
                        foundSettlement = settlement;
                        break;
                    }
                }
                if (foundSettlement != null) break;
            }

            // If we found a settlement but the manager doesn't detect it, force the detection
            var currentDetected = settlementManager.GetCurrentNearbySettlement();

            if (foundSettlement != null && currentDetected == null)
            {
                Debug.Log($"[Hotfix] Forcing settlement detection: {foundSettlement.name} at {foundSettlement.position}");

                // Force manual entry when E is pressed
                if (Input.GetKeyDown(KeyCode.E))
                {
                    Debug.Log($"[Hotfix] Manually entering settlement: {foundSettlement.name}");
                    settlementManager.EnterSettlement(foundSettlement);
                }
            }
        }
    }

    [ContextMenu("Force Settlement Detection Now")]
    public void ForceDetectionNow()
    {
        var teamMarker = GameObject.Find("TeamMarker");
        var mapMaker = FindFirstObjectByType<MapMaker2>();

        if (teamMarker == null || mapMaker?.GetMapData() == null)
        {
            Debug.LogError("[Hotfix] Missing components for detection");
            return;
        }

        Vector3 teamPos = teamMarker.transform.position;
        Vector2Int mapPos = new Vector2Int(
            Mathf.RoundToInt(teamPos.x),
            Mathf.RoundToInt(teamPos.z)
        );

        Debug.Log($"[Hotfix] Checking position {mapPos} (world {teamPos})");

        var mapData = mapMaker.GetMapData();
        var allSettlements = mapData.GetAllSettlements();

        foreach (var settlement in allSettlements)
        {
            float distance = Vector2Int.Distance(mapPos, settlement.position);
            Debug.Log($"[Hotfix] Settlement '{settlement.name}' at {settlement.position} - Distance: {distance:F2}");

            if (distance <= 1.5f)
            {
                Debug.Log($"[Hotfix] 🎯 FOUND NEARBY: {settlement.name}");

                if (settlementManager != null)
                {
                    Debug.Log($"[Hotfix] Manually entering settlement: {settlement.name}");
                    settlementManager.EnterSettlement(settlement);
                    return;
                }
            }
        }

        Debug.Log("[Hotfix] No settlement found within range");
    }

    void OnGUI()
    {
        if (!enableHotfix) return;

        GUILayout.BeginArea(new Rect(Screen.width - 300, 10, 280, 100));
        GUILayout.BeginVertical("box");

        GUILayout.Label("Settlement Detection Hotfix", new GUIStyle(GUI.skin.label) { fontSize = 12, fontStyle = FontStyle.Bold });

        if (GUILayout.Button("Force Enter Settlement"))
        {
            ForceDetectionNow();
        }

        var teamMarker = GameObject.Find("TeamMarker");
        if (teamMarker != null)
        {
            Vector3 pos = teamMarker.transform.position;
            GUILayout.Label($"Position: ({pos.x:F0}, {pos.z:F0})", new GUIStyle(GUI.skin.label) { fontSize = 10 });
        }

        GUILayout.EndVertical();
        GUILayout.EndArea();
    }
}
