export function toolbarMenuPosition(
  anchor: { left: number; right: number; top: number; bottom: number },
  menu: { width: number; height: number },
  viewport: { width: number; height: number },
  align: "left" | "right" = "left",
) {
  const margin = 12;
  const gap = 10;
  const below = Math.max(0, viewport.height - anchor.bottom - gap - margin);
  const above = Math.max(0, anchor.top - gap - margin);
  const openAbove = menu.height > below && above > below;
  const maxHeight = openAbove ? above : below;
  const width = Math.min(menu.width, Math.max(0, viewport.width - margin * 2));
  const preferredLeft = align === "right" ? anchor.right - width : anchor.left;
  return {
    left: Math.max(margin, Math.min(preferredLeft, viewport.width - width - margin)),
    top: openAbove
      ? Math.max(margin, anchor.top - gap - Math.min(menu.height, maxHeight))
      : Math.max(margin, anchor.bottom + gap),
    maxHeight,
    maxWidth: Math.max(0, viewport.width - margin * 2),
  };
}
