Editor/SubTerrainStatusWidget.cs
// Copyright (c) 2026 SubZero Studios LLC. All rights reserved.

using System;
using Sandbox;

namespace Editor.SubTerrain;

/// <summary>
/// Cursor height and brush footprint readout under Brush Properties.
/// </summary>
internal class SubTerrainStatusWidget : Widget
{
	readonly SubTerrainTool _tool;
	Label _line;

	public SubTerrainStatusWidget( SubTerrainTool tool, Widget parent ) : base( parent )
	{
		_tool = tool;

		Layout = Layout.Column();
		Layout.Margin = new Sandbox.UI.Margin( 4, 4, 4, 6 );
		Layout.Spacing = 0;

		_line = new Label( "Z -- | -- | -- tx | -- u" );
		_line.Color = Theme.TextControl.WithAlpha( 0.82f );
		_line.ToolTip = "Local height Z | height 0-1 | brush texels | brush size (world).";
		Layout.Add( _line );

		MinimumHeight = 28;
		MaximumHeight = 32;
	}

	protected override void OnPaint()
	{
		base.OnPaint();

		Paint.Antialiasing = true;
		Paint.ClearPen();
		Paint.SetBrush( Theme.WidgetBackground.WithAlpha( 0.55f ) );
		Paint.DrawRect( LocalRect.Shrink( 0, 1 ), 3 );
	}

	[EditorEvent.Frame]
	public void Refresh()
	{
		if ( _line is null )
			return;

		if ( !_tool.StatusValid || !_tool.StatusTerrain.IsValid() )
		{
			_line.Text = "Z -- | -- | -- tx | -- u";
			_line.Color = Theme.TextControl.WithAlpha( 0.45f );
			return;
		}

		var storage = _tool.StatusTerrain.Storage;
		if ( storage is null || storage.TerrainHeight <= 0.001f || storage.Resolution <= 0 )
		{
			_line.Text = "Z -- | -- | -- tx | -- u";
			_line.Color = Theme.TextControl.WithAlpha( 0.45f );
			return;
		}

		var z = _tool.StatusHitLocal.z;
		// Match sculpt/paint diameter mapping (Size is radius).
		var texels = (int)Math.Floor( _tool.BrushSettings.Size * 2.0f / storage.TerrainSize * storage.Resolution );
		_line.Text = $"Z {z:0.##} | {(z / storage.TerrainHeight):0.####} | {Math.Max( texels, 1 )} tx | {_tool.BrushSettings.Size} u";
		_line.Color = Theme.TextControl.WithAlpha( 0.88f );
	}
}