import type { CommandExecutor } from '../utils/commands'

interface KeyboardShortcut {
	key: string
	modifiers?: {
		ctrl?: boolean
		alt?: boolean
		shift?: boolean
	}
	command: string
}

const shortcuts: KeyboardShortcut[] = [
	{ key: 'b', command: 'bold' },
	{ key: 'i', command: 'italic' },
	{ key: 'u', command: 'underline' },
	{ key: 'k', command: 'link' },
	{ key: 'z', command: 'undo' },
	{ key: 'z', modifiers: { shift: true }, command: 'redo' },
	{ key: 'y', command: 'redo' },
	{ key: '.', modifiers: { shift: true }, command: 'orderedList' },
	{ key: '/', modifiers: { shift: true }, command: 'unorderedList' },
	{ key: ']', command: 'indent' },
	{ key: '[', command: 'outdent' },
	...Array.from({ length: 6 }, (_, i) => ({
		key: String(i + 1),
		modifiers: { alt: true },
		command: `h${i + 1}`
	}))
]

export function useEditorKeyboard(doc: Document, executor: CommandExecutor): void {
	// Handle keyboard shortcuts
	doc.addEventListener('keydown', (e) => {
		// Remove Enter key handling from here - it's handled in setupAutoWrapping in index.vue
		// This was causing conflicts with the main Enter key handler

		// Handle other keyboard shortcuts
		if (!e.ctrlKey && !e.metaKey) { return }

		const matchingShortcut = shortcuts.find((shortcut) => {
			const keyMatch = shortcut.key === e.key
			const modifiersMatch = !shortcut.modifiers || (
				(!shortcut.modifiers.ctrl || e.ctrlKey || e.metaKey)
				&& (!shortcut.modifiers.alt || e.altKey)
				&& (!shortcut.modifiers.shift || e.shiftKey)
			)
			return keyMatch && modifiersMatch
		})

		if (matchingShortcut) {
			e.preventDefault()
			executor.execute(matchingShortcut.command)
		}
	})
}
