/**
 * useInputModeGestureContext — Syncs input mode → mapping context
 *
 * When the interaction store's inputModeAtom changes, this hook
 * pushes/removes the corresponding MappingContext from the gesture system.
 *
 * This follows Design Decision 5: context sync belongs in hooks.
 */

import { useEffect } from 'react';
import { useAtomValue } from 'jotai';
import { inputModeAtom } from '../core/interaction-store';
import { INPUT_MODE_CONTEXTS } from './contexts';
import type { InputSystemAPI } from './useGestureSystem';

const INPUT_MODE_CONTEXT_PREFIX = 'input-mode:';

/**
 * Sync the current input mode to a gesture mapping context.
 * Call this once at the Canvas level, passing the gesture system API.
 */
export function useInputModeGestureContext(inputSystem: InputSystemAPI): void {
	const inputMode = useAtomValue(inputModeAtom);

	useEffect(() => {
		const modeType = inputMode.type;
		const ctx = INPUT_MODE_CONTEXTS[modeType] ?? null;

		if (ctx) {
			inputSystem.pushContext(ctx);
		} else {
			// Remove any previously pushed input-mode context
			// We iterate known mode types to find which one to remove
			for (const key of Object.keys(INPUT_MODE_CONTEXTS)) {
				const existing = INPUT_MODE_CONTEXTS[key];
				if (existing) {
					inputSystem.removeContext(existing.id);
				}
			}
		}

		return () => {
			// Cleanup: remove the context when mode changes or unmounts
			if (ctx) {
				inputSystem.removeContext(ctx.id);
			}
		};
	}, [inputMode.type, inputSystem]);
}
