Hello
I didn’t go too deep into your code, but still there is one point which for sure is problematic : you are using euler rotations on your cubes, instead of Quaternion. If you need to rotate meshes of 90° in 3 axis, then forget about Euler Rotation, and go 100% Quaternion. Otherwise you will hit the gymbal lock issue. I would even say your project is the perfect example of a place where Quaternions are needed
Have a look at this topic in which I had explained a bit the problem :