extends Control

@onready var splash_screen: Node = $SplashScreen
var current_menu: Control = null

const MAIN_MENU_SCENE = preload("res://scenes/ui/MainMenu.tscn")
const SETTINGS_MENU_SCENE = preload("res://scenes/ui/SettingsMenu.tscn")


func _ready() -> void:
	DebugManager.log_debug("Main scene ready", "Main")
	# Use alternative connection method with input handling
	_setup_splash_screen_connection()


func _setup_splash_screen_connection() -> void:
	# Wait for all nodes to be ready
	await get_tree().process_frame
	await get_tree().process_frame

	# Try to find SplashScreen node
	splash_screen = get_node_or_null("SplashScreen")
	if not splash_screen:
		DebugManager.log_warn("SplashScreen node not found, trying alternative methods", "Main")
		# Try to find by class or group
		var splash_nodes = get_tree().get_nodes_in_group("localizable")
		for node in splash_nodes:
			if node.scene_file_path.ends_with("SplashScreen.tscn"):
				splash_screen = node
				break

	if splash_screen:
		DebugManager.log_debug("SplashScreen node found: %s" % splash_screen.name, "Main")
		# Try connecting to the signal if it exists
		if splash_screen.has_signal("confirm_pressed"):
			splash_screen.confirm_pressed.connect(_on_confirm_pressed)
			DebugManager.log_debug("Connected to confirm_pressed signal", "Main")
		else:
			# Fallback: use input handling directly on the main scene
			DebugManager.log_warn("Using fallback input handling", "Main")
			_use_fallback_input_handling()
	else:
		DebugManager.log_error("Could not find SplashScreen node", "Main")
		_use_fallback_input_handling()


func _use_fallback_input_handling() -> void:
	# Fallback: handle input directly in the main scene
	set_process_unhandled_input(true)


func _unhandled_input(event: InputEvent) -> void:
	if splash_screen and splash_screen.is_inside_tree():
		# Forward input to splash screen or handle directly
		if event.is_action_pressed("action_confirm"):
			_on_confirm_pressed()
			get_viewport().set_input_as_handled()


func _on_confirm_pressed() -> void:
	DebugManager.log_debug("Transitioning to main menu", "Main")
	splash_screen.queue_free()
	show_main_menu()


func show_main_menu() -> void:
	clear_current_menu()
	var main_menu = MAIN_MENU_SCENE.instantiate()
	main_menu.open_settings.connect(_on_open_settings)
	add_child(main_menu)
	current_menu = main_menu


func show_settings_menu() -> void:
	clear_current_menu()
	var settings_menu = SETTINGS_MENU_SCENE.instantiate()
	settings_menu.back_to_main_menu.connect(_on_back_to_main_menu)
	add_child(settings_menu)
	current_menu = settings_menu


func clear_current_menu() -> void:
	if current_menu:
		current_menu.queue_free()
		current_menu = null


func _on_open_settings() -> void:
	DebugManager.log_debug("Opening settings menu", "Main")
	show_settings_menu()


func _on_back_to_main_menu() -> void:
	DebugManager.log_debug("Back to main menu", "Main")
	show_main_menu()
