class_name Selector
extends Node

@export var control_enabled: bool = false
@export var select_on_tab: bool = false
@export var navigate_delay: float = 0.2
@export_group("Sounds")
@export var navigate_sound: AudioStream = null
@export var select_sound: AudioStream = null
@export var return_sound: AudioStream = null

var current_item: int = 0
var item_count: int = 0
var navigate_timer: float = 0.0


func _physics_process(_delta: float) -> void:
	handle_input()


func _on_item_navigated(_index: int) -> void:
	pass


func _on_item_selected(_index: int) -> void:
	pass


func _on_return() -> void:
	pass


func handle_input() -> bool:
	if not control_enabled:
		return false
	if Input.is_action_just_pressed("b"):
		if return_sound:
			PulseSound0.load_and_play(return_sound)
		control_enabled = false
		_on_return()
		return false

	navigate_timer += get_physics_process_delta_time()
	if (
			select_on_tab
			and Input.is_action_pressed("select")
			and navigate_timer >= navigate_delay
	):
		navigate_timer = 0.0
		current_item = (current_item + 1) % item_count
		if navigate_sound:
			PulseSound0.load_and_play(navigate_sound)
		_navigate_item(current_item)
		return false
	if (
			Input.is_action_pressed("down")
			and current_item < item_count - 1
			and navigate_timer >= navigate_delay
	):
		navigate_timer = 0.0
		current_item += 1
		if navigate_sound:
			PulseSound0.load_and_play(navigate_sound)
		_navigate_item(current_item)
		return false
	if (
			Input.is_action_pressed("up")
			and current_item > 0
			and navigate_timer >= navigate_delay
	):
		navigate_timer = 0.0
		current_item -= 1
		if navigate_sound:
			PulseSound0.load_and_play(navigate_sound)
		_navigate_item(current_item)
		return false
	return true


func _navigate_item(_index: int) -> void:
	pass
