extends HBoxContainer
## Does a funky lil bump when you collect tha grunk

const COUNTER_BUMP_RATE := 0.15
const COUNTER_SPINDOWN_TIME := 0.4

const TANK_WARNING_BUFFER_PCT := 0.1

@onready var counter: Label = %Counter


func _ready() -> void:
	Game.manager.grunk_collected.connect(on_grunk_collected)
	Game.manager.grunk_emptied.connect(on_grunk_emptied)
	counter.pivot_offset = Vector2(0, counter.size.y)


func on_grunk_collected(delta: float) -> void:
	counter.text = str(int(clampf(Game.manager.grunk_tank, 0.0, Game.manager.grunk_tank_limit)))
	counter.scale = Vector2.ONE + Vector2.ONE * clampf(delta / 128.0, 0.1, 1.0)
	var buffer := remap(Game.manager.get_tank_fill_pct(), 1 - TANK_WARNING_BUFFER_PCT, 1, 0, 1)
	counter.modulate = Color.WHITE.lerp(Color.RED, clampf(buffer, 0, 1))


func on_grunk_emptied(amount: float) -> void:
	counter.modulate = Color.WHITE
	create_tween().tween_method(_set_counter, int(amount), 0, COUNTER_SPINDOWN_TIME).set_trans(
		Tween.TRANS_EXPO
	)


## Used with the spindown tween from `on_grunk_emptied`
func _set_counter(value: int) -> void:
	counter.text = str(value)
	counter.scale = Vector2.ONE * 2.0


func _process(_delta: float) -> void:
	counter.scale = counter.scale.lerp(Vector2.ONE, COUNTER_BUMP_RATE)
