using UnityEngine;

/// <summary>
/// Bridge component that connects SettlementInteractionManager's GameObject control
/// with SettlementInteractionUI's UI Toolkit system
/// </summary>
public class SettlementUIBridge : MonoBehaviour
{
    [Header("UI Bridge")]
    [Tooltip("The SettlementInteractionUI component to control")]
    public SettlementInteractionUI settlementUI;

    [Tooltip("Should this GameObject's active state control the UI visibility?")]
    public bool controlUIVisibility = true;

    private bool lastActiveState;

    void Start()
    {
        // Find SettlementInteractionUI if not assigned
        if (settlementUI == null)
        {
            // First try to get from same GameObject
            settlementUI = GetComponent<SettlementInteractionUI>();
        }

        if (settlementUI == null)
        {
            // Then try to find in scene
            settlementUI = FindFirstObjectByType<SettlementInteractionUI>();
        }

        if (settlementUI != null)
        {
            Debug.Log("[UIBridge] Connected to SettlementInteractionUI");

            // Force initial state
            lastActiveState = gameObject.activeSelf;
            UpdateUIVisibility();
        }
        else
        {
            Debug.LogError("[UIBridge] SettlementInteractionUI not found! Make sure it's on the same GameObject.");
        }
    }
    void Update()
    {
        if (!controlUIVisibility) return;

        // Check if GameObject active state changed
        bool currentActiveState = gameObject.activeSelf;
        if (currentActiveState != lastActiveState)
        {
            lastActiveState = currentActiveState;
            UpdateUIVisibility();
        }
    }

    private void UpdateUIVisibility()
    {
        if (settlementUI == null) return;

        if (gameObject.activeSelf)
        {
            Debug.Log("[UIBridge] GameObject activated - UI should show");
            // Force UI to show with test data if no real settlement detected
            settlementUI.ForceShowUI();
        }
        else
        {
            Debug.Log("[UIBridge] GameObject deactivated - UI should hide");
            settlementUI.ForceHideUI();
        }
    }

    void OnEnable()
    {
        UpdateUIVisibility();
    }

    void OnDisable()
    {
        if (settlementUI != null)
        {
            settlementUI.ForceHideUI();
        }
    }
}
