import { createContext, type ReactNode, use } from "react";
import { useZoomPan, type ZoomPanResult } from "./useZoomPan.js";

let ZoomContext = createContext<ZoomPanResult | null>(null);

export function useZoom(): ZoomPanResult {
	let ctx = use(ZoomContext);
	if (!ctx) throw new Error("useZoom must be used within ZoomProvider");
	return ctx;
}

/**
 * Current zoom factor, or 1 when no ZoomProvider is present.
 * Lets tools convert screen-space coordinates to CSS pixels without requiring the zoom plugin.
 */
export function useZoomLevel(): number {
	return use(ZoomContext)?.zoom ?? 1;
}

export function ZoomProvider({ children }: { children: ReactNode }) {
	let state = useZoomPan();
	return <ZoomContext value={state}>{children}</ZoomContext>;
}
