extends MaskAbility

@export var max_bounces := 5
@export var speed := 1.4
@export var max_height = 100.
@export var explosion : PackedScene

@onready var sprite : Sprite2D = $Sprite2D
var traveled: float = 0.0

var bouncing = false
var target : Entity = null
var bounces := max_bounces
var already_hit : Array[Entity] = []

func mask_ready():
	super.mask_ready()

func _physics_process(delta: float) -> void:
	if traveled < 1:
		if target:
			target_position = target.position
		traveled += speed * delta

		global_position = start_position.lerp(target_position, traveled)

		var arc_y = 4 * max_height * traveled * (1 - traveled)

		sprite.position.y = -arc_y
	elif bouncing and bounces > 0:
		if target:
			target.damage()
		change_target()
	else:
		global_position = target_position
		sprite.position.y = 0

func change_target():
	var enemies = get_tree().get_nodes_in_group("enemy")
	var dist := 100000.
	var closest : Entity = null
	for e : Enemy in enemies:
		if e in already_hit: continue
		var e_dist = e.global_position.distance_to(global_position)
		if e_dist < dist:
			dist = e_dist
			closest = e
	bounces -= 1
	target = null
	if dist < 60:
		target = closest
		already_hit.append(closest)
		start_position = global_position
		target_position = closest.global_position
		traveled = 0
	var explo = explosion.instantiate()
	explo.emitting = true
	add_child(explo)

func _on_hitbox_hit_entity(entity : Entity) -> void:
	if from_player:
		for c in _get_all_children(self):
			if c is Hitbox:
				c.enabled = false
		bouncing = true
		target = entity
		already_hit = [entity]
		#change_target()
	else:
		entity.damage()
