/**
 * Canvas Viewport Subscription Hook
 *
 * Provides reactive access to canvas viewport state (pan, zoom).
 * Use this to respond to viewport changes in your components.
 *
 * @example
 * ```tsx
 * function ZoomIndicator() {
 *   const { zoom, pan } = useCanvasViewport();
 *   return <div>Zoom: {Math.round(zoom * 100)}%</div>;
 * }
 * ```
 */

import { useAtomValue } from 'jotai';
import {
	zoomAtom,
	panAtom,
	viewportRectAtom,
	screenToWorldAtom,
	worldToScreenAtom,
	zoomFocusNodeIdAtom,
	zoomTransitionProgressAtom,
	isZoomTransitioningAtom,
	ZOOM_TRANSITION_THRESHOLD,
	ZOOM_EXIT_THRESHOLD,
} from '../core/viewport-store';
import type { PanOffset } from '../core/types';

export interface CanvasViewportState {
	/** Current zoom level (1 = 100%) */
	zoom: number;
	/** Current pan offset in pixels */
	pan: PanOffset;
	/** Viewport DOM rect (null if not mounted) */
	viewportRect: DOMRect | null;
	/** Convert screen coordinates to world coordinates */
	screenToWorld: (screenX: number, screenY: number) => { x: number; y: number };
	/** Convert world coordinates to screen coordinates */
	worldToScreen: (worldX: number, worldY: number) => { x: number; y: number };
	/** Node ID being zoomed into (for transitions) */
	zoomFocusNodeId: string | null;
	/** Zoom transition progress (0-1) */
	zoomTransitionProgress: number;
	/** Whether a zoom transition is in progress */
	isZoomTransitioning: boolean;
	/** Zoom level that triggers transition */
	zoomTransitionThreshold: number;
	/** Zoom level that exits transition */
	zoomExitThreshold: number;
}

/**
 * Subscribe to canvas viewport state.
 *
 * This hook provides a convenient way to access viewport state
 * without needing to know which atoms to import.
 */
export function useCanvasViewport(): CanvasViewportState {
	const zoom = useAtomValue(zoomAtom);
	const pan = useAtomValue(panAtom);
	const viewportRect = useAtomValue(viewportRectAtom);
	const screenToWorld = useAtomValue(screenToWorldAtom);
	const worldToScreen = useAtomValue(worldToScreenAtom);
	const zoomFocusNodeId = useAtomValue(zoomFocusNodeIdAtom);
	const zoomTransitionProgress = useAtomValue(zoomTransitionProgressAtom);
	const isZoomTransitioning = useAtomValue(isZoomTransitioningAtom);

	return {
		zoom,
		pan,
		viewportRect,
		screenToWorld,
		worldToScreen,
		zoomFocusNodeId,
		zoomTransitionProgress,
		isZoomTransitioning,
		zoomTransitionThreshold: ZOOM_TRANSITION_THRESHOLD,
		zoomExitThreshold: ZOOM_EXIT_THRESHOLD,
	};
}
