/**
 * External Keyboard Store
 *
 * Detects whether an external keyboard is connected to a touch device.
 * When detected, modifier-key actions become available via keyboard
 * shortcuts, so the TouchActionButton can be hidden.
 *
 * Detection: On touch devices, the first physical key event (not
 * on-screen keyboard) sets `hasExternalKeyboardAtom` to true.
 * Only meaningful when `isTouchDeviceAtom` is true — on desktop,
 * keyboard is always assumed.
 */

import { atom } from 'jotai';

/**
 * Whether an external keyboard has been detected on a touch device.
 * Set to true on first `keydown` event on a touch-capable device.
 */
export const hasExternalKeyboardAtom = atom(false);

/**
 * Effect atom: listens for keydown events on touch devices.
 * Once detected, stops listening (permanent for the session).
 */
export const watchExternalKeyboardAtom = atom(null, (get, set) => {
	if (typeof window === 'undefined') return;

	const handler = (e: KeyboardEvent) => {
		// Ignore virtual keyboard keys (typically modifier-only events)
		// A real keyboard sends identifiable key values
		if (e.key && e.key.length === 1 || ['Tab', 'Escape', 'Enter', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
			set(hasExternalKeyboardAtom, true);
			window.removeEventListener('keydown', handler);
		}
	};

	window.addEventListener('keydown', handler);
	return () => window.removeEventListener('keydown', handler);
});
