/**
 * useVirtualization Hook
 *
 * Provides virtualization metrics and controls for debugging and monitoring.
 * Useful for performance tuning and understanding what's being rendered.
 */

import { useAtomValue, useSetAtom } from 'jotai';
import {
	virtualizationMetricsAtom,
	type VisibleBounds,
} from '../core/virtualization-store';
import {
	setVirtualizationEnabledAtom,
	toggleVirtualizationAtom,
} from '../core/settings-store';

export interface VirtualizationMetrics {
	/** Whether virtualization is currently enabled */
	enabled: boolean;
	/** Total number of nodes in the graph */
	totalNodes: number;
	/** Total number of edges in the graph */
	totalEdges: number;
	/** Number of nodes currently being rendered */
	visibleNodes: number;
	/** Number of edges currently being rendered */
	visibleEdges: number;
	/** Number of nodes culled (not rendered) */
	culledNodes: number;
	/** Number of edges culled (not rendered) */
	culledEdges: number;
	/** Current visible bounds in world coordinates, or null if unavailable */
	bounds: VisibleBounds | null;
}

export interface UseVirtualizationReturn extends VirtualizationMetrics {
	/** Enable virtualization */
	enable: () => void;
	/** Disable virtualization (render all nodes/edges) */
	disable: () => void;
	/** Toggle virtualization on/off */
	toggle: () => void;
}

/**
 * Hook for accessing virtualization state and controls.
 *
 * @example
 * ```tsx
 * function PerformanceMonitor() {
 *   const {
 *     enabled,
 *     visibleNodes,
 *     totalNodes,
 *     culledNodes,
 *     toggle
 *   } = useVirtualization();
 *
 *   return (
 *     <div>
 *       <p>Rendering {visibleNodes}/{totalNodes} nodes ({culledNodes} culled)</p>
 *       <button onClick={toggle}>
 *         {enabled ? 'Disable' : 'Enable'} Virtualization
 *       </button>
 *     </div>
 *   );
 * }
 * ```
 */
export function useVirtualization(): UseVirtualizationReturn {
	const metrics = useAtomValue(virtualizationMetricsAtom);
	const setEnabled = useSetAtom(setVirtualizationEnabledAtom);
	const toggle = useSetAtom(toggleVirtualizationAtom);

	return {
		...metrics,
		enable: () => setEnabled(true),
		disable: () => setEnabled(false),
		toggle,
	};
}
