import { useCallback } from 'react'
import { useDominoStore, useDominoStoreInstance } from '../components/canvas'

export function useZoomActions(rootRef: React.RefObject<HTMLElement | null>) {
  const store = useDominoStoreInstance()
  const scale = useDominoStore(state => state.viewport.scale)

  const handleZoom = useCallback(
    (targetScale: number) => {
      const { viewport, zoomViewport } = store.getState()
      const multiplier = targetScale / viewport.scale
      const container = rootRef.current
      const centerX = (container?.offsetWidth || window.innerWidth) / 2
      const centerY = (container?.offsetHeight || window.innerHeight) / 2
      zoomViewport(multiplier, centerX, centerY, 0.02, 4)
    },
    [store, rootRef],
  )

  const stepZoom = useCallback(
    (delta: number) => {
      const { viewport } = store.getState()
      const step = Math.sign(delta) * 0.02
      const targetScale = Math.max(0.02, Math.min(4, viewport.scale + step))
      handleZoom(targetScale)
    },
    [store, handleZoom],
  )

  return {
    handleZoom,
    stepZoom,
    scale,
  }
}
