extends Control

@onready var start_button: Button = $VBox/StartButton
@onready var leaderboard_button: Button = $VBox/LeaderboardButton
@onready var login_button: Button = $VBox/LoginButton
@onready var exit_button: Button = $VBox/ExitButton
var login_status_label: Label
var _last_logged_in: bool = false
var exit_dialog: ConfirmationDialog

func _ready():
	start_button.pressed.connect(_on_start_pressed)
	leaderboard_button.pressed.connect(_on_leaderboard_pressed)
	login_button.pressed.connect(_on_login_pressed)
	exit_button.pressed.connect(_on_exit_pressed)
	_ensure_login_status_label()
	_update_login_status()
	_find_login_button()
	_refresh_login_ui(true)
	_update_login_button()
	_create_exit_dialog()

func _on_start_pressed():
	get_tree().change_scene_to_file("res://scenes/LevelSelect.tscn")

func _on_leaderboard_pressed():
	get_tree().change_scene_to_file("res://scenes/Leaderboard.tscn")

func _on_login_pressed() -> void:
	get_tree().change_scene_to_file("res://scenes/LoginScene.tscn")


func _on_exit_pressed():
	exit_dialog.popup_centered()

func _process(_delta: float) -> void:
	_update_login_status()
	var gm := get_node_or_null("/root/GameManager")
	var logged_in := false
	if gm != null and gm.has_method("is_logged_in"):
		logged_in = bool(gm.call("is_logged_in"))

	if logged_in != _last_logged_in:
		_refresh_login_ui(true)

func _ensure_login_status_label() -> void:
	if login_status_label != null:
		return

	login_status_label = Label.new()
	login_status_label.name = "LoginStatus"
	login_status_label.add_theme_font_size_override("font_size", 18)
	login_status_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	login_status_label.autowrap_mode = TextServer.AUTOWRAP_WORD

	# noliekam augšā pa vidu
	login_status_label.anchor_left = 0
	login_status_label.anchor_right = 1
	login_status_label.anchor_top = 0
	login_status_label.anchor_bottom = 0
	login_status_label.offset_left = 0
	login_status_label.offset_right = 0
	login_status_label.offset_top = 18
	login_status_label.offset_bottom = 48

	add_child(login_status_label)

func _update_login_status() -> void:
	if login_status_label == null:
		return

	var gm := get_node_or_null("/root/GameManager")
	if gm == null:
		login_status_label.text = "User: guest"
		return

	var uname: String = "guest"
	var uid: int = 0

	if "current_username" in gm:
		uname = str(gm.get("current_username"))
	if "current_user_id" in gm:
		uid = int(gm.get("current_user_id"))

	if uid > 0 and uname.strip_edges() != "":
		login_status_label.text = "Logged in as: %s" % uname
	else:
		login_status_label.text = "Playing as: guest"

func _refresh_login_ui(_force: bool = false) -> void:
	var gm := get_node_or_null("/root/GameManager")
	var logged_in := false
	var uname := "guest"

	if gm != null:
		if "current_username" in gm:
			uname = str(gm.get("current_username"))
		if gm.has_method("is_logged_in"):
			logged_in = bool(gm.call("is_logged_in"))

	_last_logged_in = logged_in

	# status label
	if login_status_label != null:
		if logged_in and uname.strip_edges() != "":
			login_status_label.text = "Logged in as: %s" % uname
		else:
			login_status_label.text = "Playing as: guest"

	# button text
	if login_button != null:
		login_button.text = "Logout" if logged_in else "Login"

func _tree() -> SceneTree:
	return Engine.get_main_loop() as SceneTree

func _gm() -> Node:
	var t := _tree()
	if t == null:
		return null
	return t.root.get_node_or_null("GameManager")

func _goto_scene(path: String) -> void:
	var t := _tree()
	if t == null:
		return
	t.change_scene_to_file(path)

func _on_login_or_logout_pressed() -> void:
	if GameManager.current_username != "" and GameManager.current_username.to_lower() != "guest":
		GameManager.current_username = ""
		GameManager.current_user_id = 0
		login_button.text = "Login"
		login_status_label.text = "Guest"
	else:
		var modal_scene := preload("res://scenes/LoginModal.tscn")
		var modal := modal_scene.instantiate()
		add_child(modal)


func _find_login_button() -> void:
	login_button = find_child("LoginButton", true, false) as Button
	if login_button == null:
		login_button = find_child("Login", true, false) as Button
	if login_button == null:
		login_button = find_child("login", true, false) as Button

	if login_button != null:
		# nodrošinām, ka nav dubultas connect
		if not login_button.pressed.is_connected(_on_login_or_logout_pressed):
			login_button.pressed.connect(_on_login_or_logout_pressed)
	else:
		push_warning("MainMenu: Login button not found. (Name it LoginButton/Login/login)")

func _update_login_button() -> void:
	if GameManager.current_username != "" and GameManager.current_username.to_lower() != "guest":
		login_button.text = "Logout"
		login_status_label.text = "Logged in as: " + GameManager.current_username
	else:
		login_button.text = "Login"
		login_status_label.text = "Guest"

func _create_exit_dialog() -> void:
	exit_dialog = ConfirmationDialog.new()
	exit_dialog.title = "Exit game"
	exit_dialog.dialog_text = "Are you sure you want to exit?"
	add_child(exit_dialog)

	exit_dialog.confirmed.connect(func():
		get_tree().quit()
	)
	
