extends Control

# Store the current joystick input value
var virtual_joystick_input: Vector2 = Vector2.ZERO

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	_update_visibility()

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta: float) -> void:
	pass

func _update_visibility() -> void:
	# Check if touchscreen is available
	var has_touchscreen = DisplayServer.is_touchscreen_available()
	
	# Check if running on mobile platform
	var os_name = OS.get_name().to_lower()
	var is_mobile_os = os_name in ["android", "ios"]
	
	# Show mobile input if touchscreen is available OR if on mobile OS
	var should_show = has_touchscreen or is_mobile_os
	
	visible = should_show
	
	# Debug output (optional, can be removed)
	if Engine.is_editor_hint():
		return
	print("MobileInput visibility: ", should_show, " (touchscreen: ", has_touchscreen, ", mobile OS: ", is_mobile_os, ", OS: ", os_name, ")")


func _on_virtual_joystick_analogic_changed(value: Vector2, _distance: float, _angle: float, _angle_clockwise: float, _angle_not_clockwise: float) -> void:
	# Store the joystick input value
	# The value is already normalized (0.0 to 1.0) from the joystick
	virtual_joystick_input = value
	
	# Update all local players with the joystick input
	_update_player_input()

func _update_player_input():
	# Find all local players and set their virtual joystick input
	var game_world = get_tree().get_first_node_in_group("game_world")
	if not game_world:
		return
	
	var player_manager = game_world.get_node_or_null("PlayerManager")
	if not player_manager:
		return
	
	# Get all local players
	var local_players = player_manager.get_local_players()
	for player in local_players:
		if player and is_instance_valid(player):
			# Set the virtual joystick input on the player
			player.virtual_joystick_input = virtual_joystick_input
