const TOOLTIP_WIDTH = 320;
const TOOLTIP_HEIGHT_ESTIMATE = 180;
const VIEWPORT_MARGIN = 16;

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

export function getTooltipPosition(
  targetRect: DOMRect | null,
  viewport = { width: window.innerWidth, height: window.innerHeight },
  direction: 'ltr' | 'rtl' = (document.documentElement.dir === 'rtl' ? 'rtl' : 'ltr'),
): TooltipPosition {
  if (!targetRect) {
    const centeredLeft = Math.max(
      VIEWPORT_MARGIN,
      (viewport.width - TOOLTIP_WIDTH) / 2,
    );
    return {
      top: VIEWPORT_MARGIN + 64,
      left: direction === 'rtl'
        ? Math.min(viewport.width - TOOLTIP_WIDTH - VIEWPORT_MARGIN, centeredLeft)
        : centeredLeft,
    };
  }

  const preferredTop = targetRect.bottom + 12;
  const top = Math.min(
    Math.max(VIEWPORT_MARGIN, preferredTop),
    viewport.height - TOOLTIP_HEIGHT_ESTIMATE - VIEWPORT_MARGIN,
  );

  let left: number;
  if (direction === 'rtl') {
    left = Math.max(
      VIEWPORT_MARGIN,
      Math.min(targetRect.right - TOOLTIP_WIDTH, viewport.width - TOOLTIP_WIDTH - VIEWPORT_MARGIN),
    );
  } else {
    left = Math.min(
      Math.max(VIEWPORT_MARGIN, targetRect.left),
      viewport.width - TOOLTIP_WIDTH - VIEWPORT_MARGIN,
    );
  }

  return { top, left };
}
