/**
 * useViewportChangeEffect
 *
 * Fires a callback when zoom or pan changes, debounced via rAF
 * to avoid per-frame spam during pinch/scroll gestures.
 */

import { useEffect, useRef } from 'react';
import { useAtomValue } from 'jotai';
import { zoomAtom, panAtom } from '../core/viewport-store';

export function useViewportChangeEffect(
	onViewportChange?: (viewport: { zoom: number; pan: { x: number; y: number } }) => void
) {
	const zoom = useAtomValue(zoomAtom);
	const pan = useAtomValue(panAtom);
	const rafRef = useRef<number | null>(null);
	const isFirstRender = useRef(true);

	useEffect(() => {
		if (isFirstRender.current) {
			isFirstRender.current = false;
			return;
		}
		if (!onViewportChange) return;

		if (rafRef.current !== null) {
			cancelAnimationFrame(rafRef.current);
		}
		rafRef.current = requestAnimationFrame(() => {
			onViewportChange({ zoom, pan });
			rafRef.current = null;
		});

		return () => {
			if (rafRef.current !== null) {
				cancelAnimationFrame(rafRef.current);
			}
		};
	}, [zoom, pan, onViewportChange]);
}
