/** Keys that are modifiers only — never annotated on their own. */
const MODIFIER_ONLY_KEYS = new Set(['Control', 'Shift', 'Alt', 'Meta', 'CapsLock']);

export function isEditableTarget(target: EventTarget | null): boolean {
  if (!(target instanceof HTMLElement)) return false;
  const tag = target.tagName;
  return tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA' || target.isContentEditable;
}

export function keyCode(event: KeyboardEvent): string {
  return event.code;
}

export function hasShortcutModifier(event: KeyboardEvent): boolean {
  return event.ctrlKey || event.metaKey;
}

export function keyLabel(event: KeyboardEvent): string | null {
  if (hasShortcutModifier(event)) return null;
  if (MODIFIER_ONLY_KEYS.has(event.key)) return null;
  if (event.key.length === 1) return event.key;
  if (event.key === ' ') return 'Space';
  return event.key;
}

export function shouldOverrideSelected(event: KeyboardEvent, hasSelection: boolean): boolean {
  if (!hasSelection) return false;
  if (hasShortcutModifier(event)) return false;
  if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(event.key)) return false;
  return keyLabel(event) !== null;
}

export function shouldRecordMarker(event: KeyboardEvent): boolean {
  if (event.repeat) return false;
  if (hasShortcutModifier(event)) return false;
  return keyLabel(event) !== null;
}

export function shouldDeleteSelected(event: KeyboardEvent, hasSelection: boolean): boolean {
  if (!hasSelection) return false;
  return event.key === 'Backspace' || event.key === 'Delete';
}
