local C=game:GetService("\082\101\112\108\105\099\097\116\101\100\083\116\111\114\097\103\101")local g=C:WaitForChild("\077\111\100\117\108\101\115")local q=require(g.src.utils.Logger)local h=require(g.src.utils.PlayerUtils)local x=game:GetService("\067\111\108\108\101\099\116\105\111\110\083\101\114\118\105\099\101")local t={}local e={}function t.create(C,g,q,t)local P=x:GetInstanceAddedSignal(g)local H=x:GetInstanceRemovedSignal(g)local function n(C)local g=false local function x(x)if h:isHuman(x)then local t=h:getPlayer(x)if t then if not g then q(t,x,C)g=true end end end end local t={}t.touchedConn=C.Touched:Connect(x)return t end local function l(C)C.touchedConn:Disconnect()end local function X(C)e[C]=n(C)end local function B(C)if e[C]then l(e[C])e[C]=nil end end for g,q in pairs(x:GetTagged(g))do if C then local g=require(q.Config)if g.roomId==C then X(q)end else X(q)end end P:Connect(X)H:Connect(B)end return t
local ReplicatedStorage = game:GetService('ReplicatedStorage')
local Modules = ReplicatedStorage:WaitForChild('Modules')
local logger = require(Modules.src.utils.Logger)
local PlayerUtils = require(Modules.src.utils.PlayerUtils)

local CollectionService = game:GetService('CollectionService')

local TagItemOnce = {}

local bricks = {}

function TagItemOnce.create(roomId, tagName, touchedFn, untouchedFn)
	local addedSignal = CollectionService:GetInstanceAddedSignal(tagName)
	local removedSignal = CollectionService:GetInstanceRemovedSignal(tagName)

	local function makeBrick(part)
		local hasTouched = false

		local function onTouchStart(hit)
			if PlayerUtils:isHuman(hit) then
				local player = PlayerUtils:getPlayer(hit)
				if player then
					if not hasTouched then
						touchedFn(player, hit, part)
						hasTouched = true
					end
				end
			end
		end

		local data = {}
		data.touchedConn = part.Touched:Connect(onTouchStart)

		return data
	end

	local function undoBrick(data)
		data.touchedConn:Disconnect()
	end

	local function onAdded(brick)
		bricks[brick] = makeBrick(brick)
	end

	local function onRemoved(brick)
		if bricks[brick] then
			undoBrick(bricks[brick])
			bricks[brick] = nil
		end
	end

	for _, brick in pairs(CollectionService:GetTagged(tagName)) do
		if roomId then
			local MapConfig = require(brick.Config)

			if MapConfig.roomId == roomId then
				onAdded(brick)
			end
		else
			onAdded(brick)
		end
	end

	addedSignal:Connect(onAdded)
	removedSignal:Connect(onRemoved)
end

return TagItemOnce