extends Node2D

@onready var camera = $Camera2D
const BASE_CAMERA_ZOOM: float = 4.0
const BASE_CAMERA_ZOOM_MOBILE: float = 5.5  # More zoomed in for mobile devices
const REFERENCE_ASPECT: float = 16.0 / 9.0

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	$Entities/Player.all_clients_ready = true
	$Entities/Player.controls_disabled = false
	$Entities/Player.is_local_player = true
	
	NetworkManager.is_hosting = true
	
	pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta: float) -> void:
	# Update camera to follow local players
	_update_camera()
	pass

func _update_camera():
	var local_players = [$Entities/Player]
	
	if local_players.is_empty():
		return
	
	# Calculate center of all local players
	var center = Vector2.ZERO
	for player in local_players:
		center += player.position
	center /= local_players.size()
	
	# Smooth camera movement
	camera.position = camera.position.lerp(center, 0.1)
	
	# Base zoom with aspect ratio adjustment (show more on wider screens)
	var viewport_size = get_viewport().get_visible_rect().size
	var aspect = viewport_size.x / max(1.0, viewport_size.y)
	var aspect_factor = 1.0
	if aspect > REFERENCE_ASPECT:
		# Wider than 16:9 -> zoom out to show more
		aspect_factor = REFERENCE_ASPECT / aspect
	
	# Detect mobile/touchscreen and use higher zoom for better visibility
	var is_mobile = false
	var os_name = OS.get_name().to_lower()
	if os_name in ["android", "ios"] or DisplayServer.is_touchscreen_available():
		is_mobile = true
	
	var base_zoom = BASE_CAMERA_ZOOM_MOBILE if is_mobile else BASE_CAMERA_ZOOM
	var target_zoom = base_zoom * aspect_factor
	
	# Adjust zoom based on player spread (for split-screen effect)
	if local_players.size() > 1:
		var max_distance = 0.0
		for player in local_players:
			var distance = center.distance_to(player.position)
			max_distance = max(max_distance, distance)
		
		# Adjust zoom to fit all players
		var spread_zoom = clamp(800.0 / (max_distance + 400.0), 0.5, 1.5)
		target_zoom *= spread_zoom
	
	# Always update zoom (for both single and multi-player)
	camera.zoom = camera.zoom.lerp(Vector2.ONE * target_zoom, 0.05)
