extends CanvasLayer

# Game UI - Main menu and multiplayer lobby

@onready var main_menu = $Control/MainMenu
@onready var host_button = $Control/MainMenu/VBoxContainer/HostButton
@onready var join_button = $Control/MainMenu/VBoxContainer/JoinButton
@onready var local_players_spinbox = $Control/MainMenu/VBoxContainer/LocalPlayersContainer/SpinBox
@onready var address_input = $Control/MainMenu/VBoxContainer/AddressContainer/AddressInput

@onready var network_manager = $"/root/NetworkManager"

func _ready():
	# Wait for nodes to be ready
	await get_tree().process_frame
	
	# Debug: Print node paths
	print("GameUI _ready() called")
	print("Main menu node: ", main_menu)
	print("Host button node: ", host_button)
	print("Join button node: ", join_button)
	
	# Verify nodes exist
	if not host_button:
		push_error("host_button is null! Check node path: $Control/MainMenu/VBoxContainer/HostButton")
		return
	if not join_button:
		push_error("join_button is null! Check node path: $Control/MainMenu/VBoxContainer/JoinButton")
		return
	
	# Connect buttons
	host_button.pressed.connect(_on_host_pressed)
	join_button.pressed.connect(_on_join_pressed)
	
	# Connect network signals
	if network_manager:
		network_manager.connection_succeeded.connect(_on_connection_succeeded)
		network_manager.connection_failed.connect(_on_connection_failed)
	else:
		push_error("NetworkManager not found!")
	
	# Check for command-line arguments
	_check_command_line_args()

func _check_command_line_args():
	var args = OS.get_cmdline_args()
	
	# Parse arguments
	var should_host = false
	var should_join = false
	var join_address = "127.0.0.1"
	var local_count = 1
	
	for arg in args:
		if arg == "--host":
			should_host = true
		elif arg == "--join":
			should_join = true
		elif arg.begins_with("--address="):
			join_address = arg.split("=")[1]
		elif arg.begins_with("--players="):
			local_count = int(arg.split("=")[1])
	
	# Auto-start based on arguments
	if should_host:
		print("Auto-hosting due to --host argument")
		network_manager.set_local_player_count(local_count)
		if network_manager.host_game():
			_start_game()
	elif should_join:
		print("Auto-joining to ", join_address, " due to --join argument")
		address_input.text = join_address
		network_manager.set_local_player_count(local_count)
		if network_manager.join_game(join_address):
			# Connection callback will handle starting the game
			pass

func _on_host_pressed():
	var local_count = int(local_players_spinbox.value)
	network_manager.set_local_player_count(local_count)
	
	if network_manager.host_game():
		print("Hosting game with ", local_count, " local players")
		_start_game()

func _on_join_pressed():
	var address = address_input.text
	if address.is_empty():
		address = "127.0.0.1"
	
	var local_count = int(local_players_spinbox.value)
	network_manager.set_local_player_count(local_count)
	
	if network_manager.join_game(address):
		print("Joining game at ", address, " with ", local_count, " local players")

func _on_connection_succeeded():
	print("Connection succeeded, starting game")
	_start_game()

func _on_connection_failed():
	print("Connection failed")
	# Show error message
	var error_label = Label.new()
	error_label.text = "Failed to connect to server"
	error_label.modulate = Color.RED
	main_menu.add_child(error_label)

func _start_game():
	# Hide menu
	main_menu.visible = false
	
	# Load the game scene
	get_tree().change_scene_to_file("res://scenes/game_world.tscn")
