/**
 * 屏幕自适应缩放：按大屏分辨率等比缩放，竖版游戏画面居中
 */

/** 当前缩放信息，供其他模块读取 */
let _scaleInfo = null

/**
 * 获取当前缩放信息（initScaler 调用后可用）
 * @returns {{ scale, offsetX, offsetY, designWidth, designHeight, displayWidth, displayHeight } | null}
 */
export function getScaleInfo() {
  return _scaleInfo
}

/**
 * 初始化并计算缩放参数，设置 canvas 尺寸
 * @param {Object} options
 * @param {number} options.designWidth  设计稿宽度
 * @param {number} options.designHeight 设计稿高度
 * @param {HTMLElement} options.containerEl 容器元素
 * @param {HTMLCanvasElement} options.canvasEl 画布元素
 * @returns {{ scale, offsetX, offsetY, designWidth, designHeight, displayWidth, displayHeight }}
 */
export function initScaler(options) {
  const { designWidth, designHeight, containerEl, canvasEl } = options
  const containerWidth = containerEl.clientWidth || window.innerWidth
  const containerHeight = containerEl.clientHeight || window.innerHeight

  const scaleX = containerWidth / designWidth
  const scaleY = containerHeight / designHeight
  const scale = Math.min(scaleX, scaleY)

  const displayWidth = Math.round(designWidth * scale)
  const displayHeight = Math.round(designHeight * scale)
  const offsetX = Math.round((containerWidth - displayWidth) / 2)
  const offsetY = Math.round((containerHeight - displayHeight) / 2)

  if (canvasEl) {
    canvasEl.width = designWidth
    canvasEl.height = designHeight
    canvasEl.style.width = `${displayWidth}px`
    canvasEl.style.height = `${displayHeight}px`
    canvasEl.style.position = 'absolute'
    canvasEl.style.left = `${offsetX}px`
    canvasEl.style.top = `${offsetY}px`
  }

  _scaleInfo = { scale, offsetX, offsetY, designWidth, designHeight, displayWidth, displayHeight }
  return _scaleInfo
}
