class_name WorldUI extends Control
## Container & accessor for the world UI.

const DEMO_CAMERA_GROUP := "DemoCamera"

@export var pause_scene := preload("res://src/ui/menus/pause_menu/pause_menu.tscn")

var _prev_camera: Camera3D

@onready var hud_container: Control = %HUDContainer
@onready var pause_container: Control = %PauseContainer


func _unhandled_key_input(event: InputEvent) -> void:
	if event.is_action_pressed("pause"):
		get_viewport().set_input_as_handled()
		pause()


func add_player_hud(hud: ShotHUD) -> void:
	hud_container.add_child(hud)


func pause() -> void:
	# Switch to demo cam, if there is one.
	var democams: Array[Node] = get_tree().get_nodes_in_group(DEMO_CAMERA_GROUP)
	if democams:
		_prev_camera = get_viewport().get_camera_3d()
		var democam: Camera3D = democams.pick_random()
		democam.make_current()

	var menu := pause_scene.instantiate()
	pause_container.add_child(menu)
	menu.tree_exiting.connect(_unpause)
	hud_container.hide()
	get_tree().paused = true


func _unpause() -> void:
	# Unset demo camera, if there is one.
	if is_instance_valid(_prev_camera):
		_prev_camera.make_current()
		_prev_camera = null
	hud_container.show()
	get_tree().paused = false
