using UnityEngine;
using System.Collections.Generic;

public class MapMaker2 : MonoBehaviour
{
    [Header("Map Settings")]
    public int initialMapSize = 150;
    public int expansionSize = 50;
    public float playerDistanceThreshold = 20f;

    [Header("Simple Mode")]
    [Tooltip("Use simple static map generation (no exploration/expansion)")]
    public bool useSimpleMode = true;

    [Header("Exploration Settings")]
    [Tooltip("Use exploration system instead of expansion")]
    public bool useExplorationSystem = true;

    public void SetMapData(MapData newMapData)
    {
        mapData = newMapData;
        Debug.Log($"📊 Map data updated to size: {mapData.Width}x{mapData.Height}");

        // Update the visualization
        if (mapVisualizer != null)
        {
            mapVisualizer.VisualizeMap(mapData);
            Debug.Log("🗺️ Map visualization updated");
        }
        else
        {
            Debug.LogWarning("⚠️ MapVisualizer is null, cannot update visualization");
        }
    }

    public MapData GetMapData()
    {
        return mapData;
    }

    [Header("Exploration Settings")]
    public int explorationMapSize = 300;
    public int explorationInitialVisible = 80;

    [Header("Expansion Settings")]
    [Tooltip("Cooldown time between map expansions in seconds")]
    public float expansionCooldown = 5f;
    [Tooltip("Chance for terrain to continue from existing edge (0-1)")]
    [Range(0f, 1f)]
    public float terrainContinuityChance = 0.7f;

    [Header("Generation Settings")]
    public int seed = 12345;

    [Header("Visualization")]
    public MapVisualizer mapVisualizer;

    private MapData mapData;
    private TerrainGenerator terrainGenerator;
    private FeatureGenerator featureGenerator;
    private ExpansionManager expansionManager;
    private ExplorationManager explorationManager;
    private Transform player;
    private float lastExpansionTime = 0f;

    void Start()
    {
        Debug.Log($"🚀 MapMaker2 starting - useSimpleMode: {useSimpleMode}, useExplorationSystem: {useExplorationSystem}");
        InitializeMap();

        if (useSimpleMode)
        {
            Debug.Log("🎮 Starting with Simple Mode - Full map generation with team marker placement");
            GenerateCompleteMapWithTeamMarker();
        }
        else if (useExplorationSystem)
        {
            Debug.Log("🔍 Starting with Exploration System");
            InitializeExplorationSystem();
        }
        else
        {
            Debug.Log("📏 Starting with Expansion System");
            GenerateInitialMap();
        }
    }
    void Update()
    {
        // In simple mode, no expansion or exploration updates needed
        if (useSimpleMode)
        {
            // Only handle finding the player reference if missing
            if (player == null)
            {
                GameObject teamMarker = GameObject.Find("TeamMarker");
                if (teamMarker != null)
                {
                    player = teamMarker.transform;
                }
            }
            return;
        }

        // Only handle finding the player reference, not continuous exploration checks
        if (player == null)
        {
            // Debug log every few seconds to show player reference status
            if (Time.time % 3f < Time.deltaTime)
            {
                Debug.LogWarning($"🚫 MapMaker2 Update: Player reference is null! useExplorationSystem: {useExplorationSystem}");

                // Try to find TeamMarker if not found
                GameObject teamMarker = GameObject.Find("TeamMarker");
                if (teamMarker != null)
                {
                    Debug.Log($"🎯 Found TeamMarker at {teamMarker.transform.position}, setting as player reference");
                    player = teamMarker.transform;
                }
            }
        }
        else if (!useExplorationSystem)
        {
            // Only run expansion checks for the old system
            CheckForExpansion();
        }
        // Exploration system is now event-driven, no Update checks needed!
    }

    private void InitializeMap()
    {
        Random.InitState(seed);

        mapData = new MapData(initialMapSize, initialMapSize);
        terrainGenerator = new TerrainGenerator();
        featureGenerator = new FeatureGenerator();
        expansionManager = new ExpansionManager(this);
        explorationManager = new ExplorationManager(this);

        // Find player object - try multiple approaches
        GameObject playerObj = GameObject.FindGameObjectWithTag("Player");

        // If no "Player" tag found, try finding by name patterns
        if (playerObj == null)
        {
            // Try common player names
            string[] playerNames = { "TeamMarker", "Player", "PlayerCharacter", "Team", "MainCharacter" };
            foreach (string name in playerNames)
            {
                playerObj = GameObject.Find(name);
                if (playerObj != null)
                {
                    Debug.LogWarning($"Found player object by name '{name}' but it doesn't have 'Player' tag. Consider adding the tag.");
                    break;
                }
            }
        }

        if (playerObj != null)
        {
            player = playerObj.transform;
            Debug.Log($"Player found: {playerObj.name} at position {player.position}");
        }
        else
        {
            Debug.LogWarning("No player object found! Trying to find any object that might be the player...");
            Debug.Log("Available GameObjects:");
            GameObject[] allObjects = FindObjectsByType<GameObject>(FindObjectsSortMode.None);
            foreach (GameObject obj in allObjects)
            {
                Debug.Log($"- {obj.name} (Tag: {obj.tag})");
            }
        }

        // Initialize visualizer if not set
        if (mapVisualizer == null)
            mapVisualizer = GetComponent<MapVisualizer>();
    }

    private void GenerateInitialMap()
    {
        // Generate base terrain
        terrainGenerator.GenerateTerrain(mapData);

        // Generate features
        featureGenerator.GenerateFeatures(mapData);

        // Visualize the map
        VisualizeMap();
    }

    /// <summary>
    /// Generate complete map with team marker placement - Simple Mode
    /// </summary>
    private void GenerateCompleteMapWithTeamMarker()
    {
        Debug.Log("🗺️ Generating complete map with beautiful terrain...");

        // Generate the full beautiful map using original generators
        terrainGenerator.GenerateTerrain(mapData);
        featureGenerator.GenerateFeatures(mapData);

        Debug.Log("🎯 Placing team marker on a settlement...");

        // Find a good settlement for team marker placement
        Vector2Int? settlementPos = FindBestSettlementForTeamMarker();

        if (settlementPos.HasValue)
        {
            // PlaceTeamMarkerAt(settlementPos.Value);
            Debug.Log($"✅ Team marker placed at settlement: {settlementPos.Value}");
        }
        else
        {
            // Fallback to center if no settlements found
            Vector2Int centerPos = new Vector2Int(mapData.Width / 2, mapData.Height / 2);
            // PlaceTeamMarkerAt(centerPos);
            Debug.LogWarning($"⚠️ No settlements found, placed team marker at center: {centerPos}");
        }

        // Visualize the map
        VisualizeMap();

        Debug.Log("🎮 Simple mode map generation complete!");
    }

    /// <summary>
    /// Find the best settlement position for team marker placement
    /// </summary>
    private Vector2Int? FindBestSettlementForTeamMarker()
    {
        List<Vector2Int> settlements = new List<Vector2Int>();

        // Find all towns and villages
        for (int x = 0; x < mapData.Width; x++)
        {
            for (int y = 0; y < mapData.Height; y++)
            {
                MapTile tile = mapData.GetTile(x, y);
                if (tile != null && (tile.featureType == FeatureType.Town || tile.featureType == FeatureType.Village))
                {
                    settlements.Add(new Vector2Int(x, y));
                }
            }
        }

        if (settlements.Count == 0) return null;

        // Prefer towns over villages, and those closer to center
        Vector2 center = new Vector2(mapData.Width / 2f, mapData.Height / 2f);
        Vector2Int bestSettlement = settlements[0];
        float bestScore = float.MinValue;

        foreach (Vector2Int settlement in settlements)
        {
            MapTile tile = mapData.GetTile(settlement.x, settlement.y);
            float score = 0;

            // Prefer towns (higher score)
            if (tile.featureType == FeatureType.Town) score += 100;
            else score += 50; // Village

            // Prefer locations closer to center (but not exactly center)
            float distanceToCenter = Vector2.Distance(settlement, center);
            score += Mathf.Max(0, 50 - distanceToCenter); // Closer to center = higher score

            if (score > bestScore)
            {
                bestScore = score;
                bestSettlement = settlement;
            }
        }

        Debug.Log($"🏛️ Found {settlements.Count} settlements, selected {mapData.GetTile(bestSettlement.x, bestSettlement.y).featureType} at {bestSettlement}");
        return bestSettlement;
    }

    /// <summary>
    /// Place team marker at specified map coordinates
    /// </summary>
    private void PlaceTeamMarkerAt(Vector2Int mapPos)
    {
        // Remove existing team marker
        GameObject existingMarker = GameObject.Find("TeamMarker");
        if (existingMarker != null)
        {
            DestroyImmediate(existingMarker);
            Debug.Log("🗑️ Removed existing team marker");
        }

        // Create new team marker
        GameObject teamMarker = new GameObject("TeamMarkerMapMaker2");

        // Position it correctly in world space
        teamMarker.transform.position = new Vector3(mapPos.x, 0.5f, mapPos.y);

        // Add visual representation
        GameObject visualMarker = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        visualMarker.transform.SetParent(teamMarker.transform);
        visualMarker.transform.localPosition = Vector3.zero;
        visualMarker.transform.localScale = Vector3.one * 0.8f;

        // Make it green and distinctive
        Renderer renderer = visualMarker.GetComponent<Renderer>();
        if (renderer != null)
        {
            renderer.material.color = Color.green;
        }

        // Add a tag for easy finding
        teamMarker.tag = "Player";

        Debug.Log($"📍 Team marker created at world position: {teamMarker.transform.position} (map {mapPos})");

        // Update player reference
        player = teamMarker.transform;
    }

    private void CheckForExpansion()
    {
        // Check if mapVisualizer is available and has valid tileSize
        if (mapVisualizer == null)
        {
            Debug.LogWarning("MapVisualizer is null! Cannot check for expansion.");
            return;
        }

        float tileSize = mapVisualizer.tileSize;
        if (tileSize <= 0)
        {
            Debug.LogWarning($"Invalid tile size: {tileSize}. Using default value of 1.");
            tileSize = 1f;
        }

        // Debug player position
        Vector2 playerPos = new Vector2(player.position.x / tileSize, player.position.z / tileSize);

        // Debug log every few seconds
        if (Time.time % 2f < Time.deltaTime) // Log every 2 seconds
        {
            Debug.Log($"Player world position: {player.position}");
            Debug.Log($"Player tile position: {playerPos} (using tileSize: {tileSize})");
            Debug.Log($"Map size: {mapData.Width}x{mapData.Height}");
            Debug.Log($"Distance to edges - Left: {playerPos.x:F1}, Right: {(mapData.Width - playerPos.x):F1}, Top: {(mapData.Height - playerPos.y):F1}, Bottom: {playerPos.y:F1}");
            Debug.Log($"Expansion threshold: {playerDistanceThreshold}");
        }

        // Check cooldown to prevent rapid expansions
        if (Time.time - lastExpansionTime < expansionCooldown)
            return;

        if (expansionManager.ShouldExpand(playerPos, mapData))
        {
            Debug.Log($"Expansion triggered! Player position: {playerPos}");
            ExpandMap(playerPos);
        }
    }

    private void ExpandMap(Vector2 playerPos)
    {
        lastExpansionTime = Time.time;

        Debug.Log("Expanding map due to player proximity to edge...");
        expansionManager.ExpandMap(mapData, playerPos, expansionSize);
        VisualizeMap(); // Update visualization
    }

    private void VisualizeMap()
    {
        if (mapVisualizer != null)
        {
            mapVisualizer.VisualizeMap(mapData);
        }

        Debug.Log($"Map generated with size: {mapData.Width}x{mapData.Height} using sprite-based tiles rotated for top-down view");
        Debug.Log($"Towns: {mapData.GetTowns().Count}, Villages: {mapData.GetVillages().Count}");
    }

    public TerrainGenerator GetTerrainGenerator() => terrainGenerator;
    public FeatureGenerator GetFeatureGenerator() => featureGenerator;
    public ExplorationManager GetExplorationManager() => explorationManager;

    // Public method to manually set player reference if automatic detection fails
    public void SetPlayer(Transform playerTransform)
    {
        player = playerTransform;
        Debug.Log($"Player manually set to: {player.name}");
    }

    /// <summary>
    /// Enable Simple Mode - Beautiful map generation without exploration/expansion
    /// </summary>
    [ContextMenu("🎮 Enable Simple Mode (Beautiful Map + Team Marker)")]
    public void EnableSimpleMode()
    {
        Debug.Log("🎮 Switching to Simple Mode...");

        useSimpleMode = true;
        useExplorationSystem = false;

        // Clear existing map visualization
        if (mapVisualizer != null)
            mapVisualizer.ClearAllTiles();

        // Regenerate with simple mode
        mapData = new MapData(initialMapSize, initialMapSize);
        GenerateCompleteMapWithTeamMarker();

        Debug.Log("✅ Simple Mode enabled - Beautiful map with team marker placement!");
    }

    // For debugging - regenerate map
    [ContextMenu("Regenerate Map")]
    public void RegenerateMap()
    {
        if (mapVisualizer != null)
            mapVisualizer.ClearAllTiles();

        // Preserve current map size instead of resetting to initial size
        int currentWidth = mapData != null ? mapData.Width : initialMapSize;
        int currentHeight = mapData != null ? mapData.Height : initialMapSize;

        Debug.Log($"Regenerating map with current size: {currentWidth}x{currentHeight}");

        Random.InitState(seed);
        mapData = new MapData(currentWidth, currentHeight);
        terrainGenerator = new TerrainGenerator();
        featureGenerator = new FeatureGenerator();

        GenerateInitialMap();
    }

    // For debugging - reset to original size
    [ContextMenu("Reset to Original Size")]
    public void ResetToOriginalSize()
    {
        if (mapVisualizer != null)
            mapVisualizer.ClearAllTiles();

        Debug.Log($"Resetting map to original size: {initialMapSize}x{initialMapSize}");
        InitializeMap();
        GenerateInitialMap();
    }

    // For debugging - force map expansion
    [ContextMenu("Force Map Expansion")]
    public void ForceExpansion()
    {
        Vector2 playerPos;

        if (player != null)
        {
            float tileSize = mapVisualizer != null && mapVisualizer.tileSize > 0 ? mapVisualizer.tileSize : 1f;
            playerPos = new Vector2(player.position.x / tileSize, player.position.z / tileSize);
        }
        else
        {
            // If no player, expand from center-right edge to test the system
            playerPos = new Vector2(mapData.Width - 10, mapData.Height / 2);
            Debug.LogWarning("No player found, using test position for forced expansion");
        }

        lastExpansionTime = 0f; // Reset cooldown
        Debug.Log($"Forcing expansion from position: {playerPos}");
        ExpandMap(playerPos);
    }

    // For debugging - manually set TeamMarker as player
    [ContextMenu("Set TeamMarker as Player")]
    public void SetTeamMarkerAsPlayer()
    {
        GameObject teamMarker = GameObject.Find("TeamMarker");
        if (teamMarker != null)
        {
            SetPlayer(teamMarker.transform);
            Debug.Log("TeamMarker set as player successfully!");
        }
        else
        {
            Debug.LogError("TeamMarker object not found!");
        }
    }

    // === Exploration System Methods ===

    private void InitializeExplorationSystem()
    {
        Debug.Log("🔍 Initializing Exploration System...");

        if (explorationManager == null)
        {
            Debug.LogError("❌ ExplorationManager is null! Cannot initialize exploration system.");
            return;
        }

        explorationManager.fullMapWidth = explorationMapSize;
        explorationManager.fullMapHeight = explorationMapSize;
        explorationManager.initialVisibleSize = explorationInitialVisible;
        explorationManager.InitializeExploration();

        Debug.Log("✅ Exploration System initialization complete");
    }

    private void ExploreNewAreas(Vector2 playerPos)
    {
        lastExpansionTime = Time.time;

        Debug.Log("🌍 Exploring new areas due to team movement...");
        explorationManager.ExploreNewAreas(playerPos, mapData);
        VisualizeMap(); // Update visualization
    }

    // === Public Methods for Event-Driven Exploration ===

    /// <summary>
    /// Check for exploration when team position changes (event-driven)
    /// </summary>
    public void OnTeamPositionChanged(Vector2Int newPosition)
    {
        if (!useExplorationSystem || explorationManager == null)
            return;

        // Optimization: Only check if team moved a significant distance or cooldown passed
        if (Time.time - lastExpansionTime < expansionCooldown)
            return;

        // Convert tile position to world position for exploration system
        Vector2 worldPos = new Vector2(newPosition.x, newPosition.y);

        Debug.Log($"🚶 Team moved to {newPosition} - checking for exploration...");

        if (explorationManager.ShouldExplore(worldPos, mapData))
        {
            Debug.Log($"🔍 Exploration triggered by team movement to {newPosition}!");
            ExploreNewAreas(worldPos);
        }
    }

    // === Methods needed by ExplorationManager ===

    public void GenerateCompleteMap(MapData targetMapData)
    {
        // Generate base terrain
        terrainGenerator.GenerateTerrain(targetMapData);

        // Generate features
        featureGenerator.GenerateFeatures(targetMapData);

        Debug.Log($"✅ Complete map generated: {targetMapData.Width}x{targetMapData.Height}");
    }

    [ContextMenu("Enable Exploration System")]
    public void EnableExplorationSystem()
    {
        useExplorationSystem = true;
        Debug.Log("🔍 Exploration system enabled! Restart the scene to take effect.");
    }

    [ContextMenu("Test Exploration Now")]
    public void TestExplorationNow()
    {
        if (!useExplorationSystem)
        {
            Debug.LogWarning("⚠️ Exploration system is not enabled! Enable it first.");
            return;
        }

        // Debug player detection
        Debug.Log($"🔍 Player object: {(player != null ? player.name : "NULL")}");
        Debug.Log($"🔍 ExplorationManager: {(explorationManager != null ? "EXISTS" : "NULL")}");

        if (player == null)
        {
            // Try to find player again
            GameObject playerObj = GameObject.FindGameObjectWithTag("Player");
            if (playerObj == null)
            {
                playerObj = GameObject.Find("TeamMarker");
            }

            if (playerObj != null)
            {
                player = playerObj.transform;
                Debug.Log($"✅ Found player: {playerObj.name}");
            }
            else
            {
                Debug.LogError("❌ Cannot find player object! Make sure TeamMarker has 'Player' tag or is named 'TeamMarker'");
                return;
            }
        }

        if (explorationManager == null)
        {
            Debug.LogError("❌ ExplorationManager is null! This should be created in InitializeMap()");
            return;
        }

        float tileSize = mapVisualizer != null && mapVisualizer.tileSize > 0 ? mapVisualizer.tileSize : 1f;
        Vector2 playerPos = new Vector2(player.position.x / tileSize, player.position.z / tileSize);

        Debug.Log($"🧪 MANUAL EXPLORATION TEST");
        Debug.Log($"Player world position: {player.position}");
        Debug.Log($"Player tile position: {playerPos}");
        Debug.Log($"Current map size: {mapData.Width}x{mapData.Height}");
        Debug.Log($"Tile size: {tileSize}");

        // Force exploration regardless of cooldown
        lastExpansionTime = 0f;
        ExploreNewAreas(playerPos);
    }

    [ContextMenu("DEBUG: Show Full 300x300 Map")]
    public void ShowFullMap()
    {
        if (!useExplorationSystem || explorationManager == null)
        {
            Debug.LogError("❌ Exploration system not enabled or null!");
            return;
        }

        explorationManager.ShowFullMap();
    }

    [ContextMenu("DEBUG: Show Exploration State")]
    public void DebugExplorationState()
    {
        if (!useExplorationSystem || explorationManager == null)
        {
            Debug.LogError("❌ Exploration system not enabled or null!");
            return;
        }

        if (player == null)
        {
            GameObject teamMarker = GameObject.Find("TeamMarker");
            if (teamMarker != null) player = teamMarker.transform;
        }

        if (player == null)
        {
            Debug.LogError("❌ No player/team marker found!");
            return;
        }

        float tileSize = mapVisualizer != null && mapVisualizer.tileSize > 0 ? mapVisualizer.tileSize : 1f;
        Vector2 playerPos = new Vector2(player.position.x / tileSize, player.position.z / tileSize);

        explorationManager.DebugExplorationState(playerPos, mapData);
    }

    [ContextMenu("Disable Exploration System")]
    public void DisableExplorationSystem()
    {
        useExplorationSystem = false;
        Debug.Log("📏 Expansion system enabled! Restart the scene to take effect.");
    }

    [ContextMenu("PERF: Toggle Performance Mode")]
    public void TogglePerformanceMode()
    {
        if (explorationManager != null)
        {
            explorationManager.TogglePerformanceMode();
        }
        else
        {
            Debug.LogError("❌ Exploration manager not available!");
        }
    }

    [ContextMenu("PERF: Test 500x500 Map")]
    public void TestLargeMap500()
    {
        if (explorationManager != null)
        {
            explorationManager.SetMapSize(500, 500);
            Debug.Log("🗺️ Testing 500x500 map - will use LOD level 4 for performance");
        }
        else
        {
            Debug.LogError("❌ Exploration manager not available!");
        }
    }

    [ContextMenu("PERF: Test 1000x1000 Map")]
    public void TestMassiveMap1000()
    {
        if (explorationManager != null)
        {
            explorationManager.SetMapSize(1000, 1000);
            Debug.Log("🗺️ Testing 1000x1000 map - maximum LOD will be applied");
        }
        else
        {
            Debug.LogError("❌ Exploration manager not available!");
        }
    }

    [ContextMenu("PERF: Reset to 300x300")]
    public void ResetToStandardSize()
    {
        if (explorationManager != null)
        {
            explorationManager.SetMapSize(300, 300);
            Debug.Log("🗺️ Reset to standard 300x300 map");
        }
        else
        {
            Debug.LogError("❌ Exploration manager not available!");
        }
    }

    [ContextMenu("FIX: Synchronize Team Marker Position")]
    public void SynchronizeTeamMarkerPosition()
    {
        if (explorationManager != null)
        {
            explorationManager.SynchronizeTeamMarkerPosition();
            Debug.Log("🔄 Team marker position synchronized between coordinate systems");
        }
        else
        {
            Debug.LogError("❌ Exploration manager not available!");
        }
    }

    [ContextMenu("TEST: Debug Full Map Coordinate Fix")]
    public void TestFullMapCoordinateFix()
    {
        if (!useExplorationSystem || explorationManager == null)
        {
            Debug.LogError("❌ Exploration system not enabled or null!");
            return;
        }

        GameObject teamMarker = GameObject.Find("TeamMarker");
        if (teamMarker == null)
        {
            Debug.LogError("❌ Team marker not found!");
            return;
        }

        Vector3 worldPos = teamMarker.transform.position;
        Vector2Int worldTilePos = new Vector2Int(
            Mathf.RoundToInt(worldPos.x),
            Mathf.RoundToInt(worldPos.y)
        );

        Debug.Log("🧪 COORDINATE FIX TEST - Before showing full map:");
        Debug.Log($"   Team marker world position: {worldPos}");
        Debug.Log($"   Team marker tile position: {worldTilePos}");
        Debug.Log($"   Current map size: {mapData?.Width ?? 0}x{mapData?.Height ?? 0}");

        // Show full map and check if position is preserved
        explorationManager.ShowFullMap();

        // Check position after full map is shown
        Vector3 newWorldPos = teamMarker.transform.position;
        Vector2Int newWorldTilePos = new Vector2Int(
            Mathf.RoundToInt(newWorldPos.x),
            Mathf.RoundToInt(newWorldPos.y)
        );

        Debug.Log("🧪 COORDINATE FIX TEST - After showing full map:");
        Debug.Log($"   Team marker world position: {newWorldPos}");
        Debug.Log($"   Team marker tile position: {newWorldTilePos}");
        Debug.Log($"   Position preserved: {(worldTilePos == newWorldTilePos ? "✅ YES" : "❌ NO")}");

        if (worldTilePos != newWorldTilePos)
        {
            Debug.LogError($"❌ COORDINATE FIX FAILED: Position changed from {worldTilePos} to {newWorldTilePos}");
        }
        else
        {
            Debug.Log("✅ COORDINATE FIX SUCCESS: Team marker position preserved when showing full map");
        }
    }

    [ContextMenu("FIX: Reset Team Marker to Map Center")]
    public void ResetTeamMarkerToCenter()
    {
        if (!useExplorationSystem || explorationManager == null)
        {
            Debug.LogError("❌ Exploration system not enabled or null!");
            return;
        }

        explorationManager.ResetTeamMarkerToMapCenter();
        Debug.Log("🎯 Team marker has been reset to the center of the map");
    }

    [ContextMenu("FIX: Clear Saved Team Position")]
    public void ClearSavedTeamPosition()
    {
        // Clear saved position from PlayerPrefs
        string keyX = $"TeamPosition_{seed}_X";
        string keyY = $"TeamPosition_{seed}_Y";

        if (PlayerPrefs.HasKey(keyX)) PlayerPrefs.DeleteKey(keyX);
        if (PlayerPrefs.HasKey(keyY)) PlayerPrefs.DeleteKey(keyY);

        PlayerPrefs.Save();

        Debug.Log($"🗑️ Cleared saved team position for seed {seed}");
        Debug.Log($"   Deleted keys: {keyX}, {keyY}");
        Debug.Log("   Restart the scene to use default center position");
    }

    [ContextMenu("DEBUG: Show Coordinate State")]
    public void DebugCoordinateState()
    {
        if (explorationManager != null)
        {
            explorationManager.DebugCoordinateState();
        }
        else
        {
            Debug.LogError("❌ Exploration manager not available!");
        }
    }

    [ContextMenu("FIX: Force Coordinate Sync")]
    public void ForceCoordinateSync()
    {
        if (explorationManager != null)
        {
            explorationManager.ForceCoordinateSync();
        }
        else
        {
            Debug.LogError("❌ Exploration manager not available!");
        }
    }

    [ContextMenu("TEST: Simple Coordinate Conversion")]
    public void TestSimpleCoordinateConversion()
    {
        if (!useExplorationSystem || explorationManager == null)
        {
            Debug.LogError("❌ Exploration system not enabled or null!");
            return;
        }

        explorationManager.TestSimpleCoordinateConversion();
    }

    [ContextMenu("TEST: Positioning After Fix")]
    public void TestPositioningAfterFix()
    {
        if (!useExplorationSystem || explorationManager == null)
        {
            Debug.LogError("❌ Exploration system not enabled or null!");
            return;
        }

        explorationManager.TestPositioningAfterFix();
    }

    [ContextMenu("TEST: Full Map Tile Coverage")]
    public void TestFullMapTileCoverage()
    {
        if (!useExplorationSystem || explorationManager == null)
        {
            Debug.LogError("❌ Exploration system not enabled or null!");
            return;
        }

        explorationManager.TestFullMapTileCoverage();
    }

    [ContextMenu("TEST: Visual Tile Rendering")]
    public void TestVisualTileRendering()
    {
        if (!useExplorationSystem || explorationManager == null)
        {
            Debug.LogError("❌ Exploration system not enabled or null!");
            return;
        }

        explorationManager.TestVisualTileRendering();
    }

    [ContextMenu("TEST: Detailed Coordinate Conversion")]
    public void TestDetailedCoordinateConversion()
    {
        if (!useExplorationSystem || explorationManager == null)
        {
            Debug.LogError("❌ Exploration system not enabled or null!");
            return;
        }

        explorationManager.TestCoordinateConversion();
    }

    /// <summary>
    /// Public method to synchronize team position - can be called by travel system
    /// </summary>
    public void SyncTeamPosition()
    {
        if (useExplorationSystem && explorationManager != null)
        {
            explorationManager.SynchronizeTeamMarkerPosition();
        }
    }

    // Expose map size properties for ExplorationManager
    public int mapWidth
    {
        get => mapData?.Width ?? initialMapSize;
        set { /* Can be used by exploration system */ }
    }

    public int mapHeight
    {
        get => mapData?.Height ?? initialMapSize;
        set { /* Can be used by exploration system */ }
    }
}