import { useCallback, useEffect } from 'react';
export function useKeyboard(options) {
    const { isOpen, onOpen, onClose, onSelectNext, onSelectPrev, onEnter, disableShortcut = false, shortcutKey = 'k', } = options;
    const handleGlobalKeyDown = useCallback((event) => {
        if (!disableShortcut && (event.metaKey || event.ctrlKey) && event.key.toLowerCase() === shortcutKey) {
            event.preventDefault();
            if (isOpen) {
                onClose();
            }
            else {
                onOpen();
            }
            return;
        }
        if (!disableShortcut && event.key === '/' && !isOpen) {
            const target = event.target;
            const isInput = target.tagName === 'INPUT' ||
                target.tagName === 'TEXTAREA' ||
                target.isContentEditable;
            if (!isInput) {
                event.preventDefault();
                onOpen();
            }
        }
    }, [isOpen, onOpen, onClose, disableShortcut, shortcutKey]);
    const handleModalKeyDown = useCallback((event) => {
        switch (event.key) {
            case 'Escape':
                event.preventDefault();
                onClose();
                break;
            case 'ArrowDown':
                event.preventDefault();
                onSelectNext();
                break;
            case 'ArrowUp':
                event.preventDefault();
                onSelectPrev();
                break;
            case 'Enter':
                event.preventDefault();
                onEnter();
                break;
            case 'Tab':
                if (event.shiftKey) {
                    onSelectPrev();
                }
                else {
                    onSelectNext();
                }
                event.preventDefault();
                break;
        }
    }, [onClose, onSelectNext, onSelectPrev, onEnter]);
    useEffect(() => {
        document.addEventListener('keydown', handleGlobalKeyDown);
        return () => {
            document.removeEventListener('keydown', handleGlobalKeyDown);
        };
    }, [handleGlobalKeyDown]);
    return {
        handleModalKeyDown,
    };
}
export function getShortcutText(key = 'K') {
    if (typeof navigator === 'undefined') {
        return `⌘${key}`;
    }
    const isMac = navigator.platform.toLowerCase().includes('mac');
    return isMac ? `⌘${key}` : `Ctrl+${key}`;
}
