/**
 * Performance Instrumentation
 *
 * Opt-in performance.mark / performance.measure wrappers for DevTools profiling.
 * All marks are prefixed with "canvas:" for easy filtering.
 *
 * Usage:
 *   const end = canvasMark('drag-frame');
 *   // ... work ...
 *   end(); // calls performance.measure automatically
 */

import { atom } from 'jotai';

/**
 * Whether performance instrumentation is enabled.
 * Off by default — set to true to see marks in DevTools Performance tab.
 */
export const perfEnabledAtom = atom(false);

// Module-level flag mirrored from atom for zero-overhead checks in hot paths.
// Updated by `setPerfEnabled`.
let _enabled = false;

/**
 * Imperatively set perf instrumentation on/off.
 * Useful from devtools console: `window.__canvasPerf?.(true)`.
 */
export function setPerfEnabled(enabled: boolean): void {
	_enabled = enabled;
}

// Expose on window for easy devtools access
if (typeof window !== 'undefined') {
	(window as unknown as Record<string, unknown>).__canvasPerf = setPerfEnabled;
}

/**
 * Start a performance mark. Returns a function that, when called,
 * creates a measure from the mark to the current time.
 *
 * When instrumentation is disabled, returns a no-op (zero overhead).
 */
export function canvasMark(name: string): () => void {
	if (!_enabled) return _noop;

	const markName = `canvas:${name}`;
	try {
		performance.mark(markName);
	} catch {
		return _noop;
	}

	return () => {
		try {
			performance.measure(`canvas:${name}`, markName);
		} catch {
			// mark may have been cleared
		}
	};
}

function _noop(): void {}

/**
 * Measure a synchronous function call.
 */
export function canvasWrap<T>(name: string, fn: () => T): T {
	const end = canvasMark(name);
	try {
		return fn();
	} finally {
		end();
	}
}
