Positioning tooltips robustly is fairly tricky since you need to consider not only the layout metrics of target element but also those of the browser window and the tooltip itself.
Luckily, there's a small library focused just on solving this problem called floating-ui. To use it, first import the API you'll need:
import {
computePosition,
autoPlacement,
offset,
shift
} from'@floating-ui/dom';
Normally, you'd also need to add @floating-ui/dom to your package.json but
to speed things up, that's already been done.
Now replace the positioning code with the floating-ui library code. The library API needs the target element, the tooltip element and has a bunch of options for how to setup positioning. It provides the x, y position for the tooltip via a Promise.
Now move your pointer over the boxes when they are near the bottom of the preview window. Its tooltip should be displayed above the box if there's more room for it there.