extends State

@export var max_speed: float = 5.0
@export var acceleration: float = 2.0
@export var deceleration: float = 200.0
@export var player: Player
@export var player_movement: PlayerMovement
@export var player_input: PlayerInput
@export var weapon_system: WeaponSystem
@export var audio: MultiplayerAudio3D
@export var step_delay: float
@export var step_speed_curve: Curve

var step_time: float

func enter() -> void:
	player_input.jumped.connect(on_jumped)
	player_input.crouch_begin.connect(begin_crouch)
	player_input.walk_begin.connect(begin_walk)

func exit() -> void:
	player_input.jumped.disconnect(on_jumped)
	player_input.crouch_begin.disconnect(begin_crouch)
	player_input.walk_begin.disconnect(begin_walk)
	step_time = 0

func physics_update(delta: float) -> void:
	if not is_multiplayer_authority():
		return
	
	if not player.is_on_floor():
		transition.emit("Fall")
		return
	
	step_time += delta * step_speed_curve.sample((player.velocity * Vector3(1,0,1)).length_squared()/(max_speed*max_speed))
	if step_time >= step_delay:
		step_time = 0
		audio.multiplayer_play()
	
	player_movement.process_movement(max_speed * weapon_system.get_speed_modifier(),acceleration,deceleration,delta)

func on_jumped() -> void:
	if player.is_on_floor():
		player_movement.jump()
		transition.emit("Fall")

func begin_walk() -> void:
	transition.emit("Walk")

func begin_crouch() -> void:
	transition.emit("Crouch")
