-- this will need to be worked into a client schema later

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local CollectionService = game:GetService("CollectionService")
local Players = game:GetService("Players")

local taggedButtons = CollectionService:GetTagged("LightupButton")

local buttons = {}
local characters = {}

for _, button in pairs(taggedButtons) do
	buttons[button] = {
		active = false
	}
end


local function onPlayerAdded(player)
	player.CharacterAdded:Connect(function(character)
		repeat task.wait(.2) until character and character.PrimaryPart and character.Humanoid

		characters[player] = character
	end)
	player.CharacterRemoving:Connect(function(character)
		characters[player] = nil
	end)
end

Players.PlayerAdded:Connect(onPlayerAdded)

for _, player in pairs(Players:GetChildren()) do
	onPlayerAdded(player)
end


while true do
	local taggedButtons = CollectionService:GetTagged("LightupButton")

	for _, button in pairs(taggedButtons) do
		if buttons[button] == nil then
			buttons[button] = {
				active = false
			}
		end
	end
	
	for _, button in pairs(buttons) do
		button.active = false
	end
	
	for player, character in pairs(characters) do
		if character and character.PrimaryPart and character.Humanoid then
			local raycastParams = RaycastParams.new()
			raycastParams.FilterDescendantsInstances = taggedButtons
			raycastParams.FilterType = Enum.RaycastFilterType.Whitelist
			local raycastResult = workspace:Raycast(character.PrimaryPart.Position, Vector3.new(0, -6, 0), raycastParams)
			
			if raycastResult and raycastResult.Instance then
				if buttons[raycastResult.Instance] then
					buttons[raycastResult.Instance].active = true
				end
			end
		end
	end
	
	task.wait()
	
	for instance, button in pairs(buttons) do
		if button.active then
			instance.Material = Enum.Material.Neon
		else
			instance.Material = Enum.Material.Plastic
		end
	end
end
