extends Control

const GAMEPLAY_SCENES = {
	"match3": "res://scenes/game/gameplays/match3_gameplay.tscn",
	"clickomania": "res://scenes/game/gameplays/clickomania_gameplay.tscn"
}

@onready var back_button: Button = $BackButtonContainer/BackButton
@onready var gameplay_container: Control = $GameplayContainer
@onready var score_display: Label = $UI/ScoreDisplay

var current_gameplay_mode: String
var global_score: int = 0:
	set = set_global_score


func _ready() -> void:
	if not back_button.pressed.is_connected(_on_back_button_pressed):
		back_button.pressed.connect(_on_back_button_pressed)

	# GameManager will set the gameplay mode, don't set default here
	DebugManager.log_debug(
		"Game _ready() completed, waiting for GameManager to set gameplay mode", "Game"
	)


func set_gameplay_mode(mode: String) -> void:
	DebugManager.log_info("set_gameplay_mode called with mode: %s" % mode, "Game")
	current_gameplay_mode = mode
	await load_gameplay(mode)
	DebugManager.log_info("set_gameplay_mode completed for mode: %s" % mode, "Game")


func load_gameplay(mode: String) -> void:
	DebugManager.log_debug("Loading gameplay mode: %s" % mode, "Game")

	# Clear existing gameplay and wait for removal
	var existing_children = gameplay_container.get_children()
	if existing_children.size() > 0:
		DebugManager.log_debug("Removing %d existing children" % existing_children.size(), "Game")
		for child in existing_children:
			DebugManager.log_debug("Removing existing child: %s" % child.name, "Game")
			child.queue_free()

		# Wait for children to be properly removed from scene tree
		await get_tree().process_frame
		DebugManager.log_debug(
			"Children removal complete, container count: %d" % gameplay_container.get_child_count(),
			"Game"
		)

	# Load new gameplay
	if GAMEPLAY_SCENES.has(mode):
		DebugManager.log_debug("Found scene path: %s" % GAMEPLAY_SCENES[mode], "Game")
		var gameplay_scene = load(GAMEPLAY_SCENES[mode])
		var gameplay_instance = gameplay_scene.instantiate()
		DebugManager.log_debug("Instantiated gameplay: %s" % gameplay_instance.name, "Game")
		gameplay_container.add_child(gameplay_instance)
		DebugManager.log_debug(
			(
				"Added gameplay to container, child count now: %d"
				% gameplay_container.get_child_count()
			),
			"Game"
		)

		# Connect gameplay signals to shared systems
		if gameplay_instance.has_signal("score_changed"):
			gameplay_instance.score_changed.connect(_on_score_changed)
			DebugManager.log_debug("Connected score_changed signal", "Game")
	else:
		DebugManager.log_error("Gameplay mode '%s' not found in GAMEPLAY_SCENES" % mode, "Game")


func set_global_score(value: int) -> void:
	global_score = value
	if score_display:
		score_display.text = "Score: " + str(global_score)


func _on_score_changed(points: int) -> void:
	self.global_score += points
	SaveManager.update_current_score(self.global_score)


func get_global_score() -> int:
	return global_score


func _get_current_gameplay_instance() -> Node:
	if gameplay_container.get_child_count() > 0:
		return gameplay_container.get_child(0)
	return null


func _on_back_button_pressed() -> void:
	DebugManager.log_debug("Back button pressed in game scene", "Game")
	AudioManager.play_ui_click()

	# Save current grid state if we have an active match3 gameplay
	var gameplay_instance = _get_current_gameplay_instance()
	if gameplay_instance and gameplay_instance.has_method("save_current_state"):
		DebugManager.log_info("Saving grid state before exit", "Game")
		# Make sure the gameplay instance is still valid and not being destroyed
		if is_instance_valid(gameplay_instance) and gameplay_instance.is_inside_tree():
			gameplay_instance.save_current_state()
		else:
			DebugManager.log_warn("Gameplay instance invalid, skipping grid save on exit", "Game")

	# Save the current score immediately before exiting
	SaveManager.finish_game(global_score)
	GameManager.exit_to_main_menu()


func _input(event: InputEvent) -> void:
	if event.is_action_pressed("ui_back"):
		# Handle gamepad/keyboard back action - same as back button
		_on_back_button_pressed()
	elif event.is_action_pressed("action_south") and Input.is_action_pressed("action_north"):
		# Debug: Switch to clickomania when primary+secondary actions pressed together
		if current_gameplay_mode == "match3":
			set_gameplay_mode("clickomania")
			DebugManager.log_debug("Switched to clickomania gameplay", "Game")
		else:
			set_gameplay_mode("match3")
			DebugManager.log_debug("Switched to match3 gameplay", "Game")
