-- Cache common functions to avoid unnecessary table lookups

local TableInsert, NewVector3 = table.insert, Vector3.new

function GetCornerOffsets(Origin, InitialStates)
	-- Calculates and returns the offset of every corner in the initial state from the origin CFrame

	local CornerOffsets = {}

	-- Get offset for origin point
	local OriginOffset = Origin:inverse()

	-- Go through each item in the initial state
	for Item, State in pairs(InitialStates) do
		local ItemCFrame = State.CFrame
		local SizeX, SizeY, SizeZ = Item.Size.X / 2, Item.Size.Y / 2, Item.Size.Z / 2

		-- Gather each corner
		TableInsert(CornerOffsets, OriginOffset * (ItemCFrame * NewVector3(SizeX, SizeY, SizeZ)))
		TableInsert(CornerOffsets, OriginOffset * (ItemCFrame * NewVector3(-SizeX, SizeY, SizeZ)))
		TableInsert(CornerOffsets, OriginOffset * (ItemCFrame * NewVector3(SizeX, -SizeY, SizeZ)))
		TableInsert(CornerOffsets, OriginOffset * (ItemCFrame * NewVector3(SizeX, SizeY, -SizeZ)))
		TableInsert(CornerOffsets, OriginOffset * (ItemCFrame * NewVector3(-SizeX, SizeY, -SizeZ)))
		TableInsert(CornerOffsets, OriginOffset * (ItemCFrame * NewVector3(-SizeX, -SizeY, SizeZ)))
		TableInsert(CornerOffsets, OriginOffset * (ItemCFrame * NewVector3(SizeX, -SizeY, -SizeZ)))
		TableInsert(CornerOffsets, OriginOffset * (ItemCFrame * NewVector3(-SizeX, -SizeY, -SizeZ)))
	end

	-- Return the offsets
	return CornerOffsets

end

function FreeDragging:InstallDragEndListener()
    Support.AddUserInputListener('Ended', {'Touch', 'MouseButton1'}, true, function (Input)

        -- Clear drag detection data
        self.StartScreenPoint = nil
        self.StartTarget = nil
        ContextActionService:UnbindAction 'BT: Watch for dragging'

        -- Reset from drag mode if dragging
        if self.IsDragging then

            -- Reset axes
            self.Tool:SetAxes(self.Tool.Axes)

            -- Finalize the dragging operation
            self:FinishDragging()

        end

    end)
end

return FreeDragging
