import { useCallback } from 'react'
import { useDominoStore, useDominoStoreInstance } from './domino-hooks'
import type { Padding, ScrollIntoViewOptions, SceneElement } from './domino'
import { useDominoContainer } from './use-domino-container'
import { calculateZoomToFitTransform } from './math'

/**
 * Hook to zoom the Domino canvas to fit all elements.
 * (Internal hook, prefer using useDominoInstance)
 */
export function useDominoZoomToFit(
  explicitContainerRef?: React.RefObject<HTMLElement | null>,
) {
  const store = useDominoStoreInstance()
  const setViewport = useDominoStore(state => state.setViewport)
  const containerRef = useDominoContainer(explicitContainerRef)

  const zoomToFit = useCallback(
    (options?: Omit<ScrollIntoViewOptions, 'force' | 'scale'>) => {
      const container = containerRef?.current
      if (!container) return

      const { elements, padding: globalPadding } = store.getState()
      const elementList = Object.values(elements) as SceneElement[]
      if (elementList.length === 0) return

      const finalPadding = {
        top: options?.padding?.top ?? globalPadding.top ?? 0,
        right: options?.padding?.right ?? globalPadding.right ?? 0,
        bottom: options?.padding?.bottom ?? globalPadding.bottom ?? 0,
        left: options?.padding?.left ?? globalPadding.left ?? 0,
      } as Required<Padding>

      const nextViewport = calculateZoomToFitTransform(
        elementList,
        container.getBoundingClientRect(),
        finalPadding,
      )

      if (nextViewport) {
        setViewport(nextViewport)
      }
    },
    [setViewport, containerRef, store],
  )

  return zoomToFit
}
