A Godot v4 game about working in an office
extends Control

var selected_index := 0
var num_menu_items := 1
var active_menu = "Main"

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	for child in get_children():
		child.visible = false
		if child.name == active_menu:
			child.visible = true
			num_menu_items = child.get_child_count()
	var label = (find_child(active_menu).get_child(selected_index) as Label)
	label.text = "> " + label.text

func show_menu():
	self.visible = true

func hide_menu():
	self.visible = false

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	if !self.visible:
		return
	
	if Input.is_action_just_pressed('down'):
		selected_index = (selected_index + 1) % num_menu_items
	elif Input.is_action_just_pressed('up'):
		selected_index = (selected_index - 1) % num_menu_items
	
	if Input.is_action_just_pressed('select'):
		var curr_label = find_child(active_menu).get_child(selected_index) as Label
		var option = curr_label.text
		if option == "> back":
			find_child(active_menu).visible = false
			active_menu = "Main"
			$Main.visible = true
			num_menu_items = $Main.get_child_count()
			selected_index = 0
		elif option == "> SMACK":
			$Main.visible = false
			$Smack.visible = true
			active_menu = "Smack"
			num_menu_items = $Smack.get_child_count()
			selected_index = 0
		elif option == "> CAST":
			$Main.visible = false
			$Cast.visible = true
			active_menu = "Cast"
			num_menu_items = $Cast.get_child_count()
			selected_index = 0
		elif option == "> USE":
			$Main.visible = false
			$Use.visible = true
			active_menu = "Use"
			num_menu_items = $Use.get_child_count()
			selected_index = 0
		else:
			var player = get_parent().get_parent().get_node("Player")
			if active_menu == "Smack":
				player.choose_option(BattlePlayer.MoveOption.ATTACK, $Smack.get_child(selected_index).text.substr(2))
			elif active_menu == "Cast":
				player.choose_option(BattlePlayer.MoveOption.SPELL, $Cast.get_child(selected_index).text.substr(2))
			elif active_menu == "Use":
				player.choose_option(BattlePlayer.MoveOption.ITEM, $Use.get_child(selected_index).text.substr(2))
			elif active_menu == "Main":
				player.choose_option(BattlePlayer.MoveOption.RUN, "Bail")
	
	# Add visual indicator to labels
	var menu = find_child(active_menu)
	for child in menu.get_children():
		if child.get_index() == selected_index:
			if !(child as Label).text.begins_with("> "):
				child.text = "> " + child.text
		else:
			if (child as Label).text.begins_with("> "):
				child.text = child.text.substr(2)