extends CharacterBody3D

const CHASE_SHORT_1 := preload("res://audio/Shortchase1.wav")
const CHASE_SHORT_2 := preload("res://audio/Shortchase2.wav")
const CHASE_MID := preload("res://audio/Midchase1.wav")
const CHASE_LONG := preload("res://audio/Chase1.wav")
const CHASE_TRACKS := [CHASE_SHORT_1, CHASE_SHORT_2, CHASE_MID, CHASE_LONG]
static var _last_chase: AudioStream = null

var speed: int = 3
var clumsiness: int = 0
var _saved: bool = false

@onready var safety_zone: Node = get_node_or_null("/root/Game/World/ElevatorSafeZone")


#func start(xform):
	#transform = xform
	#velocity = (-xform.basis.z * speed).rotated(Vector3.UP, randf_range(-PI/4, PI/4))

func _ready():
	var candidates: Array = CHASE_TRACKS.filter(func(s): return s != _last_chase)
	var stream: AudioStream = candidates[randi() % candidates.size()]
	_last_chase = stream
	$ScreamPlayer.stream = stream
	var delay := randf_range(0.0, 0.5)
	get_tree().create_timer(delay, false).timeout.connect(
		func(): $ScreamPlayer.play(),
		CONNECT_ONE_SHOT
	)

func _physics_process(_delta):
	velocity.z = -speed
	move_and_slide()

func _on_area_3d_area_entered(area: Area3D) -> void:
	if area == safety_zone and not _saved:
		_saved = true
		var elevator = safety_zone.get_node_or_null("Elevator")
		if elevator and elevator.get_door_close_progress() > 0.7:
			EventBus.survivor_squeaked_in.emit()
		get_tree().create_timer(0.5, false).timeout.connect(
			func(): queue_free(),
			CONNECT_ONE_SHOT
		)
