/**
 * The TV renders on a fixed 1920×1080 virtual canvas and is scaled to the real screen with a CSS
 * transform, so every layout is pixel-identical on a 720p bar TV, a 4K panel or a demo iframe.
 */
export const STAGE_WIDTH = 1920;
export const STAGE_HEIGHT = 1080;

export interface StageFit {
  /** Uniform scale applied to the 1920×1080 canvas. */
  scale: number;
  /** Letterbox offsets (screen px) that centre the scaled canvas. */
  offsetX: number;
  offsetY: number;
}

/**
 * Largest uniform scale that fits the canvas inside the viewport, centred (letterbox/pillarbox).
 * Offsets are floored to whole pixels so the canvas edge never lands on a half pixel.
 */
export function fitStage(viewportWidth: number, viewportHeight: number, stageWidth = STAGE_WIDTH, stageHeight = STAGE_HEIGHT): StageFit {
  if (!(viewportWidth > 0) || !(viewportHeight > 0) || !(stageWidth > 0) || !(stageHeight > 0)) {
    return { scale: 0, offsetX: 0, offsetY: 0 };
  }
  const scale = Math.min(viewportWidth / stageWidth, viewportHeight / stageHeight);
  return {
    scale,
    offsetX: Math.max(0, Math.floor((viewportWidth - stageWidth * scale) / 2)),
    offsetY: Math.max(0, Math.floor((viewportHeight - stageHeight * scale) / 2)),
  };
}
