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

const DEMO_CAMERA_GROUP := "DemoCamera"

@export var pause_scene: PackedScene
@export var death_alert_scene: PackedScene
@export var winner_alert_scene: PackedScene

var _prev_camera: Camera3D
var _pre_death_camera: Camera3D

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

@onready var world: World = $".."


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 play_death_sequence() -> void:
	_pre_death_camera = get_viewport().get_camera_3d()
	hud_container.hide()
	var alert := death_alert_scene.instantiate()
	alert.tree_exiting.connect(_finish_death_sequence)
	effect_container.add_child(alert)


func _finish_death_sequence() -> void:
	hud_container.show()
	_pre_death_camera.make_current()


func play_winner_sequence() -> void:
	hud_container.hide()
	var alert := winner_alert_scene.instantiate()
	alert.tree_exiting.connect(_finish_winner_sequence)
	effect_container.add_child(alert)


func _finish_winner_sequence() -> void:
	world.fade_to_title()


func pause() -> void:
	# Turn off fast-forward, if it's on
	world.fast_forward = false

	# 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
