export type FloatingWindowLayerRect = {
  width?: number;
  height?: number;
};

export function clampFloatingWindowRect(
  layerRect: FloatingWindowLayerRect | null | undefined,
  left: unknown,
  top: unknown,
  width: unknown,
  height: unknown,
  minWidth: number,
  minHeight: number,
  defaultWidth: number,
  defaultHeight: number,
) {
  const safeWidth = Math.max(
    minWidth,
    Math.min(
      Math.max(minWidth, Number(width) || defaultWidth),
      Math.max(minWidth, (Number(layerRect?.width) || defaultWidth) - 12),
    ),
  );
  const safeHeight = Math.max(
    minHeight,
    Math.min(
      Math.max(minHeight, Number(height) || defaultHeight),
      Math.max(minHeight, (Number(layerRect?.height) || defaultHeight) - 12),
    ),
  );
  const maxLeft = Math.max(0, (Number(layerRect?.width) || safeWidth) - safeWidth);
  const maxTop = Math.max(0, (Number(layerRect?.height) || safeHeight) - safeHeight);
  return {
    left: Math.max(0, Math.min(maxLeft, Number(left) || 0)),
    top: Math.max(0, Math.min(maxTop, Number(top) || 0)),
    width: safeWidth,
    height: safeHeight,
  };
}
