extends NodeState

@export var player: Player
@export var animatedSprite2D: AnimatedSprite2D
@export var wallCheck: ShapeCast2D
@export var floorCheck: RayCast2D
@export var ledgeGrabBox: CollisionShape2D
@export var jumpState: NodeState


@export_category("Fall State")
@export var coyoteTime: float = .4
var coyoteJump: bool

const GRAVITY = player.GRAVITY
@onready var speed = player.speed
@onready var maxSpeed = player.maxAirSpeed
@onready var friction = player.airFriction


@warning_ignore("unused_parameter")
func on_process(delta: float) -> void:
	pass

func on_phyisics_process(delta: float) -> void:
	#print(fallTime)
	if !player.is_on_floor():
		get_coyte_time()
		player.velocity.y += GRAVITY * delta
	#player.velocity.x = move_toward(player.velocity.x, 0, friction)
	
	var direction: float = GameInputEvents.movement_input()
	
	if direction:
		player.velocity.x += direction * speed * delta
		player.velocity.x = move_toward(player.velocity.x, clamp(player.velocity.x, -maxSpeed, maxSpeed), friction * delta)
	
	if direction != 0:
		animatedSprite2D.flip_h = false if direction > 0 else true
	
	if direction == 0:
		player.velocity.x = move_toward(player.velocity.x, 0, friction * delta)
	
	
	transition_states()

func get_coyte_time() -> void:
	await get_tree().create_timer(coyoteTime).timeout
	coyoteJump = false

func enter() -> void:
	animatedSprite2D.play("Fall")
	ledgeGrabBox.disabled = false
	if player.is_on_floor():
		ledgeGrabBox.disabled = true
		return
	coyoteJump = true

func exit() -> void:
	ledgeGrabBox.disabled = true
	animatedSprite2D.stop()

func transition_states() -> void:
	#transitioning state
	
	if player.is_on_floor():
		transition.emit("idle")
	
	#jump state
	if GameInputEvents.jump_input():
		transition.emit("jump")
	
	if wallCheck.is_colliding() and !floorCheck.is_colliding() and player.velocity.y == 0 and player.is_on_floor():
		transition.emit("Grab")
	
	if GameInputEvents.dash_input() and player.canDash:
		transition.emit("dash")
	
	
	
