extends GameBall

const ABILITY_MAGNITUDE := 2.0

const SCREENSHAKE_INTENSITY := 8.0
const SCREENSHAKE_LENGTH := 3.0

var _ability_impulse := Vector3.ZERO

@onready var fireball_pivot: Node3D = %FireballPivot

@onready var powerball_animation: AnimationPlayer = %PowerballAnimation

@onready var game: Game = get_tree().get_first_node_in_group(Game.group)


func _activate_ability() -> void:
	_ability_impulse = linear_velocity.normalized() * ABILITY_MAGNITUDE
	can_sleep = false
	freeze = true
	powerball_animation.play("activate")


func _finish_ability() -> void:
	can_sleep = true
	freeze = false
	apply_central_impulse(_ability_impulse)
	game.viewport.screen_shake(SCREENSHAKE_INTENSITY, SCREENSHAKE_LENGTH)


func _process(_delta: float) -> void:
	# Rotate fireball to direction of travel
	var y := linear_velocity.normalized()
	if y.length_squared() <= 1e-9:
		y = -global_basis.z.normalized()
	var x := Vector3(y.y, -y.x, 0)
	var z := y.cross(x).normalized()
	x = z.cross(y).normalized()  # orthonormalize
	fireball_pivot.global_basis = Basis(x, y, z)
