extends Node

const SCENES := {
	"lobby":      "res://scenes/tavern_lobby.tscn",
	"tavern":     "res://scenes/tavern.tscn",
	"dm_view":    "res://scenes/dm_view.tscn",
	"entrance_hall": "res://scenes/entrance_hall.tscn",
	"refectory":  "res://scenes/refectory.tscn",
	"library":    "res://scenes/library.tscn",
	"chapel":     "res://scenes/chapel.tscn",
	"cloister":   "res://scenes/cloister.tscn",
	"sanctum":    "res://scenes/sanctum.tscn",
}

var pending_room_index: int = 0
var _current_scene_node: Node = null


func _ready() -> void:
	NetworkManager.game_started.connect(_on_game_started)
	get_tree().root.ready.connect(_on_root_ready, CONNECT_ONE_SHOT)


func _on_root_ready() -> void:
	var args := OS.get_cmdline_args() + OS.get_cmdline_user_args()
	var is_server := OS.has_feature("dedicated_server") or "--server" in args
	if not is_server:
		transition_to("lobby")


func transition_to(scene_name: String) -> void:
	var path: String = SCENES.get(scene_name, "")
	var packed := ResourceLoader.load(path, "PackedScene", ResourceLoader.CACHE_MODE_REUSE) as PackedScene
	if packed == null:
		push_error("[SceneManager] Scene not found: %s" % scene_name)
		return
	var container := get_node_or_null("/root/Main/CurrentScene")
	if container == null:
		push_error("[SceneManager] CurrentScene node not found in main.tscn")
		return
	if _current_scene_node != null:
		_current_scene_node.get_parent().remove_child(_current_scene_node)
		_current_scene_node.queue_free()
		_current_scene_node = null
	_current_scene_node = packed.instantiate()
	container.add_child(_current_scene_node)


func _on_game_started() -> void:
	var args := OS.get_cmdline_args() + OS.get_cmdline_user_args()
	if OS.has_feature("dedicated_server") or "--server" in args:
		return
	var role: String = NetworkManager.players.get(NetworkManager.my_id, {}).get("role", "player")
	if role == "dm":
		transition_to("dm_view")
	else:
		transition_to("tavern")
