extends Control

const AUTH_LOGOUT_URL := "https://pauth.ranaze.com/api/Auth/logout"

@onready var _login_button: Button = $MarginContainer/CenterContainer/ContentVBox/VBoxContainer/LogInButton
@onready var _logout_request: HTTPRequest = %LogoutRequest

func _ready():
	_register_focus_sounds()
	_update_login_button()

func _register_focus_sounds() -> void:
	var button_container := $MarginContainer/CenterContainer/ContentVBox/VBoxContainer
	for child in button_container.get_children():
		if child is BaseButton:
			var button: BaseButton = child
			if not button.is_connected("focus_entered", Callable(self, "_on_menu_item_focus")):
				button.focus_entered.connect(_on_menu_item_focus)
			if not button.is_connected("mouse_entered", Callable(self, "_on_menu_item_focus")):
				button.mouse_entered.connect(_on_menu_item_focus)

func _on_start_button_pressed():
	get_tree().change_scene_to_file("uid://dchj6g2i8ebph")

func _on_settings_button_pressed():
	get_tree().change_scene_to_file("uid://d3tqrm4ry4l88")

func _on_quit_button_pressed():
	get_tree().quit()

func _on_log_in_button_pressed():
	if AuthState.is_logged_in:
		_request_logout()
	else:
		get_tree().change_scene_to_file("res://scenes/UI/login_screen.tscn")

func _on_menu_item_focus() -> void:
	if MenuSfx:
		MenuSfx.play_hover()

func _request_logout() -> void:
	if AuthState.access_token.is_empty():
		AuthState.clear_session()
		_update_login_button()
		return
	var headers := PackedStringArray([
		"Authorization: Bearer %s" % AuthState.access_token,
	])
	var err := _logout_request.request(AUTH_LOGOUT_URL, headers, HTTPClient.METHOD_POST)
	if err != OK:
		push_warning("Failed to send logout request: %s" % err)
		AuthState.clear_session()
		_update_login_button()

func _on_logout_request_completed(result: int, response_code: int, _headers: PackedStringArray, body: PackedByteArray) -> void:
	var body_text := body.get_string_from_utf8()
	if result != HTTPRequest.RESULT_SUCCESS or response_code < 200 or response_code >= 300:
		push_warning("Logout failed (%s/%s): %s" % [result, response_code, body_text])
	AuthState.clear_session()
	_update_login_button()

func _update_login_button() -> void:
	if AuthState.is_logged_in:
		_login_button.text = "LOG OUT"
	else:
		_login_button.text = "LOG IN"

func _on_secret_button_pressed():
	get_tree().change_scene_to_file("uid://q4abhlwqdvay")
