local C=game:GetService("\080\108\097\121\101\114\115")local J=game:GetService("\082\101\112\108\105\099\097\116\101\100\083\116\111\114\097\103\101")local E=require(J.Shared.components)local l=(require(J.Lib.Matter)).useEvent local f=Instance.new("\082\101\109\111\116\101\069\118\101\110\116")f.Name="\077\097\116\116\101\114\082\101\109\111\116\101"f.Parent=J local T={"\082\111\111\109\098\097","\077\111\100\101\108";"\072\101\097\108\116\104";"\084\097\114\103\101\116";"\077\111\116\104\101\114\115\104\105\112","\083\112\105\110\110\101\114"}local w={}for C,J in T do w[E[J]]=true end local function Z(J)for C,E in l(C,"\080\108\097\121\101\114\065\100\100\101\100")do local l={}for C,J in J do local E={}l[tostring(C)]=E for C,J in J do if w[C]then E[tostring(C)]={data=J}end end end print("\083\101\110\100\105\110\103 \105\110\105\116\105\097\108 \112\097\121\108\111\097\100 \116\111",E)f:FireClient(E,l)end local E={}for C in w do for l,f in J:queryChanged(C)do local T=tostring(l)local w=tostring(C)if E[T]==nil then E[T]={}end if J:contains(l)then E[T][w]={data=f.new}end end end if next(E)then f:FireAllClients(E)end end return{system=Z;priority=math.huge}
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Components = require(ReplicatedStorage.Shared.components)
local useEvent = require(ReplicatedStorage.Lib.Matter).useEvent

local RemoteEvent = Instance.new("RemoteEvent")
RemoteEvent.Name = "MatterRemote"
RemoteEvent.Parent = ReplicatedStorage

local REPLICATED_COMPONENTS = {
	"Roomba",
	"Model",
	"Health",
	"Target",
	"Mothership",
	"Spinner",
}

local replicatedComponents = {}

for _, name in REPLICATED_COMPONENTS do
	replicatedComponents[Components[name]] = true
end

local function replication(world)
	for _, player in useEvent(Players, "PlayerAdded") do
		local payload = {}

		for entityId, entityData in world do
			local entityPayload = {}
			payload[tostring(entityId)] = entityPayload

			for component, componentData in entityData do
				if replicatedComponents[component] then
					entityPayload[tostring(component)] = { data = componentData }
				end
			end
		end

		print("Sending initial payload to", player)
		RemoteEvent:FireClient(player, payload)
	end

	local changes = {}

	for component in replicatedComponents do
		for entityId, record in world:queryChanged(component) do
			local key = tostring(entityId)
			local name = tostring(component)

			if changes[key] == nil then
				changes[key] = {}
			end

			if world:contains(entityId) then
				changes[key][name] = { data = record.new }
			end
		end
	end

	if next(changes) then
		RemoteEvent:FireAllClients(changes)
	end
end

return {
	system = replication,
	priority = math.huge,
}
