-- To avoid using .Activated for each slot we do this
-- better for optimization

local function onInputBegan(input: InputObject, processed)
	if not ScreenGui.Enabled then 
		return
	end
	
	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		for _, obj in ScreenGui.Parent:GetGuiObjectsAtPosition(input.Position.X, input.Position.Y) do
			if IsSlot(obj) then
				ChangeToolHold(obj)
				return
			end
		end
	end
	
	if processed then
		return
	end
	
	if input.KeyCode == Enum.KeyCode.Backquote then
		local tween = TweenService:Create(Backpack, TweenInfo.new(), {
			Size = if IsBackpackOpen
				then UDim2.fromScale(1, 0)
				else BackpackSize
		})
		
		IsBackpackOpen = not IsBackpackOpen
		Backpack.List.ScrollBarThickness = if IsBackpackOpen then 12 else 0
		
		tween:Destroy()
		tween:Play()
	elseif input.UserInputType == Enum.UserInputType.Keyboard then
		local value = input.KeyCode.Value - Enum.KeyCode.Zero.Value
		
		if value < 0 or value > 9 then
			return
		end
		
		local slot = HandleBar["Slot" .. value]
		ChangeToolHold(slot)
	end
end

for _, v in LocalPlayer.Backpack:GetChildren() do
	AddSlotObject(v)
end

LocalPlayer.Backpack.ChildAdded:Connect(doCheckAndReplaceTools)
LocalPlayer.Backpack.ChildRemoved:Connect(doCheckAndReplaceTools)
LocalPlayer.CharacterAdded:Connect(HandleCharacter)
UserInputService.InputBegan:Connect(onInputBegan)
