import { useCanvasStore } from '../state/canvasStore'

export const useCanvas = () => {
  const { camX, camY, zoom, flying, dragging, collapsed, spacePanning } = useCanvasStore()

  const screenToWorld = (screenX: number, screenY: number) => {
    return {
      x: (screenX - window.innerWidth / 2) / zoom + camX,
      y: (screenY - window.innerHeight / 2) / zoom + camY,
    }
  }

  const worldToScreen = (worldX: number, worldY: number) => {
    return {
      x: (worldX - camX) * zoom + window.innerWidth / 2,
      y: (worldY - camY) * zoom + window.innerHeight / 2,
    }
  }

  const pan = (dx: number, dy: number) => {
    const { camX, camY } = useCanvasStore.getState()
    useCanvasStore.getState().setCam(camX - dx / zoom, camY - dy / zoom)
  }

  const zoomAt = (factor: number, centerX: number, centerY: number) => {
    const { zoom, camX, camY } = useCanvasStore.getState()
    const newZoom = Math.max(0.1, Math.min(5, zoom * factor))
    
    const worldCenter = screenToWorld(centerX, centerY)
    const newCamX = worldCenter.x - (centerX - window.innerWidth / 2) / newZoom
    const newCamY = worldCenter.y - (centerY - window.innerHeight / 2) / newZoom
    
    useCanvasStore.getState().setZoom(newZoom)
    useCanvasStore.getState().setCam(newCamX, newCamY)
  }

  return {
    camX,
    camY,
    zoom,
    flying,
    dragging,
    collapsed,
    spacePanning,
    screenToWorld,
    worldToScreen,
    pan,
    zoomAt,
  }
}
