extends Node

@export var ui: CanvasLayer
@export var active_npcs_parent: Node
@export var debug_overlay_visible := true

var _refresh_accumulator := 0.0


func _ready() -> void:
	_apply_debug_overlay_visibility()


func _process(delta: float) -> void:
	_refresh_accumulator += delta
	if _refresh_accumulator < 0.5:
		return
	_refresh_accumulator = 0.0
	_apply_debug_overlay_visibility()


func _unhandled_key_input(event: InputEvent) -> void:
	if not event is InputEventKey or not event.pressed or event.echo:
		return
	if event.keycode == KEY_F10:
		toggle_debug_overlay()
		get_viewport().set_input_as_handled()
	elif event.keycode == KEY_F12:
		reset_demo_scene()
		get_viewport().set_input_as_handled()


func toggle_debug_overlay() -> void:
	debug_overlay_visible = not debug_overlay_visible
	_apply_debug_overlay_visibility()
	print(
		"[DemoController] %s"
		% ("Debug overlay visible" if debug_overlay_visible else "Cinematic overlay hidden")
	)


func reset_demo_scene() -> void:
	print("[DemoController] Resetting simulation garden demo")
	get_tree().reload_current_scene()


func _apply_debug_overlay_visibility() -> void:
	if ui != null and ui.has_method("set_debug_overlay_visible"):
		ui.set_debug_overlay_visible(debug_overlay_visible)

	for node in ResourceNode.get_all():
		if node.has_method("set_debug_label_enabled"):
			node.set_debug_label_enabled(debug_overlay_visible)

	for node in StorageNode.get_all():
		if node.has_method("set_debug_label_enabled"):
			node.set_debug_label_enabled(debug_overlay_visible)

	for node in ActivitySite.get_all():
		if node.has_method("set_debug_label_enabled"):
			node.set_debug_label_enabled(debug_overlay_visible)

	if active_npcs_parent == null:
		return
	for child in active_npcs_parent.get_children():
		if child.has_method("set_debug_overlay_visible"):
			child.set_debug_overlay_visible(debug_overlay_visible)
