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

const SCREAM_OPEN_DB := 0.0
const SCREAM_CLOSED_DB := -20.0

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

@onready var safety_zone: Node = get_node_or_null("/root/Game/World/ElevatorSafeZone")
@onready var _elevator: Node = safety_zone.get_node_or_null("Elevator") if safety_zone else null


#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):
	var p: float = _elevator.get_door_close_progress() if _elevator else 0.0
	if _in_safety_zone and not _saved and p > 0.49:
		velocity.z = 0
	else:
		velocity.z = -speed
	move_and_slide()
	if _elevator:
		$ScreamPlayer.volume_db = lerp(SCREAM_OPEN_DB, SCREAM_CLOSED_DB, p)

func _on_area_3d_area_entered(area: Area3D) -> void:
	if area == safety_zone and not _in_safety_zone:
		_in_safety_zone = true
		var elevator = safety_zone.get_node_or_null("Elevator")
		var close_progress: float = elevator.get_door_close_progress() if elevator else 0.0
		if close_progress > 0.49:
			return
		get_tree().create_timer(0.5, false).timeout.connect(
			func():
				if not is_instance_valid(self):
					return
				var elev = safety_zone.get_node_or_null("Elevator")
				var final_progress: float = elev.get_door_close_progress() if elev else 0.0
				if final_progress > 0.49:
					return
				_saved = true
				EventBus.survivor_entered_elevator.emit()
				queue_free(),
			CONNECT_ONE_SHOT
		)
