import { reactive } from 'vue'

export function useCanvasViewport() {
  const viewport = reactive({ scale: 1, x: 0, y: 0 })

  function fit(containerWidth: number, containerHeight: number, imageWidth: number, imageHeight: number): void {
    if (!imageWidth || !imageHeight) return
    viewport.scale = Math.min((containerWidth - 40) / imageWidth, (containerHeight - 40) / imageHeight, 1)
    viewport.scale = Math.max(0.02, viewport.scale)
    viewport.x = (containerWidth - imageWidth * viewport.scale) / 2
    viewport.y = (containerHeight - imageHeight * viewport.scale) / 2
  }

  function zoomAt(factor: number, x: number, y: number): void {
    const nextScale = Math.max(0.03, Math.min(24, viewport.scale * factor))
    const imageX = (x - viewport.x) / viewport.scale
    const imageY = (y - viewport.y) / viewport.scale
    viewport.x = x - imageX * nextScale
    viewport.y = y - imageY * nextScale
    viewport.scale = nextScale
  }

  return { viewport, fit, zoomAt }
}
