Compass suddenly flips heading during camera tilt from top of viewport

I’m implementing a compass overlay that rotates based on the camera heading. When users drag from the top of the viewport to tilt the camera, the compass suddenly flips between two headings (approximately 0° and 180°). This happens during the drag motion itself, not at any specific pitch angle, and only occurs when dragging from the top of the screen.

Here’s an example sandcastle of my implementation: Sandcastle

Has anyone encountered this behavior before or know what might be causing these sudden heading flips during top-down drag interactions? Is there a way to prevent that from happening?

Thanks in advance,
Shay