extends CharacterBody2D

@export var speed: float = 450.0
@export var target_velocity = Vector2.ZERO
@export var acc: float = 3000.0
@export var fri: float = 2000.0
var element = "water"

func _ready() -> void:
	get_tree().paused = false
	$AnimatedSprite2D.animation = "water"

func _physics_process(delta):
	Global.player_position = global_position
	var direction = Vector2.ZERO
	
	var vp_size := get_viewport_rect().size
	
	global_position.x = clamp(global_position.x, 0.0, vp_size.x)
	global_position.y = clamp(global_position.y, 0.0, vp_size.y)
	
	if Input.is_action_pressed("move_right"):
		direction.x += 4
	if Input.is_action_pressed("move_left"):
		direction.x -= 4
	if Input.is_action_pressed("move_down"):
		direction.y += 4
	if Input.is_action_pressed("move_up"):
		direction.y -= 4
	
	direction = direction.normalized()
	
	target_velocity = direction * speed
	
	if direction != Vector2.ZERO:
		if velocity != Vector2.ZERO and velocity.normalized().dot(direction) < 0:
			velocity = velocity.move_toward(Vector2.ZERO, fri * delta)
		velocity = velocity.move_toward(target_velocity, acc * delta)
	else:
		velocity = velocity.move_toward(Vector2.ZERO, fri * delta)
	
	move_and_slide()
	
	var look := get_global_mouse_position() - global_position
	var angle := look.angle()
	
	var slices := 8
	var slice_angle := TAU / slices
	
	angle = fposmod(-angle + PI / 2, TAU)
	
	var index := int(floor((angle + slice_angle / 2.0) / slice_angle)) % slices
	$AnimatedSprite2D.frame = index
	
	if Input.is_action_just_pressed("shoot"):
		$Shoot.play()
	
	if Input.is_action_just_pressed("action"):
		if $AnimatedSprite2D.animation == "fire":
			$AnimatedSprite2D.play("wind")
			element = "wind"
			$AnimatedSprite2D.frame = index
		elif $AnimatedSprite2D.animation == "water":
			$AnimatedSprite2D.play("fire")
			element = "fire"
			$AnimatedSprite2D.frame = index
		elif $AnimatedSprite2D.animation == "wind":
			$AnimatedSprite2D.play("water")
			element = "water"
			$AnimatedSprite2D.frame = index
	



func _on_area_2d_area_entered(area: Area2D) -> void:
	if area.is_in_group("enemy"):
		$Die.play()
		get_tree().paused = true
		$"../Label".show()
		$"../Button".show()
