//=============================================================================
// CursorWrapEX.js
// アイテム／装備／スキルリストで上下キーでカーソルループ（2列対応）
//=============================================================================

(function() {

  function wrapCursorUp(window, prevIndex) {
    const maxItems = window.maxItems();
    const maxCols = window.maxCols();

    // カーソルが動かなかったとき（最上段）だけ処理
    if (window.index() === prevIndex && prevIndex < maxCols) {
      const lastRow = Math.floor((maxItems - 1) / maxCols);
      let newIndex = (prevIndex % maxCols) + lastRow * maxCols;
      if (newIndex >= maxItems) newIndex -= maxCols;
      window.select(newIndex);
    }
  }

  function wrapCursorDown(window, prevIndex) {
    const maxItems = window.maxItems();
    const maxCols = window.maxCols();
    const nextIndex = prevIndex + maxCols;

    // カーソルが動かなかったとき（最下段）だけ処理
    if (window.index() === prevIndex && nextIndex >= maxItems) {
      const newIndex = prevIndex % maxCols;
      window.select(newIndex);
    }
  }

  function patchCursorWrap(targetClass) {
    const _cursorUp = targetClass.prototype.cursorUp;
    const _cursorDown = targetClass.prototype.cursorDown;

    targetClass.prototype.cursorUp = function(wrap) {
      const prevIndex = this.index();
      _cursorUp.call(this, wrap);
      if (wrap !== false) wrapCursorUp(this, prevIndex);
    };

    targetClass.prototype.cursorDown = function(wrap) {
      const prevIndex = this.index();
      _cursorDown.call(this, wrap);
      if (wrap !== false) wrapCursorDown(this, prevIndex);
    };
  }

  patchCursorWrap(Window_ItemList);
  patchCursorWrap(Window_SkillList);
  patchCursorWrap(Window_EquipSlot);

})();
