export interface CanvasFrameSizeInput {
  availableWidth: number;
  availableHeight: number;
  viewWidth?: number | null;
  viewHeight?: number | null;
}

export interface CanvasFrameSize {
  w: number;
  h: number;
}

const positiveInteger = (value: unknown, fallback = 1): number => {
  const numeric = Number(value);
  return Number.isFinite(numeric) && numeric > 0
    ? Math.max(1, Math.floor(numeric))
    : fallback;
};

export const resolveCanvasFrameSize = ({
  availableWidth,
  availableHeight,
  viewWidth,
  viewHeight,
}: CanvasFrameSizeInput): CanvasFrameSize => {
  const available = {
    w: positiveInteger(availableWidth),
    h: positiveInteger(availableHeight),
  };

  const documentWidth = positiveInteger(viewWidth, 800);
  const documentHeight = positiveInteger(viewHeight, 600);
  const scale = Math.min(
    1,
    available.w / documentWidth,
    available.h / documentHeight,
  );

  return {
    w: positiveInteger(Math.round(documentWidth * scale)),
    h: positiveInteger(Math.round(documentHeight * scale)),
  };
};
