class_name ItemLootHelper
extends RefCounted

# Helper class for spawning Item instances as loot

# Spawn an Item instance as loot at a position
static func spawn_item_loot(item: Item, position: Vector2, entities_node: Node, game_world: Node = null) -> Node:
	if not item:
		push_error("ItemLootHelper: Cannot spawn null item!")
		return null
	
	var loot_scene = preload("res://scenes/loot.tscn")
	if not loot_scene:
		push_error("ItemLootHelper: Could not load loot.tscn scene!")
		return null
	
	# Generate deterministic random velocity for physics using dungeon seed
	# This ensures loot bounces the same on all clients
	var loot_rng = RandomNumberGenerator.new()
	var base_seed = 0
	if game_world and "dungeon_seed" in game_world:
		base_seed = game_world.dungeon_seed
	# Create unique seed for this loot item: dungeon_seed + position hash + counter
	# Use position hash to make seed unique per spawn location
	var pos_hash = hash(str(int(position.x)) + "_" + str(int(position.y)))
	var loot_seed = base_seed + pos_hash + 20000  # Offset to avoid collisions with enemy loot
	loot_rng.seed = loot_seed
	
	var random_angle = loot_rng.randf() * PI * 2
	var random_force = loot_rng.randf_range(25.0, 50.0)  # Reduced to half speed
	var random_velocity_z = loot_rng.randf_range(40.0, 60.0)  # Reduced to half speed
	var initial_velocity = Vector2(cos(random_angle), sin(random_angle)) * random_force
	
	# Find safe spawn position if game_world is provided
	var safe_spawn_pos = position
	if game_world and game_world.has_method("_find_nearby_safe_spawn_position"):
		safe_spawn_pos = game_world._find_nearby_safe_spawn_position(position, 64.0)
	
	# Spawn loot instance
	var loot = loot_scene.instantiate()
	if not entities_node:
		push_error("ItemLootHelper: entities_node is null!")
		return null
	
	# Set properties before adding to scene tree (to avoid physics state change errors)
	loot.global_position = safe_spawn_pos
	loot.loot_type = loot.LootType.ITEM
	loot.item = item  # Set the item instance
	# Set initial velocity before _ready() processes
	loot.velocity = initial_velocity
	loot.velocity_z = random_velocity_z
	loot.velocity_set_by_spawner = true
	loot.is_airborne = true
	
	# Add to scene tree using call_deferred to avoid physics state change errors
	entities_node.call_deferred("add_child", loot)
	
	# Set multiplayer authority to server if in multiplayer
	# Since this is a static helper function (RefCounted), we can't access the global multiplayer directly
	# Instead, check if game_world is provided and has the sync method (which implies multiplayer)
	# We'll also check if entities_node is in a scene tree with multiplayer
	var is_multiplayer = false
	if game_world and game_world.has_method("_sync_item_loot_spawn"):
		# If game_world has the sync method, we're likely in multiplayer
		# Use a script call to check multiplayer (game_world is a Node and has access to multiplayer)
		# We'll rely on the sync method existence as an indicator
		is_multiplayer = true
	
	if is_multiplayer:
		loot.set_multiplayer_authority(1)
		
		# Sync to clients if game_world is provided
		if game_world and game_world.has_method("_sync_item_loot_spawn"):
			# Generate unique loot ID
			# loot_id_counter is declared as a variable in game_world.gd, so it always exists
			var loot_id = game_world.loot_id_counter
			game_world.loot_id_counter += 1
			loot.set_meta("loot_id", loot_id)
			
			# Sync item data to clients
			game_world._rpc_to_ready_peers("_sync_item_loot_spawn", [safe_spawn_pos, item.save(), initial_velocity, random_velocity_z, loot_id])
	
	print("ItemLootHelper: Spawned item loot: ", item.item_name, " at ", safe_spawn_pos)
	return loot
