extends Node

@onready var back_button: Button = $BackButtonContainer/BackButton
const MATCH3_SCENE_PATH := "res://scenes/match3/match3.tscn"
var match3_instance: Node

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


func _on_back_button_pressed() -> void:
	AudioManager.play_ui_click()
	GameManager.save_game()
	if match3_instance and is_instance_valid(match3_instance):
		match3_instance.queue_free()
	GameManager.exit_to_main_menu()

func _load_match3_scene() -> void:
	var match3_scene := load(MATCH3_SCENE_PATH)
	if not match3_scene or not match3_scene is PackedScene:
		push_error("Failed to load Match3 scene at: %s" % MATCH3_SCENE_PATH)
		return

	match3_instance = match3_scene.instantiate()
	add_child(match3_instance)
