namespace splat;

using Godot;

/// <summary>
/// In-game overlay showing simulated time, speed, and building count. Kept
/// controller-navigable and purely informational for Phase 1.
/// </summary>
public partial class HUD : Control
{
    private Label _timeLabel = default!;
    private Label _speedLabel = default!;
    private Label _buildingLabel = default!;
    private Label _toolLabel = default!;
    private Control _reticle = default!;

    public override void _Ready()
    {
        _timeLabel = GetNode<Label>("Margin/Panel/Margin/Stats/TimeLabel");
        _speedLabel = GetNode<Label>("Margin/Panel/Margin/Stats/SpeedLabel");
        _buildingLabel = GetNode<Label>("Margin/Panel/Margin/Stats/BuildingLabel");
        _toolLabel = GetNode<Label>("ToolStatus/ToolLabel");
        _reticle = GetNode<Control>("PlacementReticle");

        SetTool(InputManager.Tool.Select);

        var gm = FindGameManager();
        if (gm != null)
        {
            gm.SpeedChanged += OnSpeedChanged;
            gm.NewDay += OnNewDay;
        }

        var bm = FindBuildingManager();
        if (bm != null)
            bm.BuildingsChanged += OnBuildingsChanged;
    }

    private void OnSpeedChanged(float timeScale)
        => _speedLabel.Text = timeScale <= 0f ? "Speed: Paused" : $"Speed: {timeScale}x";

    private void OnNewDay(int day)
        => _timeLabel.Text = $"Day {day}";

    private void OnBuildingsChanged(int count)
        => _buildingLabel.Text = $"Buildings: {count}";

    /// <summary>Reflect the active interaction mode and show its placement reticle.</summary>
    public void SetTool(InputManager.Tool tool)
    {
        _toolLabel.Text = tool switch
        {
            InputManager.Tool.PlaceBuilding => "Cottage  •  A / Enter to place",
            InputManager.Tool.PlaceRoad => "Road  •  A / Enter to place",
            InputManager.Tool.Demolish => "Demolish  •  A / Enter to remove",
            InputManager.Tool.Inspect => "Inspect",
            _ => "Explore  •  Y / Tab to build"
        };
        _reticle.Visible = tool is InputManager.Tool.PlaceBuilding
            or InputManager.Tool.PlaceRoad
            or InputManager.Tool.Demolish;
    }

    private static GameManager FindGameManager()
        => (GameManager)((SceneTree)Engine.GetMainLoop()).Root
            .FindChild("GameManager", owned: true, recursive: true);

    private static BuildingManager FindBuildingManager()
        => (BuildingManager)((SceneTree)Engine.GetMainLoop()).Root
            .FindChild("BuildingManager", owned: true, recursive: true);
}
