/**
 * Attaches a document-level keydown listener that calls `onEscape` when Escape is pressed.
 * Returns the handler reference so it can be removed later via `detachEscHandler`.
 */
export function attachEscHandler (onEscape: () => void): (e: KeyboardEvent) => void {
  const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') onEscape() }
  document.addEventListener('keydown', handler)
  return handler
}

/**
 * Removes a previously attached Escape key handler from the document.
 * Returns null for easy inline cleanup: `this._escHandler = detachEscHandler(this._escHandler)`.
 */
export function detachEscHandler (handler: ((e: KeyboardEvent) => void) | null): null {
  if (handler) {
    document.removeEventListener('keydown', handler)
  }
  return null
}
