extends Node2D

const RADIUS := 10.0
const SPEED := 420.0
const PLATFORM_HALF := Vector2(80.0, 12.0)

var velocity := Vector2.ZERO


func _ready() -> void:
	velocity = Vector2(320.0, -360.0).normalized() * SPEED


func reset_to(center: Vector2) -> void:
	position = center
	var dir := Vector2(randf_range(-0.6, 0.6), -1.0).normalized()
	velocity = dir * SPEED
	queue_redraw()


func step(delta: float, platform_pos: Vector2, platform_vx: float, bounds: Rect2) -> void:
	position += velocity * delta
	_bounce_walls(bounds)
	_bounce_platform_top(platform_pos, platform_vx)
	queue_redraw()


func _bounce_walls(bounds: Rect2) -> void:
	var min_x := bounds.position.x + RADIUS
	var max_x := bounds.end.x - RADIUS
	var min_y := bounds.position.y + RADIUS
	var max_y := bounds.end.y - RADIUS

	if position.x < min_x:
		position.x = min_x
		velocity.x = absf(velocity.x)
	elif position.x > max_x:
		position.x = max_x
		velocity.x = -absf(velocity.x)

	if position.y < min_y:
		position.y = min_y
		velocity.y = absf(velocity.y)
	elif position.y > max_y:
		position.y = max_y
		velocity.y = -absf(velocity.y)

	_normalize_speed()


func _bounce_platform_top(platform_pos: Vector2, platform_vx: float) -> void:
	var left := platform_pos.x - PLATFORM_HALF.x
	var right := platform_pos.x + PLATFORM_HALF.x
	var top := platform_pos.y - PLATFORM_HALF.y
	var bottom := platform_pos.y + PLATFORM_HALF.y

	if position.x < left - RADIUS or position.x > right + RADIUS:
		return
	if velocity.y <= 0.0:
		return
	if position.y + RADIUS < top:
		return
	if position.y - RADIUS > bottom + 4.0:
		return

	position.y = top - RADIUS
	velocity.y = -absf(velocity.y)
	velocity.x += platform_vx * 0.45
	_normalize_speed()


func _normalize_speed() -> void:
	if velocity.length_squared() < 1.0:
		velocity = Vector2.RIGHT * SPEED
	else:
		velocity = velocity.normalized() * SPEED


func _draw() -> void:
	draw_circle(Vector2.ZERO, RADIUS, Color(1.0, 0.88, 0.35))
	draw_arc(Vector2.ZERO, RADIUS, 0.0, TAU, 24, Color(1.0, 0.95, 0.7), 1.5)
