using UnityEngine;
using System.Collections.Generic;
using System.Linq;

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

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

    private MapData mapData;
    private TerrainGenerator terrainGenerator;
    private FeatureGenerator featureGenerator;
    private ExpansionManager expansionManager;
    private Transform player;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        InitializeMap();
        GenerateInitialMap();
    }

    // Update is called once per frame
    void Update()
    {
        if (player != null)
        {
            CheckForExpansion();
        }
    }

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

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

        // Find player object (assuming it has a "Player" tag)
        GameObject playerObj = GameObject.FindGameObjectWithTag("Player");
        if (playerObj != null)
            player = playerObj.transform;
    }

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

        // Generate features
        featureGenerator.GenerateFeatures(mapData);

        // Visualize the map (you'll need to implement this based on your rendering system)
        VisualizeMap();
    }

    private void CheckForExpansion()
    {
        Vector2 playerPos = new Vector2(player.position.x, player.position.z);
        if (expansionManager.ShouldExpand(playerPos, mapData))
        {
            ExpandMap(playerPos);
        }
    }

    private void ExpandMap(Vector2 playerPos)
    {
        expansionManager.ExpandMap(mapData, playerPos, expansionSize);
        VisualizeMap(); // Update visualization
    }

    private void VisualizeMap()
    {
        // This is where you'd implement your map visualization
        // For now, we'll just log the map data
        Debug.Log($"Map generated with size: {mapData.Width}x{mapData.Height}");
        Debug.Log($"Towns: {mapData.GetTowns().Count}, Villages: {mapData.GetVillages().Count}");
    }

    public MapData GetMapData() => mapData;
}
