/*:
 * @target MV
 * @plugindesc 【拡張】SupponShopStockの通貨を変数で管理＆切り替え可能にします
 * @author Tokomagi
 *
 * @help
 * ◆概要
 * このプラグインは「SupponShopStock」の通貨処理を拡張し、
 * 「変数の値」を通貨として扱えるようにします。
 * さらに、プラグインコマンドで通貨変数・通貨単位を切り替えることができます。
 *
 * ▼初期設定
 * ・デフォルトでは通常の所持金（ゴールド）を使います。
 * ・プラグインコマンドで「通貨変数」を指定すると、その変数が通貨となります。
 *
 * ▼プラグインコマンド（MV）
 *   SupponCurrency setCurrencyVar 95
 *     → 通貨変数を「変数ID:95」に変更
 *   SupponCurrency setCurrencyUnit P
 *     → 通貨単位を「P」に変更
 */

(function() {
  
    const _Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand;
    Game_Interpreter.prototype.pluginCommand = function(command, args) {
      _Game_Interpreter_pluginCommand.call(this, command, args);
      if (command === 'SupponCurrency') {
        switch (args[0]) {
          case 'setCurrencyVar': {
            const varId = Number(args[1] || 0);
            $gameSystem._supponCurrencyVarId = varId;
            console.log('[SupponCurrency] 通貨変数IDを設定:', varId);
            break;
          }
          case 'setCurrencyUnit': {
            const unit = String(args[1] || 'G');
            $gameSystem._supponCurrencyUnit = unit;
            console.log('[SupponCurrency] 通貨単位を設定:', unit);
            break;
          }
        }
      }
    };
  
    const _Game_System_initialize = Game_System.prototype.initialize;
    Game_System.prototype.initialize = function() {
      _Game_System_initialize.call(this);
      this._supponCurrencyVarId = 0;
      this._supponCurrencyUnit = 'G';
    };
  
    const getSupponCurrencyUnit = function() {
      return $gameSystem._supponCurrencyUnit || 'G';
    };
  
    const getSupponCurrencyAmount = function() {
      const varId = $gameSystem._supponCurrencyVarId || 0;
      const amount = varId > 0 ? $gameVariables.value(varId) : $gameParty.gold();
      console.log('[SupponCurrency] 現在の通貨値:', amount);
      return amount;
    };
  
    const decreaseSupponCurrency = function(amount) {
      const varId = $gameSystem._supponCurrencyVarId || 0;
      if (varId > 0) {
        const now = $gameVariables.value(varId);
        $gameVariables.setValue(varId, now - amount);
        console.log(`[SupponCurrency] 変数${varId}から${amount}消費 → ${now - amount}`);
      } else {
        $gameParty.loseGold(amount);
        console.log(`[SupponCurrency] ゴールドから${amount}消費 → ${$gameParty.gold()}`);
      }
    };
  
    const _Window_ShopBuy_drawItem = Window_ShopBuy.prototype.drawItem;
    Window_ShopBuy.prototype.drawItem = function(index) {
      if (!SceneManager.isSupponSS()) {
        _Window_ShopBuy_drawItem.call(this, index);
        return;
      }
  
      const item = this._data[index];
      const rect = this.itemRect(index);
      const priceWidth = 96;
      rect.width -= this.textPadding();
  
      const stock = this._shopGoods[index][4] > 0
        ? $gameVariables.value(this._shopGoods[index][4])
        : this._shopGoods[index][5];
  
      this.changePaintOpacity(this.isEnabled(item) && stock > 0);
      this.drawItemName(item, rect.x, rect.y, rect.width - priceWidth);
  
      let text;
      if (stock > 0) {
        const price = this.price(item);
        text = `${price}${getSupponCurrencyUnit()}`;
      } else {
        text = '売り切れ';
      }
  
      this.drawText(text, rect.x + rect.width - priceWidth, rect.y, priceWidth, 'right');
      this.changePaintOpacity(true);
    };
  
    if (typeof Scene_supponSSshop === 'undefined') {
      console.warn('[SupponCurrency] Scene_supponSSshop is not ready yet. Deferring patch...');
      SceneManager._sceneSupponPatchWait = true;
      return; // 後でリトライ処理入れてもOK
  }

    Scene_supponSSshop.prototype.money = function() {
      return getSupponCurrencyAmount();
    };
  
    Scene_supponSSshop.prototype.doBuy = function(number) {
      const price = this.buyingPrice() * number;
      decreaseSupponCurrency(price);
      $gameParty.gainItem(this._item, number);
      this.processStockBuy(number);
    };
  })();