extends Node2D

@export var max_droplets: int = 100
@export var spawn_rate: float = 0.1
var spawn_timer: float = 0.1

func _physics_process(delta):
	var mm_node = $MultiMeshInstance2D
	var mm = mm_node.multimesh
	
	# 1. Get all current RigidBody2D children
	var fluid_bodies = get_children().filter(func(node): return node is RigidBody2D)
	
	# 2. FORCE MultiMesh to match the current body count
	# This is why they weren't 'registering'—the MultiMesh slot didn't exist yet!
	if mm.instance_count != fluid_bodies.size():
		mm.instance_count = fluid_bodies.size()

	# 3. Visual Sync
	for i in range(fluid_bodies.size()):
		var body = fluid_bodies[i]
		# Subtract the container's position so particles don't "drift"
		var t = Transform2D(0.0, body.global_position - global_position)
		mm.set_instance_transform_2d(i, t)

	# 4. Interaction (Surface Tension)
	for i in range(fluid_bodies.size()):
		for j in range(i + 1, fluid_bodies.size()):
			var b1 = fluid_bodies[i]
			var b2 = fluid_bodies[j]
			var dist_vec = b1.global_position - b2.global_position
			var dist = dist_vec.length()
			
			if dist < 40.0:
				var force = dist_vec.normalized() * 5.0
				b1.apply_central_force(-force)
				b2.apply_central_force(force)

	# 5. Spawning
	spawn_timer += delta
	if spawn_timer >= spawn_rate and fluid_bodies.size() < max_droplets:
		%SceneManager.addDropplet()
		mm.instance_count = fluid_bodies.size()
		spawn_timer = 0.0
