using UnityEngine;

/// <summary>
/// Debug helper for the travel system - helps troubleshoot coordinate issues
/// </summary>
public class TravelSystemDebugger : MonoBehaviour
{
    [Header("Debug Settings")]
    public bool enableDebugOverlay = true;
    public bool showCoordinates = true;
    public bool showCameraInfo = true;
    public KeyCode toggleKey = KeyCode.F9;

    [Header("Visual Debug")]
    public Color guiTextColor = Color.yellow;
    public int fontSize = 16;

    private Camera mapCamera;
    private MapMaker2 mapMaker;
    private SimpleTeamPlacement teamPlacement;
    private TeamTravelSystem travelSystem;

    void Start()
    {
        mapCamera = Camera.main;
        mapMaker = FindFirstObjectByType<MapMaker2>();
        teamPlacement = FindFirstObjectByType<SimpleTeamPlacement>();
        travelSystem = FindFirstObjectByType<TeamTravelSystem>();
    }

    void Update()
    {
        if (Input.GetKeyDown(toggleKey))
        {
            enableDebugOverlay = !enableDebugOverlay;
            Debug.Log($"🔧 Travel System Debug Overlay: {(enableDebugOverlay ? "ENABLED" : "DISABLED")}");
        }

        // Log mouse clicks for debugging
        if (Input.GetMouseButtonDown(0))
        {
            LogMouseClickInfo();
        }
    }

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

        GUI.color = guiTextColor;
        GUIStyle style = new GUIStyle(GUI.skin.label);
        style.fontSize = fontSize;

        float yPos = 50f;
        float lineHeight = 25f;

        // Mouse position info
        if (showCoordinates)
        {
            Vector3 mousePos = Input.mousePosition;
            GUI.Label(new Rect(10, yPos, 400, lineHeight), $"Screen Mouse: {mousePos.x:F0}, {mousePos.y:F0}", style);
            yPos += lineHeight;

            if (mapCamera != null)
            {
                Vector3 worldPos = GetMouseWorldPosition();
                GUI.Label(new Rect(10, yPos, 400, lineHeight), $"World Mouse: {worldPos.x:F2}, {worldPos.y:F2}, {worldPos.z:F2}", style);
                yPos += lineHeight;

                Vector2Int tilePos = WorldToTilePosition(worldPos);
                GUI.Label(new Rect(10, yPos, 400, lineHeight), $"Tile Position: {tilePos.x}, {tilePos.y}", style);
                yPos += lineHeight;
            }
        }

        // Camera info
        if (showCameraInfo && mapCamera != null)
        {
            GUI.Label(new Rect(10, yPos, 400, lineHeight), $"Camera Pos: {mapCamera.transform.position.x:F1}, {mapCamera.transform.position.y:F1}, {mapCamera.transform.position.z:F1}", style);
            yPos += lineHeight;
            GUI.Label(new Rect(10, yPos, 400, lineHeight), $"Camera Size: {mapCamera.orthographicSize:F1}", style);
            yPos += lineHeight;
        }

        // System status
        yPos += lineHeight;
        GUI.Label(new Rect(10, yPos, 400, lineHeight), "=== SYSTEM STATUS ===", style);
        yPos += lineHeight;

        bool mapMakerOK = mapMaker != null;
        bool teamPlacementOK = teamPlacement != null && teamPlacement.IsTeamPlaced();
        bool travelSystemOK = travelSystem != null;

        GUI.color = mapMakerOK ? Color.green : Color.red;
        GUI.Label(new Rect(10, yPos, 400, lineHeight), $"MapMaker2: {(mapMakerOK ? "✅ OK" : "❌ Missing")}", style);
        yPos += lineHeight;

        GUI.color = teamPlacementOK ? Color.green : Color.red;
        GUI.Label(new Rect(10, yPos, 400, lineHeight), $"Team Placement: {(teamPlacementOK ? "✅ OK" : "❌ Missing/Not Placed")}", style);
        yPos += lineHeight;

        GUI.color = travelSystemOK ? Color.green : Color.red;
        GUI.Label(new Rect(10, yPos, 400, lineHeight), $"Travel System: {(travelSystemOK ? "✅ OK" : "❌ Missing")}", style);
        yPos += lineHeight;

        if (teamPlacementOK)
        {
            GUI.color = Color.cyan;
            Vector2Int teamPos = teamPlacement.GetTeamPosition();
            GUI.Label(new Rect(10, yPos, 400, lineHeight), $"Team Position: {teamPos.x}, {teamPos.y}", style);
            yPos += lineHeight;
        }

        if (mapMakerOK && mapMaker.GetMapData() != null)
        {
            GUI.color = Color.cyan;
            var mapData = mapMaker.GetMapData();
            GUI.Label(new Rect(10, yPos, 400, lineHeight), $"Map Size: {mapData.Width}x{mapData.Height}", style);
            yPos += lineHeight;

            float tileSize = mapMaker.mapVisualizer?.tileSize ?? 1f;
            GUI.Label(new Rect(10, yPos, 400, lineHeight), $"Tile Size: {tileSize}", style);
            yPos += lineHeight;
        }

        GUI.color = Color.white;
    }

    private void LogMouseClickInfo()
    {
        Debug.Log("=== MOUSE CLICK DEBUG ===");
        Debug.Log($"Screen Position: {Input.mousePosition}");

        if (mapCamera != null)
        {
            Vector3 worldPos = GetMouseWorldPosition();
            Debug.Log($"World Position: {worldPos}");

            Vector2Int tilePos = WorldToTilePosition(worldPos);
            Debug.Log($"Tile Position: {tilePos}");

            if (mapMaker?.GetMapData() != null)
            {
                var mapData = mapMaker.GetMapData();
                bool isValid = mapData.IsValidPosition(tilePos.x, tilePos.y);
                Debug.Log($"Valid Tile: {isValid}");

                if (isValid)
                {
                    var tile = mapData.GetTile(tilePos.x, tilePos.y);
                    Debug.Log($"Tile Info: {tile.terrainType}, {tile.featureType}");
                }
            }
        }
        else
        {
            Debug.LogWarning("No camera found for world position calculation");
        }

        Debug.Log("========================");
    }

    private Vector3 GetMouseWorldPosition()
    {
        if (mapCamera == null) return Vector3.zero;

        Ray ray = mapCamera.ScreenPointToRay(Input.mousePosition);

        // Try raycast first
        if (Physics.Raycast(ray, out RaycastHit hit, 1000f))
        {
            return hit.point;
        }

        // Fallback: use camera plane projection at Z=0 (map level)
        Plane mapPlane = new Plane(Vector3.back, Vector3.zero);
        if (mapPlane.Raycast(ray, out float distance))
        {
            return ray.GetPoint(distance);
        }

        return Vector3.zero;
    }

    private Vector2Int WorldToTilePosition(Vector3 worldPos)
    {
        float tileSize = mapMaker?.mapVisualizer?.tileSize ?? 1f;
        return new Vector2Int(
            Mathf.RoundToInt(worldPos.x / tileSize),
            Mathf.RoundToInt(worldPos.y / tileSize)
        );
    }
}
