/**
 * usePlugin — React hook for plugin registration
 *
 * Registers a plugin on mount and unregisters on unmount.
 * Safe to call with the same plugin across re-renders — it
 * only registers once (keyed by plugin.id).
 */

import { useEffect, useRef } from 'react';
import type { CanvasPlugin } from '../core/plugin-types';
import { registerPlugin, unregisterPlugin, hasPlugin } from '../core/plugin-registry';

/**
 * Register a canvas plugin for the lifetime of the component.
 *
 * @example
 * ```tsx
 * const myPlugin: CanvasPlugin = {
 *   id: 'my-plugin',
 *   name: 'My Plugin',
 *   nodeTypes: { 'custom': CustomNode },
 * };
 *
 * function App() {
 *   usePlugin(myPlugin);
 *   return <Canvas ... />;
 * }
 * ```
 */
export function usePlugin(plugin: CanvasPlugin): void {
	const registeredRef = useRef(false);

	useEffect(() => {
		if (!hasPlugin(plugin.id)) {
			registerPlugin(plugin);
			registeredRef.current = true;
		}

		return () => {
			if (registeredRef.current && hasPlugin(plugin.id)) {
				try {
					unregisterPlugin(plugin.id);
				} catch {
					// Dependency conflict on unmount — plugin will be cleaned up later
				}
				registeredRef.current = false;
			}
		};
	}, [plugin.id]);
}

/**
 * Register multiple plugins at once.
 * Plugins are registered in order, so dependencies should come first.
 *
 * @example
 * ```tsx
 * usePlugins([basePlugin, extensionPlugin]);
 * ```
 */
export function usePlugins(plugins: CanvasPlugin[]): void {
	const registeredRef = useRef<string[]>([]);

	useEffect(() => {
		const registered: string[] = [];

		for (const plugin of plugins) {
			if (!hasPlugin(plugin.id)) {
				registerPlugin(plugin);
				registered.push(plugin.id);
			}
		}
		registeredRef.current = registered;

		return () => {
			// Unregister in reverse order (respect dependency order)
			for (const id of registeredRef.current.reverse()) {
				if (hasPlugin(id)) {
					try {
						unregisterPlugin(id);
					} catch {
						// Dependency conflict — skip
					}
				}
			}
			registeredRef.current = [];
		};
	}, [plugins.map((p) => p.id).join(',')]);
}
