extends CharacterBody3D

class_name Player

const MAX_HP = 100

@export var hp: int = 100:
	set(value):
		if value < 0:
			hp = 0
		else:
			hp = value
		if hp == 0:
			die()
		
	get:
		return hp

@export var animation_player: AnimationPlayer
@export var stand_up_area: Area3D

@export var CROUCH_TIME: float = 1.0
@export var SPEED: float = 5.0
@export var JUMP_VELOCITY: float = 4.5
# Replace with settings
@export var TOGGLE_CROUCH: bool = true
@export var WALK_MODIFIER: float = 0.5



@export var crouched: bool = false:
	set(value):
		if value != crouched and stand_up_area.has_overlapping_bodies() == false:
			crouched = value
			update_crouch()
			SPEED = (SPEED*WALK_MODIFIER) if crouched else (SPEED/WALK_MODIFIER)
		potential_crouched = value
	get:
		return crouched

@onready var TEMP_start_pos = global_position

var potential_crouched: bool = crouched

func _enter_tree() -> void:
	set_multiplayer_authority(str(name).to_int())

func _process(_delta: float) -> void:
	if not is_multiplayer_authority():
		return
	if potential_crouched != crouched:
		crouched = potential_crouched

func _physics_process(delta: float) -> void:
	if not is_multiplayer_authority():
		return
	# Add the gravity.
	if not is_on_floor():
		velocity += get_gravity() * delta

	# Handle jump.
	if Input.is_action_just_pressed("plr_jump") and is_on_floor():
		velocity.y = JUMP_VELOCITY

	# Get the input direction and handle the movement/deceleration.
	# As good practice, you should replace UI actions with custom gameplay actions.
	var input_dir := Input.get_vector("plr_strafe_r","plr_strafe_l", "plr_back","plr_forward")
	var direction := (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
	if direction:
		velocity.x = direction.x * SPEED
		velocity.z = direction.z * SPEED
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
		velocity.z = move_toward(velocity.z, 0, SPEED)

	move_and_slide()

func update_crouch():
	if crouched:
		animation_player.play("Crouch",-1,1/CROUCH_TIME)
	else:
		animation_player.play("Crouch",-1,-1/CROUCH_TIME,true)

func _input(event: InputEvent) -> void:
	if not is_multiplayer_authority():
		return
	if event.is_action_pressed("plr_crouch"):
		if TOGGLE_CROUCH:
			crouched = not crouched
		else:
			crouched = true
	elif event.is_action_released("plr_crouch") and TOGGLE_CROUCH == false:
		crouched = false

func die() -> void:
	global_position = TEMP_start_pos
	hp = MAX_HP
