/*!
 * KeyGuard — 游戏方向键守卫（UMD）
 * ------------------------------------------------------------------
 * 决定键盘方向键 / WASD 是否应作为「迷宫移动」处理：
 *   - 焦点位于 INPUT / TEXTAREA / SELECT / contenteditable 元素内：忽略（还给输入框）
 *   - 按下含 meta / ctrl / alt 的组合键（如 Cmd+A、Ctrl+A）：忽略
 *   - 其余只用 key 判断是否为移动键，命中才交给游戏并允许 preventDefault
 *
 * 可用环境：
 *   - 浏览器：<script src="keyguard.js"></script> → window.KeyGuard
 *   - Node：   require('./keyguard.js')
 * ------------------------------------------------------------------
 */
(function (root, factory) {
  'use strict';
  if (typeof module === 'object' && module.exports) {
    module.exports = factory();
  } else if (typeof define === 'function' && define.amd) {
    define([], factory);
  } else {
    root.KeyGuard = factory();
  }
})(typeof self !== 'undefined' ? self : this, function () {
  'use strict';

  // 移动键（统一取 e.key 小写）→ [dx, dy]
  var MOVE_KEYS = {
    arrowup: [0, -1],
    w: [0, -1],
    arrowdown: [0, 1],
    s: [0, 1],
    arrowleft: [-1, 0],
    a: [-1, 0],
    arrowright: [1, 0],
    d: [1, 0]
  };

  /**
   * 判断事件目标是否为「文本编辑类」元素。
   */
  function isEditableTarget(target) {
    if (!target || typeof target !== 'object') return false;
    var tag = (target.tagName || '').toUpperCase();
    if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;
    if (target.isContentEditable === true) return true;
    return false;
  }

  /**
   * 该键盘事件是否应当被游戏忽略（不拦截、不移动）。
   * 含 meta/ctrl/alt 修饰、或目标在编辑控件内时返回 true。
   */
  function shouldIgnore(ev) {
    if (!ev) return true;
    if (ev.metaKey || ev.ctrlKey || ev.altKey) return true;
    return isEditableTarget(ev.target || ev.srcElement || null);
  }

  /**
   * 从键盘事件解析移动方向；非移动键或无效事件返回 null。
   */
  function gameKeyDelta(ev) {
    if (!ev || typeof ev.key !== 'string' || ev.key === '') return null;
    return MOVE_KEYS[ev.key.toLowerCase()] || null;
  }

  /**
   * 核心分发：
   *   - 应忽略 → 返回 false（调用方不应 preventDefault，也不应触发移动）
   *   - 移动键 → onMove(dx, dy) 后返回 true（调用方 preventDefault）
   *   - 其他键 → 返回 false
   */
  function handleGameKey(ev, onMove) {
    if (shouldIgnore(ev)) return false;
    var d = gameKeyDelta(ev);
    if (!d) return false;
    if (typeof onMove === 'function') onMove(d[0], d[1]);
    return true;
  }

  return {
    VERSION: '1.0.0',
    MOVE_KEYS: MOVE_KEYS,
    isEditableTarget: isEditableTarget,
    shouldIgnore: shouldIgnore,
    gameKeyDelta: gameKeyDelta,
    handleGameKey: handleGameKey
  };
});