export type UndoRedoShortcut = 'undo' | 'redo';

export function isEditableShortcutTarget(target: EventTarget | null): boolean {
  if (!(target instanceof HTMLElement)) return false;
  const tagName = target.tagName.toLowerCase();
  return target.isContentEditable || tagName === 'input' || tagName === 'textarea' || tagName === 'select';
}

function isKey(event: KeyboardEvent, key: 'z' | 'y'): boolean {
  return event.key.toLowerCase() === key || event.code === `Key${key.toUpperCase()}`;
}

export function getUndoRedoShortcut(event: KeyboardEvent): UndoRedoShortcut | null {
  if (isEditableShortcutTarget(event.target)) return null;
  if (!event.metaKey && !event.ctrlKey) return null;
  if (event.altKey) return null;

  if (isKey(event, 'z')) {
    return event.shiftKey ? 'redo' : 'undo';
  }
  if (isKey(event, 'y')) {
    return 'redo';
  }
  return null;
}
