extends CanvasLayer

# "Mirrored" stat bar, top-middle of the screen: the filled region is
# centered in the bar's full extent, so it shrinks toward the middle from
# both edges as the stat drains, instead of draining left-to-right like a
# normal bar. Driven by Ship._update_hud() calling set_fill() with a
# health/max_health or energy/max_energy fraction (see ships/ship_movement.gd).
# Reused for both the HealthBar and EnergyBar instances in world.tscn — fill
# color and vertical stacking position are per-instance overrides of the
# exports below (health above energy).

const BAR_WIDTH := 300.0
const BAR_HEIGHT := 14.0
const COLOR_BG := Color(0.15, 0.18, 0.25, 0.6)

@export var margin_top: float = 20.0
@export var fill_color: Color = Color(0.25, 0.55, 1.0, 0.95)

var _fill: ColorRect


func _ready() -> void:
	layer = 4
	_build_ui()
	set_fill(0.0)


func _build_ui() -> void:
	var container := Control.new()
	container.anchor_left = 0.5
	container.anchor_right = 0.5
	container.anchor_top = 0.0
	container.anchor_bottom = 0.0
	container.offset_left = -BAR_WIDTH / 2.0
	container.offset_right = BAR_WIDTH / 2.0
	container.offset_top = margin_top
	container.offset_bottom = margin_top + BAR_HEIGHT
	container.mouse_filter = Control.MOUSE_FILTER_IGNORE
	add_child(container)

	var bg := ColorRect.new()
	bg.color = COLOR_BG
	bg.anchor_left = 0.0
	bg.anchor_right = 1.0
	bg.anchor_top = 0.0
	bg.anchor_bottom = 1.0
	bg.mouse_filter = Control.MOUSE_FILTER_IGNORE
	container.add_child(bg)

	_fill = ColorRect.new()
	_fill.color = fill_color
	_fill.mouse_filter = Control.MOUSE_FILTER_IGNORE
	container.add_child(_fill)


# frac in [0, 1]; the fill rect stays centered in the bar's full extent so it
# shrinks toward the middle from both edges as energy drains.
func set_fill(frac: float) -> void:
	if _fill == null:
		return
	var f := clampf(frac, 0.0, 1.0)
	var w := BAR_WIDTH * f
	_fill.position = Vector2((BAR_WIDTH - w) / 2.0, 0.0)
	_fill.size = Vector2(w, BAR_HEIGHT)
