/*:
 * @plugindesc 敵キャラに職業based能力値とレベルシステムを追加し、3つのカスタムステータスウィンドウを表示します。
 * @author えむうん
 * @target MZ
 *
 * @param Window Settings
 * @desc ステータスウィンドウの設定
 * 
 * @param HP/MP Window X
 * @parent Window Settings
 * @desc HP/MPウィンドウのX座標
 * @type number
 * @default 0
 *
 * @param HP/MP Window Y
 * @parent Window Settings
 * @desc HP/MPウィンドウのY座標
 * @type number
 * @default 0
 *
 * @param HP/MP Window Width
 * @parent Window Settings
 * @desc HP/MPウィンドウの幅
 * @type number
 * @default 300
 *
 * @param HP/MP Window Height
 * @parent Window Settings
 * @desc HP/MPウィンドウの高さ
 * @type number
 * @default 100
 *
 * @param Name/Level Window X
 * @parent Window Settings
 * @desc 名前/レベルウィンドウのX座標
 * @type number
 * @default 0
 *
 * @param Name/Level Window Y
 * @parent Window Settings
 * @desc 名前/レベルウィンドウのY座標
 * @type number
 * @default 110
 *
 * @param Name/Level Window Width
 * @parent Window Settings
 * @desc 名前/レベルウィンドウの幅
 * @type number
 * @default 300
 *
 * @param Name/Level Window Height
 * @parent Window Settings
 * @desc 名前/レベルウィンドウの高さ
 * @type number
 * @default 72
 *
 * @param Stats Window X
 * @parent Window Settings
 * @desc 能力値ウィンドウのX座標
 * @type number
 * @default 0
 *
 * @param Stats Window Y
 * @parent Window Settings
 * @desc 能力値ウィンドウのY座標
 * @type number
 * @default 192
 *
 * @param Stats Window Width
 * @parent Window Settings
 * @desc 能力値ウィンドウの幅
 * @type number
 * @default 300
 *
 * @param Stats Window Height
 * @parent Window Settings
 * @desc 能力値ウィンドウの高さ
 * @type number
 * @default 180
 *
 * @param Window Opacity
 * @parent Window Settings
 * @desc ウィンドウの不透明度 (0-255)。0で完全透明、255で完全不透明。
 * @type number
 * @min 0
 * @max 255
 * @default 255
 *
 * @param Display Stats
 * @desc 表示するステータス
 * @type select[]
 * @option 攻撃力
 * @value atk
 * @option 防御力
 * @value def
 * @option 魔法力
 * @value mat
 * @option 魔法防御
 * @value mdf
 * @option 敏捷性
 * @value agi
 * @option 運
 * @value luk
 * @default ["atk","def","mat","mdf","agi","luk"]
 *
 * @param Status Window Switch ID
 * @desc ステータスウィンドウの表示/非表示を制御するスイッチのID
 * @type switch
 * @default 1
 *
 * @param Debug Mode
 * @desc デバッグログを有効にする（true）または無効にする（false）
 * @type boolean
 * @default false
 *
 * @command ShowEnemyStatus
 * @text 敵キャラステータス表示
 * @desc 指定した敵キャラのステータスを表示します
 *
 * @arg enemyId
 * @type number
 * @text 敵キャラID
 * @desc 表示する敵キャラのID（0の場合、トループの先頭の敵を表示）
 *
 * @help
 * このプラグインは、敵キャラに職業ベースの能力値とレベルシステムを追加し、
 * 3つのカスタムステータスウィンドウを表示します。
 * さらに、ステータスをゲージで視覚的に表示します。
 * 
 * プラグインコマンド:
 * ShowEnemyStatus enemyId
 * 
 * 例: ShowEnemyStatus 1
 * 敵キャラID 1 のステータスを表示します。
 * enemyId に 0 を指定すると、現在のトループの先頭の敵のステータスを表示します。
 * 
 * メモタグ:
 * 敵キャラのメモ欄に以下を記述することで、デフォルトの職業とレベルを設定できます。
 * <EnemyClass:3>  # デフォルトの職業IDを3に設定
 * <EnemyLevel:10> # デフォルトのレベルを10に設定
 * <EnemyLevelVariable:5> # レベルを格納している変数のID
 */

(function() {
    'use strict';

    const pluginName = "MonsterLevelStatusPlugin";
    const parameters = PluginManager.parameters(pluginName);
    const hpmpWindowX = Number(parameters['HP/MP Window X'] || 0);
    const hpmpWindowY = Number(parameters['HP/MP Window Y'] || 0);
    const hpmpWindowWidth = Number(parameters['HP/MP Window Width'] || 300);
    const hpmpWindowHeight = Number(parameters['HP/MP Window Height'] || 100);
    const nameLevelWindowX = Number(parameters['Name/Level Window X'] || 0);
    const nameLevelWindowY = Number(parameters['Name/Level Window Y'] || 110);
    const nameLevelWindowWidth = Number(parameters['Name/Level Window Width'] || 300);
    const nameLevelWindowHeight = Number(parameters['Name/Level Window Height'] || 72);
    const statsWindowX = Number(parameters['Stats Window X'] || 0);
    const statsWindowY = Number(parameters['Stats Window Y'] || 192);
    const statsWindowWidth = Number(parameters['Stats Window Width'] || 300);
    const statsWindowHeight = Number(parameters['Stats Window Height'] || 180);
    const windowOpacity = Number(parameters['Window Opacity'] || 255);
    const displayStats = JSON.parse(parameters['Display Stats'] || '["atk","def","mat","mdf","agi","luk"]');
    const statusWindowSwitchId = Number(parameters['Status Window Switch ID'] || 1);
    const isDebugMode = parameters['Debug Mode'] === 'true';

    function debugLog(message) {
        if (Utils.isOptionValid('test') && isDebugMode) {
            console.log(`[${pluginName}] ${message}`);
        }
    }

    // DataManager拡張
    const _DataManager_extractMetadata = DataManager.extractMetadata;
    DataManager.extractMetadata = function(data) {
        _DataManager_extractMetadata.call(this, data);
        debugLog(`Extracting metadata for: ${data.name}`);
        if (data.meta.EnemyClass) {
            data.classId = Number(data.meta.EnemyClass);
            debugLog(`EnemyClass set: ${data.classId}`);
        }
        if (data.meta.EnemyLevel) {
            data.level = Number(data.meta.EnemyLevel);
            debugLog(`EnemyLevel set: ${data.level}`);
        }
        if (data.meta.EnemyLevelVariable) {
            data.levelVariableId = Number(data.meta.EnemyLevelVariable);
            debugLog(`EnemyLevelVariable set: ${data.levelVariableId}`);
        }
        debugLog(`Extracted metadata: ${JSON.stringify(data.meta)}`);
    };

    // Game_Enemy拡張
    const _Game_Enemy_setup = Game_Enemy.prototype.setup;
    Game_Enemy.prototype.setup = function(enemyId, x, y) {
        _Game_Enemy_setup.call(this, enemyId, x, y);
        debugLog(`Setting up enemy ${enemyId}`);
        this._classId = this.enemy().classId || 1;
        this._level = this.getEnemyLevel();
        this._hp = this.mhp;
        this._mp = this.mmp;
        debugLog(`Enemy ${enemyId} setup complete:`);
        debugLog(`Class ID: ${this._classId}`);
        debugLog(`Level: ${this._level}`);
        debugLog(`Base params: ${JSON.stringify(this.enemy().params)}`);
        debugLog(`Current params: ${this.param(0)}, ${this.param(1)}, ${this.param(2)}, ${this.param(3)}, ${this.param(4)}, ${this.param(5)}, ${this.param(6)}, ${this.param(7)}`);
    };

    Game_Enemy.prototype.getEnemyLevel = function() {
        debugLog(`Getting enemy level for ${this.enemy().name}`);
        if (this.enemy().levelVariableId) {
            const level = $gameVariables.value(this.enemy().levelVariableId);
            debugLog(`Level from variable ${this.enemy().levelVariableId}: ${level}`);
            return Math.max(1, level); // Ensure level is at least 1
        }
        const level = this.enemy().level || 1;
        debugLog(`Level from enemy data: ${level}`);
        return level;
    };

    Game_Enemy.prototype.currentClass = function() {
        debugLog(`Getting current class for ${this.enemy().name}`);
        const classData = $dataClasses[this._classId] || $dataClasses[1];
        debugLog(`Current class: ${classData.name}`);
        return classData;
    };

    Game_Enemy.prototype.paramBase = function(paramId) {
        debugLog(`Getting base param ${paramId} for ${this.enemy().name}`);
        const baseParam = this.enemy().params[paramId];
        debugLog(`Base param ${paramId}: ${baseParam}`);
        return baseParam;
    };

    Game_Enemy.prototype.paramPlus = function(paramId) {
        return 0;
    };

    Game_Enemy.prototype.param = function(paramId) {
        debugLog(`Calculating param ${paramId} for ${this.enemy().name}`);
        const baseParam = this.paramBase(paramId);
        const classData = this.currentClass();
        let value = baseParam;

        if (classData && classData.params[paramId]) {
            const classParam = classData.params[paramId][this._level];
            value += classParam;
            
            debugLog(`Param ${paramId} calculation:`);
            debugLog(`Base value: ${baseParam}`);
            debugLog(`Class param for level ${this._level}: ${classParam}`);
            debugLog(`Final value: ${value}`);
        }

        value += this.paramPlus(paramId);

        debugLog(`Final param ${paramId} value: ${Math.max(1, value)}`);
        return Math.max(1, value);
    };

    Game_Enemy.prototype.setClassIdAndLevel = function(classId, level) {
        debugLog(`Setting class ID and level for ${this.enemy().name}`);
        this._classId = classId;
        this._level = level;
        this.refresh();
        debugLog(`New class ID: ${classId}, New level: ${level}`);
    };

    Game_Enemy.prototype.useSkill = function(skill) {
        Game_Battler.prototype.useSkill.call(this, skill);
        this.requestStatusWindowUpdate();
    };

    Game_Enemy.prototype.paySkillCost = function(skill) {
        Game_Battler.prototype.paySkillCost.call(this, skill);
        this.requestStatusWindowUpdate();
    };

    // Game_Action拡張
    const _Game_Action_makeDamageValue = Game_Action.prototype.makeDamageValue;
    Game_Action.prototype.makeDamageValue = function(target, critical) {
        debugLog(`Calculating damage for ${this.subject().name()} -> ${target.name()}`);
        const result = _Game_Action_makeDamageValue.call(this, target, critical);
        if (isNaN(result)) {
            debugLog(`Invalid damage calculation: ${this.subject().name()} -> ${target.name()}`);
            return 0;
        }
        debugLog(`Damage calculation result: ${result}`);
        return result;
    };

    const _Game_Action_apply = Game_Action.prototype.apply;
    Game_Action.prototype.apply = function(target) {
        _Game_Action_apply.call(this, target);
        if (this.subject().isEnemy()) {
            this.subject().requestStatusWindowUpdate();
        }
        if (target.isEnemy()) {
            target.requestStatusWindowUpdate();
        }
    };

    // Window_EnemyHPMP
    function Window_EnemyHPMP() {
        this.initialize(...arguments);
    }

    Window_EnemyHPMP.prototype = Object.create(Window_Base.prototype);
    Window_EnemyHPMP.prototype.constructor = Window_EnemyHPMP;

    Window_EnemyHPMP.prototype.initialize = function(rect) {
        Window_Base.prototype.initialize.call(this, rect);
        this.opacity = windowOpacity;
        this.contentsOpacity = 255;
        this._enemy = null;
        this.refresh();
    };

    Window_EnemyHPMP.prototype.setEnemy = function(enemy) {
        if (this._enemy !== enemy) {
            this._enemy = enemy;
            this.refresh();
        }
    };

    Window_EnemyHPMP.prototype.drawGauge = function(x, y, width, rate, color1, color2) {
        const fillW = Math.floor(width * rate);
        const gaugeY = y + this.lineHeight() - 8;
        this.contents.fillRect(x, gaugeY, width, 6, ColorManager.gaugeBackColor());
        this.contents.gradientFillRect(x, gaugeY, fillW, 6, color1, color2);
    };

    Window_EnemyHPMP.prototype.refresh = function() {
        this.contents.clear();
        if (this._enemy) {
            debugLog(`Refreshing HP/MP window for ${this._enemy.name()}`);
            let y = 0;
            
            // HP Gauge
            const hpRate = this._enemy.hp / this._enemy.mhp;
            this.drawText("HP", 0, y, 60);
            this.drawGauge(60, y, this.contents.width - 60, hpRate, ColorManager.hpGaugeColor1(), ColorManager.hpGaugeColor2());
            this.drawText(`${this._enemy.hp}/${this._enemy.mhp}`, 0, y, this.contents.width, 'right');
            y += this.lineHeight();

            // MP Gauge
            const mpRate = this._enemy.mp / this._enemy.mmp;
            this.drawText("MP", 0, y, 60);
            this.drawGauge(60, y, this.contents.width - 60, mpRate, ColorManager.mpGaugeColor1(), ColorManager.mpGaugeColor2());
            this.drawText(`${this._enemy.mp}/${this._enemy.mmp}`, 0, y, this.contents.width, 'right');

            debugLog(`HP/MP window refreshed for ${this._enemy.name()}`);
        }
    };

    // Window_EnemyNameLevel
    function Window_EnemyNameLevel() {
        this.initialize(...arguments);
    }

    Window_EnemyNameLevel.prototype = Object.create(Window_Base.prototype);
    Window_EnemyNameLevel.prototype.constructor = Window_EnemyNameLevel;

    Window_EnemyNameLevel.prototype.initialize = function(rect) {
        Window_Base.prototype.initialize.call(this, rect);
        this.opacity = windowOpacity;
        this.contentsOpacity = 255;
        this._enemy = null;
        this.refresh();
    };

    Window_EnemyNameLevel.prototype.setEnemy = function(enemy) {
        if (this._enemy !== enemy) {
            this._enemy = enemy;
            this.refresh();
        }
    };

    Window_EnemyNameLevel.prototype.refresh = function() {
        this.contents.clear();
        if (this._enemy) {
            debugLog(`Refreshing Name/Level window for ${this._enemy.name()}`);
            const nameWidth = this.contents.width - this.textWidth("Lv. 000");
            
            // Draw enemy name
            this.drawText(this._enemy.name(), 0, 0, nameWidth);
            
            // Draw enemy level
            this.drawText(`Lv. ${this._enemy._level}`, nameWidth, 0, this.contents.width - nameWidth, 'right');

            debugLog(`Name/Level window refreshed for ${this._enemy.name()}`);
        }
    };

    // Window_EnemyStats
    function Window_EnemyStats() {
        this.initialize(...arguments);
    }

    Window_EnemyStats.prototype = Object.create(Window_Base.prototype);
    Window_EnemyStats.prototype.constructor = Window_EnemyStats;
    Window_EnemyStats.prototype.initialize = function(rect) {
        Window_Base.prototype.initialize.call(this, rect);
        this.opacity = windowOpacity;
        this.contentsOpacity = 255;
        this._enemy = null;
        this.refresh();
    };

    Window_EnemyStats.prototype.setEnemy = function(enemy) {
        if (this._enemy !== enemy) {
            this._enemy = enemy;
            this.refresh();
        }
    };

    Window_EnemyStats.prototype.refresh = function() {
        this.contents.clear();
        if (this._enemy) {
            debugLog(`Refreshing stats window for ${this._enemy.name()}`);
            const lineHeight = this.lineHeight();
            const gaugeHeight = lineHeight - 8;
            const labelWidth = 60;
            const gaugeWidth = this.contents.width - labelWidth - 60;

            // Start from the top of the window
            let y = 0;

            displayStats.forEach(stat => {
                const paramId = ['atk', 'def', 'mat', 'mdf', 'agi', 'luk'].indexOf(stat);
                if (paramId !== -1) {
                    const value = this._enemy.param(paramId + 2);
                    const maxValue = this.getMaxValueForStat(stat);
                    const rate = value / maxValue;
                    
                    this.drawText(stat.toUpperCase(), 0, y, labelWidth);
                    this.drawGauge(labelWidth, y, gaugeWidth, rate, this.getColorForStat(stat));
                    this.drawText(value, labelWidth + gaugeWidth, y, 60, 'right');
                    
                    debugLog(`Stat ${stat.toUpperCase()}: ${value}/${maxValue} (${Math.floor(rate * 100)}%)`);
                    y += lineHeight;
                }
            });
            debugLog(`Stats window refreshed for ${this._enemy.name()}`);
        }
    };

    Window_EnemyStats.prototype.drawGauge = function(x, y, width, rate, color) {
        const fillW = Math.floor(width * rate);
        const gaugeY = y + this.lineHeight() - 8;
        this.contents.fillRect(x, gaugeY, width, 6, ColorManager.gaugeBackColor());
        this.contents.gradientFillRect(x, gaugeY, fillW, 6, color, color);
    };

    Window_EnemyStats.prototype.getMaxValueForStat = function(stat) {
        // この値は適切に調整する必要があります
        const maxValues = {
            atk: 255,
            def: 255,
            mat: 255,
            mdf: 255,
            agi: 255,
            luk: 255
        };
        return maxValues[stat] || 999;
    };

    Window_EnemyStats.prototype.getColorForStat = function(stat) {
        const colors = {
            atk: ColorManager.textColor(2),  // 赤
            def: ColorManager.textColor(3),  // 緑
            mat: ColorManager.textColor(5),  // 青
            mdf: ColorManager.textColor(6),  // 黄
            agi: ColorManager.textColor(4),  // シアン
            luk: ColorManager.textColor(7)   // 紫
        };
        return colors[stat] || ColorManager.normalColor();
    };

    // Scene_Battle拡張
    const _Scene_Battle_createAllWindows = Scene_Battle.prototype.createAllWindows;
    Scene_Battle.prototype.createAllWindows = function() {
        _Scene_Battle_createAllWindows.call(this);
        this.createEnemyStatusWindows();
    };

    Scene_Battle.prototype.createEnemyStatusWindows = function() {
        debugLog("Creating enemy status windows for battle scene");
        const hpmpRect = new Rectangle(hpmpWindowX, hpmpWindowY, hpmpWindowWidth, hpmpWindowHeight);
        this._enemyHPMPWindow = new Window_EnemyHPMP(hpmpRect);
        
        const nameLevelRect = new Rectangle(nameLevelWindowX, nameLevelWindowY, nameLevelWindowWidth, nameLevelWindowHeight);
        this._enemyNameLevelWindow = new Window_EnemyNameLevel(nameLevelRect);
        
        const statsRect = new Rectangle(statsWindowX, statsWindowY, statsWindowWidth, statsWindowHeight);
        this._enemyStatsWindow = new Window_EnemyStats(statsRect);
        
        // ウィンドウレイヤーを取得
        const windowLayer = this._windowLayer;
        
        // ヘルプウィンドウのインデックスを取得
        const helpWindowIndex = windowLayer.children.indexOf(this._helpWindow);
        
        // 敵キャラのステータスウィンドウをヘルプウィンドウの直前に挿入
        if (helpWindowIndex > -1) {
            windowLayer.addChildAt(this._enemyHPMPWindow, helpWindowIndex);
            windowLayer.addChildAt(this._enemyNameLevelWindow, helpWindowIndex);
            windowLayer.addChildAt(this._enemyStatsWindow, helpWindowIndex);
        } else {
            // ヘルプウィンドウが見つからない場合は、最も下のレイヤーに追加
            windowLayer.addChildAt(this._enemyHPMPWindow, 0);
            windowLayer.addChildAt(this._enemyNameLevelWindow, 1);
            windowLayer.addChildAt(this._enemyStatsWindow, 2);
        }

        this._enemyHPMPWindow.hide();
        this._enemyNameLevelWindow.hide();
        this._enemyStatsWindow.hide();
        debugLog("Enemy status windows created for battle scene");
    };

    const _Scene_Battle_update = Scene_Battle.prototype.update;
    Scene_Battle.prototype.update = function() {
        _Scene_Battle_update.call(this);
        this.updateEnemyStatusWindows();
        this.updateEnemyStatusWindowsOnDemand();
    };

    Scene_Battle.prototype.updateEnemyStatusWindows = function() {
        if ($gameSwitches.value(statusWindowSwitchId)) {
            this._enemyHPMPWindow.show();
            this._enemyNameLevelWindow.show();
            this._enemyStatsWindow.show();
            this._enemyHPMPWindow.opacity = windowOpacity;
            this._enemyNameLevelWindow.opacity = windowOpacity;
            this._enemyStatsWindow.opacity = windowOpacity;
        } else {
            this._enemyHPMPWindow.hide();
            this._enemyNameLevelWindow.hide();
            this._enemyStatsWindow.hide();
            this._enemyHPMPWindow.opacity = 0;
            this._enemyNameLevelWindow.opacity = 0;
            this._enemyStatsWindow.opacity = 0;
        }
    };

    Scene_Battle.prototype.requestEnemyStatusWindowUpdate = function(enemy) {
        this._enemyStatusUpdateRequired = true;
        this._enemyToUpdate = enemy;
    };

    Scene_Battle.prototype.updateEnemyStatusWindowsOnDemand = function() {
        if (this._enemyStatusUpdateRequired && this._enemyToUpdate) {
            this._enemyHPMPWindow.setEnemy(this._enemyToUpdate);
            this._enemyNameLevelWindow.setEnemy(this._enemyToUpdate);
            this._enemyStatsWindow.setEnemy(this._enemyToUpdate);
            this._enemyHPMPWindow.refresh();
            this._enemyNameLevelWindow.refresh();
            this._enemyStatsWindow.refresh();
            debugLog(`Refreshed enemy status windows for ${this._enemyToUpdate.name()} after damage`);
            this._enemyStatusUpdateRequired = false;
            this._enemyToUpdate = null;
        }
    };

    // Scene_Map拡張
    const _Scene_Map_createAllWindows = Scene_Map.prototype.createAllWindows;
    Scene_Map.prototype.createAllWindows = function() {
        _Scene_Map_createAllWindows.call(this);
        this.createEnemyStatusWindows();
    };

    Scene_Map.prototype.createEnemyStatusWindows = function() {
        debugLog("Creating enemy status windows for map scene");
        const hpmpRect = new Rectangle(hpmpWindowX, hpmpWindowY, hpmpWindowWidth, hpmpWindowHeight);
        this._enemyHPMPWindow = new Window_EnemyHPMP(hpmpRect);
        
        const nameLevelRect = new Rectangle(nameLevelWindowX, nameLevelWindowY, nameLevelWindowWidth, nameLevelWindowHeight);
        this._enemyNameLevelWindow = new Window_EnemyNameLevel(nameLevelRect);
        
        const statsRect = new Rectangle(statsWindowX, statsWindowY, statsWindowWidth, statsWindowHeight);
        this._enemyStatsWindow = new Window_EnemyStats(statsRect);
        
        // ウィンドウレイヤーを取得
        const windowLayer = this._windowLayer;
        
        // マップシーンではヘルプウィンドウが常に存在するとは限らないため、
        // 最も下のレイヤーに追加します
        windowLayer.addChildAt(this._enemyHPMPWindow, 0);
        windowLayer.addChildAt(this._enemyNameLevelWindow, 1);
        windowLayer.addChildAt(this._enemyStatsWindow, 2);

        this._enemyHPMPWindow.hide();
        this._enemyNameLevelWindow.hide();
        this._enemyStatsWindow.hide();
        debugLog("Enemy status windows created for map scene");
    };

    const _Scene_Map_update = Scene_Map.prototype.update;
    Scene_Map.prototype.update = function() {
        _Scene_Map_update.call(this);
        this.updateEnemyStatusWindows();
    };

    Scene_Map.prototype.updateEnemyStatusWindows = function() {
        if ($gameSwitches.value(statusWindowSwitchId)) {
            this._enemyHPMPWindow.show();
            this._enemyNameLevelWindow.show();
            this._enemyStatsWindow.show();
            this._enemyHPMPWindow.opacity = windowOpacity;
            this._enemyNameLevelWindow.opacity = windowOpacity;
            this._enemyStatsWindow.opacity = windowOpacity;
        } else {
            this._enemyHPMPWindow.hide();
            this._enemyNameLevelWindow.hide();
            this._enemyStatsWindow.hide();
            this._enemyHPMPWindow.opacity = 0;
            this._enemyNameLevelWindow.opacity = 0;
            this._enemyStatsWindow.opacity = 0;
        }
    };

    // プラグインコマンド
    PluginManager.registerCommand(pluginName, "ShowEnemyStatus", args => {
        const enemyId = Number(args.enemyId);
        debugLog(`ShowEnemyStatus command called with enemyId: ${enemyId}`);
        let targetEnemy;

        if (enemyId === 0 && $gameTroop.members().length > 0) {
            targetEnemy = $gameTroop.members()[0];
            debugLog(`Using first enemy in troop: ${targetEnemy.name()}`);
        } else if (enemyId > 0) {
            const enemy = $dataEnemies[enemyId];
            if (enemy) {
                targetEnemy = new Game_Enemy(enemyId, 0, 0);
                debugLog(`Created new Game_Enemy instance for enemyId: ${enemyId}`);
            }
        }

        if (targetEnemy) {
            if (SceneManager._scene instanceof Scene_Battle) {
                SceneManager._scene._enemyHPMPWindow.setEnemy(targetEnemy);
                SceneManager._scene._enemyNameLevelWindow.setEnemy(targetEnemy);
                SceneManager._scene._enemyStatsWindow.setEnemy(targetEnemy);
                debugLog(`Set enemy for battle scene windows: ${targetEnemy.name()}`);
            } else if (SceneManager._scene instanceof Scene_Map) {
                SceneManager._scene._enemyHPMPWindow.setEnemy(targetEnemy);
                SceneManager._scene._enemyNameLevelWindow.setEnemy(targetEnemy);
                SceneManager._scene._enemyStatsWindow.setEnemy(targetEnemy);
                debugLog(`Set enemy for map scene windows: ${targetEnemy.name()}`);
            }
            $gameSwitches.setValue(statusWindowSwitchId, true);
            debugLog(`ShowEnemyStatus command executed for enemy ${targetEnemy.name()}`);
        } else {
            debugLog(`ShowEnemyStatus command failed: Invalid enemy ID ${enemyId}`);
        }
    });

    // BattleManager拡張
    const _BattleManager_setup = BattleManager.setup;
    BattleManager.setup = function(troopId, canEscape, canLose) {
        _BattleManager_setup.call(this, troopId, canEscape, canLose);
        this.updateEnemyStats();
    };

    BattleManager.updateEnemyStats = function() {
        debugLog("Updating enemy stats for all enemies in troop");
        $gameTroop.members().forEach(enemy => {
            const baseEnemy = enemy.enemy();
            debugLog(`Updating stats for ${enemy.name()}:`);
            debugLog(`Base stats: ${JSON.stringify(baseEnemy.params)}`);
            debugLog(`Current stats: ${enemy.param(0)}, ${enemy.param(1)}, ${enemy.param(2)}, ${enemy.param(3)}, ${enemy.param(4)}, ${enemy.param(5)}, ${enemy.param(6)}, ${enemy.param(7)}`);
        });
    };

    // Game_Enemy拡張（ダメージ処理）
    const _Game_Enemy_performDamage = Game_Enemy.prototype.performDamage;
    Game_Enemy.prototype.performDamage = function() {
        _Game_Enemy_performDamage.call(this);
        debugLog(`Enemy ${this.name()} took damage, HP: ${this._hp}/${this.mhp}`);
        this.requestStatusWindowUpdate();
    };

    Game_Enemy.prototype.performMpDamage = function() {
        if (this.isSpriteVisible()) {
            this.requestEffect('whiten');
        }
        SoundManager.playEnemyDamage();
        debugLog(`Enemy ${this.name()} took MP damage, MP: ${this._mp}/${this.mmp}`);
        this.requestStatusWindowUpdate();
    };

    Game_Enemy.prototype.requestStatusWindowUpdate = function() {
        if (SceneManager._scene instanceof Scene_Battle) {
            SceneManager._scene.requestEnemyStatusWindowUpdate(this);
        }
    };

    // BattleManager拡張（バトル終了処理）
    const _BattleManager_endBattle = BattleManager.endBattle;
    BattleManager.endBattle = function(result) {
        _BattleManager_endBattle.call(this, result);
        $gameSwitches.setValue(statusWindowSwitchId, false);
        debugLog("Battle ended, status window switch turned off");
    };

    // エラー処理の拡張
    const _SceneManager_catchException = SceneManager.catchException;
    SceneManager.catchException = function(e) {
        _SceneManager_catchException.call(this, e);
        debugLog(`Error occurred: ${e.message}\n${e.stack}`);
    };

    // パフォーマンス最適化：更新間隔の設定
    const UPDATE_INTERVAL = 16; // 約60FPS

    const _Window_EnemyHPMP_update = Window_EnemyHPMP.prototype.update;
    Window_EnemyHPMP.prototype.update = function() {
        _Window_EnemyHPMP_update.call(this);
        if (this._enemy) {
            this.refresh();
        }
        this.opacity = $gameSwitches.value(statusWindowSwitchId) ? windowOpacity : 0;
    };

    const _Window_EnemyNameLevel_update = Window_EnemyNameLevel.prototype.update;
    Window_EnemyNameLevel.prototype.update = function() {
        _Window_EnemyNameLevel_update.call(this);
        if (this._enemy) {
            this.refresh();
        }
        this.opacity = $gameSwitches.value(statusWindowSwitchId) ? windowOpacity : 0;
    };

    const _Window_EnemyStats_update = Window_EnemyStats.prototype.update;
    Window_EnemyStats.prototype.update = function() {
        _Window_EnemyStats_update.call(this);
        if (this._enemy) {
            this.refresh();
        }
        this.opacity = $gameSwitches.value(statusWindowSwitchId) ? windowOpacity : 0;
    };

    // デバッグ機能：Ctrl+Dでステータスウィンドウの表示切替
    const _Scene_Map_updateDebug = Scene_Map.prototype.updateDebug;
    Scene_Map.prototype.updateDebug = function() {
        _Scene_Map_updateDebug.call(this);
        if (Input.isTriggered('debug') && Input.isPressed('control')) {
            $gameSwitches.setValue(statusWindowSwitchId, !$gameSwitches.value(statusWindowSwitchId));
            debugLog(`Status window visibility toggled: ${$gameSwitches.value(statusWindowSwitchId)}`);
        }
    };

    const _Scene_Battle_updateDebug = Scene_Battle.prototype.updateDebug;
    Scene_Battle.prototype.updateDebug = function() {
        _Scene_Battle_updateDebug.call(this);
        if (Input.isTriggered('debug') && Input.isPressed('control')) {
            $gameSwitches.setValue(statusWindowSwitchId, !$gameSwitches.value(statusWindowSwitchId));
            debugLog(`Status window visibility toggled: ${$gameSwitches.value(statusWindowSwitchId)}`);
        }
    };

    // 敵キャラの能力値更新
    Game_Enemy.prototype.refresh = function() {
        Game_Battler.prototype.refresh.call(this);
        if (this.hp > this.mhp) {
            this._hp = this.mhp;
        }
        if (this.mp > this.mmp) {
            this._mp = this.mmp;
        }
        debugLog(`Enemy ${this.name()} refreshed: HP ${this._hp}/${this.mhp}, MP ${this._mp}/${this.mmp}`);
    };

    // 敵キャラのレベルアップ処理
    Game_Enemy.prototype.levelUp = function() {
        this._level++;
        this.refresh();
        debugLog(`Enemy ${this.name()} leveled up to ${this._level}`);
    };

    // 敵キャラの経験値獲得処理
    Game_Enemy.prototype.gainExp = function(exp) {
        const newExp = this.currentExp() + exp;
        const newLevel = this.expToLevel(newExp);
        if (newLevel > this._level) {
            this.changeLevel(newLevel, false);
        }
        debugLog(`Enemy ${this.name()} gained ${exp} exp, now at level ${this._level}`);
    };

    Game_Enemy.prototype.currentExp = function() {
        return this.currentLevelExp();
    };

    Game_Enemy.prototype.currentLevelExp = function() {
        return this.expForLevel(this._level);
    };

    Game_Enemy.prototype.nextLevelExp = function() {
        return this.expForLevel(this._level + 1);
    };

    Game_Enemy.prototype.nextRequiredExp = function() {
        return this.nextLevelExp() - this.currentExp();
    };

    Game_Enemy.prototype.maxLevel = function() {
        return 99;
    };

    Game_Enemy.prototype.expForLevel = function(level) {
        return Math.round(level * level * level * (4 / 5));
    };

    Game_Enemy.prototype.expToLevel = function(exp) {
        let level = 1;
        while (level < this.maxLevel() && this.expForLevel(level + 1) <= exp) {
            level++;
        }
        return level;
    };

    Game_Enemy.prototype.changeLevel = function(level, show) {
        level = level.clamp(1, this.maxLevel());
        const oldLevel = this._level;
        this._level = level;
        this.refresh();
        if (show && level > oldLevel) {
            this.displayLevelUp(this.findNewSkills(oldLevel));
        }
        debugLog(`Enemy ${this.name()} changed level from ${oldLevel} to ${level}`);
    };

    Game_Enemy.prototype.displayLevelUp = function(newSkills) {
        const text = TextManager.levelUp.format(this._name, TextManager.level, this._level);
        $gameMessage.newPage();
        $gameMessage.add(text);
        newSkills.forEach(skill => {
            $gameMessage.add(TextManager.obtainSkill.format(skill.name));
        });
    };

    Game_Enemy.prototype.findNewSkills = function(oldLevel) {
        const newSkills = [];
        // ここで敵キャラのスキル習得処理を実装します（必要に応じて）
        return newSkills;
    };

    debugLog(`${pluginName} initialized`);
})();