extends Control
## Main Scene
##
## Entry point for the application.
## Displays loading screen with logged in player info.
## Provides "Play Now" and "Logout" buttons for authenticated users.

# Scene paths
const SCENE_LOGIN = "res://scenes/auth/login.tscn"
const SCENE_CHARACTER_LIST = "res://scenes/character/character_list.tscn"

# UI node references (from scene)
@onready var background_panel: Panel = $BackgroundPanel
@onready var title_label: Label = $CenterContainer/PanelContainer/MarginContainer/VBoxContainer/TitleLabel
@onready var welcome_label: Label = $CenterContainer/PanelContainer/MarginContainer/VBoxContainer/WelcomeLabel
@onready var status_label: Label = $CenterContainer/PanelContainer/MarginContainer/VBoxContainer/StatusLabel
@onready var button_container: HBoxContainer = $CenterContainer/PanelContainer/MarginContainer/VBoxContainer/ButtonContainer
@onready var play_now_button: Button = $CenterContainer/PanelContainer/MarginContainer/VBoxContainer/ButtonContainer/PlayNowButton
@onready var logout_button: Button = $CenterContainer/PanelContainer/MarginContainer/VBoxContainer/ButtonContainer/LogoutButton


func _ready() -> void:
	print("=== Code of Conquest Starting ===")
	print("Godot Version: ", Engine.get_version_info())
	print("Platform: ", OS.get_name())

	# Connect button signals
	play_now_button.pressed.connect(_on_play_now_pressed)
	logout_button.pressed.connect(_on_logout_pressed)

	# Initially hide buttons (will show after auth check)
	button_container.visible = false

	# Wait a frame for services to initialize
	await get_tree().process_frame

	# Check authentication status
	_check_authentication()



## Check if user is authenticated
func _check_authentication() -> void:
	if StateManager.is_authenticated():
		print("[Main] User is authenticated")

		# Get user info and display
		var user_data = StateManager.get_current_user()
		var username = user_data.get("email", user_data.get("name", "Player"))
		welcome_label.text = "Welcome, %s" % username

		status_label.text = "Validating session..."

		# Validate token with backend
		_validate_token()
	else:
		print("[Main] User not authenticated")
		welcome_label.text = "Not authenticated"
		status_label.text = "Please log in to continue"

		# Wait a moment then navigate to login
		await get_tree().create_timer(1.5).timeout
		_navigate_to_login()


## Validate auth token with backend
func _validate_token() -> void:
	# TODO: Replace with actual validation endpoint
	# For now, assume token is valid and show buttons

	print("[Main] Token validation not yet implemented")
	print("[Main] Assuming valid, showing play options...")

	# Uncomment when endpoint exists:
	# HTTPClient.http_get("/api/v1/auth/validate", _on_token_valid, _on_token_invalid)

	# For now, just show buttons (remove this when validation is implemented)
	await get_tree().create_timer(0.5).timeout
	_show_play_options()


## Show play/logout buttons
func _show_play_options() -> void:
	status_label.text = "Ready to play!"
	button_container.visible = true


## Handle valid token
func _on_token_valid(response: APIResponse) -> void:
	if response.is_success():
		print("[Main] Token is valid")
		_show_play_options()
	else:
		print("[Main] Token validation failed: ", response.get_error_message())
		_handle_invalid_token()


## Handle invalid token
#func _on_token_invalid(response: APIResponse) -> void:
	#print("[Main] Token invalid or network error")
	#_handle_invalid_token()


## Clear session and go to login
func _handle_invalid_token() -> void:
	status_label.text = "Session expired"
	welcome_label.text = "Please log in again"
	button_container.visible = false

	StateManager.clear_user_session()

	await get_tree().create_timer(1.5).timeout
	_navigate_to_login()


## Handle "Play Now" button press
func _on_play_now_pressed() -> void:
	print("[Main] Play Now button pressed")

	# Disable buttons during navigation
	button_container.visible = false
	status_label.text = "Loading characters..."

	# Navigate to character list
	_navigate_to_character_list()


## Handle "Logout" button press
func _on_logout_pressed() -> void:
	print("[Main] Logout button pressed")

	# Disable buttons
	button_container.visible = false
	status_label.text = "Logging out..."
	welcome_label.text = "Goodbye!"

	# Clear session
	StateManager.clear_user_session()

	# Wait a moment then navigate to login
	await get_tree().create_timer(1.0).timeout
	_navigate_to_login()


## Navigate to login scene
func _navigate_to_login() -> void:
	print("[Main] Navigating to login...")

	# Check if scene exists
	if not FileAccess.file_exists(SCENE_LOGIN):
		print("[Main] ERROR: Login scene not found at ", SCENE_LOGIN)
		status_label.text = "Login scene not yet created.\nSee Phase 2 in GETTING_STARTED.md"
		return

	# Navigate
	get_tree().change_scene_to_file(SCENE_LOGIN)


## Navigate to character list
func _navigate_to_character_list() -> void:
	print("[Main] Navigating to character list...")

	# Check if scene exists
	if not FileAccess.file_exists(SCENE_CHARACTER_LIST):
		print("[Main] ERROR: Character list scene not found at ", SCENE_CHARACTER_LIST)
		status_label.text = "Character list not yet created.\nSee Phase 3 in GETTING_STARTED.md"
		button_container.visible = true  # Re-show buttons
		return

	# Navigate
	get_tree().change_scene_to_file(SCENE_CHARACTER_LIST)
