export interface FloatingPositionParams {
  rect: DOMRect;
  popupWidth: number;
  popupHeight: number;
  viewportWidth: number;
  viewportHeight: number;
  margin?: number;
}

export interface FloatingPosition {
  top: number;
  left: number;
}

export const computeFloatingPosition = ({
  rect,
  popupWidth,
  popupHeight,
  viewportWidth,
  viewportHeight,
  margin = 8,
}: FloatingPositionParams): FloatingPosition => {
  const spaceBelow = viewportHeight - rect.bottom;
  const spaceAbove = rect.top;
  const verticalGap = margin;
  let top = rect.bottom + verticalGap;
  if (spaceBelow < popupHeight + verticalGap && spaceAbove >= popupHeight + verticalGap) {
    top = rect.top - popupHeight - verticalGap;
  }
  if (spaceBelow < popupHeight + verticalGap && spaceAbove < popupHeight + verticalGap) {
    top = Math.max(margin, viewportHeight - popupHeight - margin);
  }
  const clampedLeft = Math.min(
    Math.max(margin, rect.left),
    Math.max(margin, viewportWidth - popupWidth - margin)
  );
  return { top, left: clampedLeft };
};
