I really need help to achieve this rotation

I have the first clip where I allowed only Y axis to rotate which looks like this.


I want X and Z axis to not be change when I rotated a part which looks something like this.

Added it together, this is the result. Here is the main thing I want to achieve.

The issue is when I rotated on X axis, the part flipped its direction.


However, when I rotated the Z axis, the part didn’t flip itself.

I’ve tried for hours and I can’t even solve this problem at all. I really need help on this issue. Here is the code.

local PartA = workspace.PartA
local PartB = workspace.PartB
local RunService = game:GetService("RunService")

RunService.Stepped:Connect(function()
    
    local TargetPartOrientationsY = PartA.Orientation.Y

    PartB.CFrame = CFrame.new(PartB.Position) * CFrame.Angles(0,math.rad(TargetPartOrientationsY),0)

end)

Search ‘gimbal lock’ on the forums for solutions.
When you rotate a CFrame by a factor of 90 degrees it can align 2 of the axes and cause issues like this.

How can you prevent this from happening? What functions do I use to fix this issue?

I don’t have your answer, but those other posts do.