using UnityEngine;

/// <summary>
/// Singleton that persists settlement data across scene transitions
/// Ensures town generation is consistent based on settlement type
/// </summary>
public class SettlementContext : MonoBehaviour
{
    public static SettlementContext Instance { get; private set; }

    [Header("Current Settlement Data")]
    public string settlementName = "Haven Village";
    public SettlementType settlementType = SettlementType.Town;
    public bool hasHarbor = false;
    public Vector2Int mapPosition = Vector2Int.zero;
    public int settlementSeed = 0; // For consistent generation

    [Header("Generated Data")]
    public TownShop[] availableShops;
    public ShopData[] generatedShopData; // Data-only shop definitions
    public bool isGenerated = false;

    private void Awake()
    {
        // Singleton pattern - persist across scenes
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
            Debug.Log("SettlementContext created and marked as DontDestroyOnLoad");
        }
        else
        {
            Debug.Log("SettlementContext already exists, destroying duplicate");
            Destroy(gameObject);
        }
    }

    /// <summary>
    /// Set settlement data before entering town scene
    /// </summary>
    public void SetSettlement(string name, SettlementType type, Vector2Int position, bool harbor = false)
    {
        settlementName = name;
        settlementType = type;
        mapPosition = position;
        hasHarbor = harbor;

        // Generate consistent seed based on position and name
        settlementSeed = (position.x * 1000 + position.y) ^ name.GetHashCode();

        // Clear existing generation to force regeneration
        isGenerated = false;
        availableShops = null;

        Debug.Log($"Settlement context set: {name} ({type}) at {position}, seed: {settlementSeed}");
    }

    /// <summary>
    /// <summary>
    /// Generate shops based on settlement type - just logs what would be created
    /// TownShopManager handles the actual shop configuration
    /// </summary>
    public TownShop[] GenerateShops()
    {
        if (isGenerated)
        {
            Debug.Log("Settlement already generated");
            return new TownShop[0];
        }

        Debug.Log($"Planning shops for {settlementType}: {settlementName}");

        // Use settlement seed for consistent generation logging
        var oldState = Random.state;
        Random.InitState(settlementSeed);

        if (settlementType == SettlementType.Town)
        {
            Debug.Log("Town will have: Weapons, Armor, Potions, General shops");
            if (Random.value > 0.3f) // 70% chance
            {
                Debug.Log("Town will also have: Adventurer's Guild");
            }
            if (hasHarbor && Random.value > 0.5f) // 50% chance if near water
            {
                Debug.Log("Town will also have: Harbor Trading Post");
            }
        }
        else // Village
        {
            Debug.Log("Village will have: General Store");
            if (Random.value > 0.4f) // 60% chance
            {
                var shopTypes = new string[] { "Herb Shop", "Old Weaponsmith" };
                int index = Random.Range(0, shopTypes.Length);
                Debug.Log($"Village will also have: {shopTypes[index]}");
            }
        }

        // Restore random state
        Random.state = oldState;
        isGenerated = true;

        Debug.Log("Shop configuration complete - TownShopManager will handle activation");
        return new TownShop[0]; // No MonoBehaviour instances created here
    }

    /// <summary>
    /// Get shops for current settlement (generates if needed)
    /// </summary>
    public TownShop[] GetShops()
    {
        if (!isGenerated || availableShops == null)
        {
            return GenerateShops();
        }
        return availableShops;
    }

    /// <summary>
    /// Clear settlement data (for testing)
    /// </summary>
    [ContextMenu("Clear Settlement Data")]
    public void ClearSettlementData()
    {
        isGenerated = false;
        availableShops = null;
        Debug.Log("Settlement data cleared");
    }

    /// <summary>
    /// Debug method to test different settlement types
    /// </summary>
    [ContextMenu("Test Village Generation")]
    public void TestVillageGeneration()
    {
        SetSettlement("Test Village", SettlementType.Village, new Vector2Int(50, 50));
        var shops = GenerateShops();
        Debug.Log($"Village shops: {string.Join(", ", System.Array.ConvertAll(shops, s => s.buildingName))}");
    }

    [ContextMenu("Test Town Generation")]
    public void TestTownGeneration()
    {
        SetSettlement("Test Town", SettlementType.Town, new Vector2Int(100, 100), true);
        var shops = GenerateShops();
        Debug.Log($"Town shops: {string.Join(", ", System.Array.ConvertAll(shops, s => s.buildingName))}");
    }
}
