/*:
 * @target MZ
 * @plugindesc メニュー画面レイアウトカスタマイズプラグイン（個別ウィンドウ版）
 * @author えむうん
 *
 * @param CommandWindowLayout
 * @text コマンドウィンドウレイアウト設定
 * @type struct<CommandLayoutSettings>
 * @default {"direction":"vertical","startX":"0","startY":"0","width":"240","height":"360","spacing":"0","align":"left","visible":"true"}
 * 
 * @param ActorWindowLayout
 * @text アクターウィンドウレイアウト設定
 * @type struct<ActorLayoutSettings>
 * @default {"direction":"horizontal","startX":"240","startY":"0","width":"280","height":"170","spacing":"10","visible":"true"}
 * 
 * @param GoldWindow
 * @text ゴールドウィンドウ設定
 * @type struct<WindowSettings>
 * @default {"x":"0","y":"360","width":"240","height":"80","visible":"true"}
 *
 * @param ActorDisplay
 * @text アクター表示設定
 * @type struct<ActorDisplaySettings>
 * @default {"faceSettings":"{\"show\":\"true\",\"x\":\"12\",\"y\":\"12\",\"width\":\"144\",\"height\":\"144\"}","nameSettings":"{\"show\":\"true\",\"x\":\"168\",\"y\":\"12\",\"width\":\"150\",\"fontSize\":\"28\"}","levelSettings":"{\"show\":\"true\",\"x\":\"168\",\"y\":\"40\",\"width\":\"150\",\"fontSize\":\"24\"}","gaugeSettings":"{\"show\":\"true\",\"x\":\"168\",\"y\":\"70\",\"width\":\"150\",\"spacing\":\"28\",\"fontSize\":\"22\",\"showHP\":\"true\",\"showMP\":\"true\",\"showTP\":\"true\",\"showValue\":\"true\"}","paramSettings":"{\"show\":\"true\",\"startX\":\"12\",\"startY\":\"156\",\"width\":\"120\",\"fontSize\":\"22\",\"spacing\":\"32\"}","equipmentSettings":"{\"show\":\"true\",\"x\":\"12\",\"y\":\"264\",\"width\":\"280\",\"fontSize\":\"22\"}"} 
 */

/*~struct~ActorDisplaySettings:
 * @param faceSettings
 * @text フェイス画像設定
 * @type struct<BasicDisplaySettings>
 * @default {"show":"true","x":"12","y":"12","width":"144","height":"144"}
 *
 * @param nameSettings
 * @text 名前表示設定
 * @type struct<BasicDisplaySettings>
 * @default {"show":"true","x":"168","y":"12","width":"150","fontSize":"28"}
 *
 * @param levelSettings
 * @text レベル表示設定
 * @type struct<BasicDisplaySettings>
 * @default {"show":"true","x":"168","y":"40","width":"150","fontSize":"24"}
 *
 * @param gaugeSettings
 * @text ゲージ表示設定
 * @type struct<GaugeDisplaySettings>
 * @default {"show":"true","x":"168","y":"70","width":"150","spacing":"28","fontSize":"22","showHP":"true","showMP":"true","showTP":"true","showValue":"true"}
 *
 * @param paramSettings
 * @text パラメータ表示設定
 * @type struct<ParamDisplaySettings>
 * @default {"show":"true","startX":"12","startY":"156","width":"120","fontSize":"22","spacing":"32"}
 *
 * @param equipmentSettings
 * @text 装備表示設定
 * @type struct<BasicDisplaySettings>
 * @default {"show":"true","x":"12","y":"264","width":"280","fontSize":"22"}
 */

/*~struct~BasicDisplaySettings:
 * @param show
 * @text 表示
 * @type boolean
 * @default true
 *
 * @param x
 * @text X座標
 * @type number
 * @min -1000
 * @max 1000
 * @default 0
 *
 * @param y
 * @text Y座標
 * @type number
 * @min -1000
 * @max 1000
 * @default 0
 *
 * @param width
 * @text 幅
 * @type number
 * @min 0
 * @max 1000
 * @default 150
 *
 * @param height
 * @text 高さ
 * @type number
 * @min 0
 * @max 1000
 * @default 144
 *
 * @param fontSize
 * @text フォントサイズ
 * @type number
 * @min 12
 * @max 48
 * @default 28
 */

/*~struct~GaugeDisplaySettings:
 * @param show
 * @text 表示
 * @type boolean
 * @default true
 *
 * @param x
 * @text X座標
 * @type number
 * @default 168
 *
 * @param y
 * @text Y座標
 * @type number
 * @default 70
 *
 * @param width
 * @text 幅
 * @type number
 * @default 150
 *
 * @param spacing
 * @text 間隔
 * @type number
 * @default 28
 *
 * @param fontSize
 * @text フォントサイズ
 * @type number
 * @default 22
 *
 * @param showHP
 * @text HP表示
 * @type boolean
 * @default true
 *
 * @param showMP
 * @text MP表示
 * @type boolean
 * @default true
 *
 * @param showTP
 * @text TP表示
 * @type boolean
 * @default true
 *
 * @param showValue
 * @text 数値表示
 * @type boolean
 * @default true
 */

/*~struct~ParamDisplaySettings:
 * @param show
 * @text 表示
 * @type boolean
 * @default true
 *
 * @param startX
 * @text 開始X座標
 * @type number
 * @default 12
 *
 * @param startY
 * @text 開始Y座標
 * @type number
 * @default 156
 *
 * @param width
 * @text 幅
 * @type number
 * @default 120
 *
 * @param fontSize
 * @text フォントサイズ
 * @type number
 * @default 22
 *
 * @param spacing
 * @text 間隔
 * @type number
 * @default 32
 */

/*~struct~CommandLayoutSettings:
 * @param direction
 * @text 配置方向
 * @type select
 * @option 縦方向
 * @value vertical
 * @option 横方向
 * @value horizontal
 * @default vertical
 * 
 * @param startX
 * @text 開始X座標
 * @type number
 * @min -2000
 * @max 2000
 * @default 0
 * 
 * @param startY
 * @text 開始Y座標
 * @type number
 * @min -2000
 * @max 2000
 * @default 0
 * 
 * @param width
 * @text ウィンドウ幅
 * @type number
 * @min 0
 * @max 2000
 * @default 240
 * 
 * @param height
 * @text ウィンドウ高さ
 * @type number
 * @min 0
 * @max 2000
 * @default 360
 * 
 * @param spacing
 * @text コマンド間隔
 * @type number
 * @min 0
 * @max 100
 * @default 0
 *
 * @param align
 * @text テキスト位置
 * @type select
 * @option 左揃え
 * @value left
 * @option 中央
 * @value center
 * @option 右揃え
 * @value right
 * @default left
 * 
 * @param visible
 * @text 表示
 * @type boolean
 * @default true
 */

/*~struct~ActorLayoutSettings:
 * @param direction
 * @text 配置方向
 * @type select
 * @option 横方向
 * @value horizontal
 * @option 縦方向
 * @value vertical
 * @default horizontal
 * 
 * @param startX
 * @text 開始X座標
 * @type number
 * @min -2000
 * @max 2000
 * @default 240
 * 
 * @param startY
 * @text 開始Y座標
 * @type number
 * @min -2000
 * @max 2000
 * @default 0
 * 
 * @param width
 * @text ウィンドウ幅
 * @type number
 * @min 0
 * @max 2000
 * @default 280
 * 
 * @param height
 * @text ウィンドウ高さ
 * @type number
 * @min 0
 * @max 2000
 * @default 170
 * 
 * @param spacing
 * @text ウィンドウ間隔
 * @type number
 * @min 0
 * @max 500
 * @default 10
 * 
 * @param visible
 * @text 表示
 * @type boolean
 * @default true
 */

/*~struct~WindowSettings:
 * @param x
 * @type number
 * @min -2000
 * @max 2000
 * @default 0
 * @text X座標
 * 
 * @param y
 * @type number
 * @min -2000
 * @max 2000
 * @default 0
 * @text Y座標
 * 
 * @param width
 * @type number
 * @min 0
 * @max 2000
 * @default 240
 * @text 幅
 * 
 * @param height
 * @type number
 * @min 0
 * @max 2000
 * @text 高さ
 * @desc 空白の場合、自動調整されます
 * 
 * @param visible
 * @type boolean
 * @default true
 * @text 表示
 */

(() => {
    'use strict';

    const pluginName = 'CustomMenuLayout';

    const defaultDisplaySettings = {
        faceSettings: {
            show: true,
            x: 12,
            y: 12,
            width: 144,
            height: 144
        },
        nameSettings: {
            show: true,
            x: 168,
            y: 12,
            width: 150,
            fontSize: 28
        },
        levelSettings: {
            show: true,
            x: 168,
            y: 40,
            width: 150,
            fontSize: 24
        },
        gaugeSettings: {
            show: true,
            x: 168,
            y: 70,
            width: 150,
            spacing: 28,
            fontSize: 22,
            showHP: true,
            showMP: true,
            showTP: true,
            showValue: true
        },
        paramSettings: {
            show: true,
            startX: 12,
            startY: 156,
            width: 120,
            fontSize: 22,
            spacing: 32
        },
        equipmentSettings: {
            show: true,
            x: 12,
            y: 264,
            width: 280,
            fontSize: 22
        }
    };

    const defaultCommandLayoutSettings = {
        direction: 'vertical',
        startX: 0,
        startY: 0,
        width: 240,
        height: 360,
        spacing: 0,
        align: 'left',
        visible: true
    };

    const defaultActorLayoutSettings = {
        direction: 'horizontal',
        startX: 240,
        startY: 0,
        width: 280,
        height: 170,
        spacing: 10,
        visible: true
    };

    const defaultGoldSettings = {
        x: 0,
        y: 360,
        width: 240,
        height: 80,
        visible: true
    };

    function parseWindowSettings(settings) {
        try {
            if (typeof settings === 'string') {
                settings = JSON.parse(settings);
            }
            return {
                x: Number(settings.x || 0),
                y: Number(settings.y || 0),
                width: Number(settings.width || 240),
                height: settings.height ? Number(settings.height) : null,
                visible: settings.visible !== 'false'
            };
        } catch (e) {
            console.error('Window settings parse error:', e);
            return {
                x: 0,
                y: 0,
                width: 240,
                height: null,
                visible: true
            };
        }
    }

    function parsePluginParameters() {
        try {
            const params = PluginManager.parameters(pluginName);
            
            let displaySettings = params.ActorDisplay ? JSON.parse(params.ActorDisplay) : defaultDisplaySettings;
            
            ['faceSettings', 'nameSettings', 'levelSettings', 'gaugeSettings', 'paramSettings', 'equipmentSettings'].forEach(key => {
                if (typeof displaySettings[key] === 'string') {
                    try {
                        displaySettings[key] = JSON.parse(displaySettings[key]);
                    } catch (e) {
                        console.error(`Error parsing ${key}:`, e);
                        displaySettings[key] = defaultDisplaySettings[key];
                    }
                }
            });

            return {
                commandLayoutSettings: JSON.parse(params.CommandWindowLayout || JSON.stringify(defaultCommandLayoutSettings)),
                actorLayoutSettings: JSON.parse(params.ActorWindowLayout || JSON.stringify(defaultActorLayoutSettings)),
                goldSettings: JSON.parse(params.GoldWindow || JSON.stringify(defaultGoldSettings)),
                displaySettings: displaySettings
            };
        } catch (e) {
            console.error('Plugin parameter parse error:', e);
            return {
                commandLayoutSettings: defaultCommandLayoutSettings,
                actorLayoutSettings: defaultActorLayoutSettings,
                goldSettings: defaultGoldSettings,
                displaySettings: defaultDisplaySettings
            };
        }
    }

    const parsedParams = parsePluginParameters();

    //-----------------------------------------------------------------------------
    // Window_MenuCommand
    //-----------------------------------------------------------------------------
    const _Window_MenuCommand_initialize = Window_MenuCommand.prototype.initialize;
    Window_MenuCommand.prototype.initialize = function(rect) {
        _Window_MenuCommand_initialize.call(this, rect);
        this.updateCommandLayout();
    };

    Window_MenuCommand.prototype.updateCommandLayout = function() {
        const layout = parsedParams.commandLayoutSettings;
        this.setCommandAlignment(layout.align);
        if (layout.direction === 'horizontal') {
            this.setHorizontalLayout(layout);
        } else {
            this.setVerticalLayout(layout);
        }
    };

    Window_MenuCommand.prototype.setCommandAlignment = function(align) {
        this.setAlignmentCommand(align);
    };

    Window_MenuCommand.prototype.setAlignmentCommand = function(align) {
        this.itemTextAlign = function() {
            return align;
        };
    };

    Window_MenuCommand.prototype.setHorizontalLayout = function(layout) {
        this.maxCols = function() {
            return Math.max(1, this.maxItems());
        };
        this.itemWidth = function() {
            return (this.innerWidth - this.itemPadding() * 2) / this.maxCols();
        };
        this._spacing = layout.spacing;
    };

    Window_MenuCommand.prototype.setVerticalLayout = function(layout) {
        this.maxCols = function() {
            return 1;
        };
        this._spacing = layout.spacing;
    };

    //-----------------------------------------------------------------------------
    // Window_MenuActor
    //-----------------------------------------------------------------------------
    function Window_MenuActor() {
        this.initialize(...arguments);
    }

    Window_MenuActor.prototype = Object.create(Window_StatusBase.prototype);
    Window_MenuActor.prototype.constructor = Window_MenuActor;

    Object.assign(Window_MenuActor.prototype, Window_Selectable.prototype);

    Window_MenuActor.prototype.initialize = function(rect) {
        this._additionalSprites = {};
        this._actor = null;
        this._selected = false;
        this._index = -1;
        Window_StatusBase.prototype.initialize.call(this, rect);
        Window_Selectable.prototype.initialize.call(this, rect);
        this.deactivate();
        this.refresh();
    };

    Window_MenuActor.prototype._createAllParts = function() {
        Window_Base.prototype._createAllParts.call(this);
        this._additionalSprites = this._additionalSprites || {};
    };

    Window_MenuActor.prototype.isActive = function() {
        return this.active;
    };

    Window_MenuActor.prototype.isCurrentItemEnabled = function() {
        return !!this._actor;
    };

    Window_MenuActor.prototype.maxItems = function() {
        return 1;
    };

    Window_MenuActor.prototype.maxCols = function() {
        return 1;
    };

    Window_MenuActor.prototype.itemHeight = function() {
        return this.innerHeight;
    };

    Window_MenuActor.prototype.itemWidth = function() {
        return this.innerWidth;
    };

    Window_MenuActor.prototype.itemRect = function() {
        return new Rectangle(0, 0, this.innerWidth, this.innerHeight);
    };

    Window_MenuActor.prototype.setActor = function(actor) {
        if (this._actor !== actor) {
            this._actor = actor;
            this.refresh();
        }
    };

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

    Window_MenuActor.prototype.select = function(index) {
        this._index = index;
        this.refreshCursor();
        this.callUpdateHelp();
        
        if (!this._selected) {
            this._selected = true;
            if (SceneManager._scene._actorWindows) {
                SceneManager._scene._actorWindows.forEach(window => {
                    if (window !== this) {
                        window._selected = false;
                        window._index = -1;
                        window.refreshCursor();
                    }
                });
            }
            this.refresh();
        }
    };

    Window_MenuActor.prototype.deselect = function() {
        this._index = -1;
        this._selected = false;
        this.refreshCursor();
        this.refresh();
    };

    Window_MenuActor.prototype.refreshCursor = function() {
        if (this._selected) {
            const rect = this.itemRect(0);
            this.setCursorRect(rect.x, rect.y, rect.width, rect.height);
        } else {
            this.setCursorRect(0, 0, 0, 0);
        }
    };

    Window_MenuActor.prototype.onTouchSelect = function() {
        if (this.visible && this._actor) {
            const lastSelected = this._selected;
            
            if (SceneManager._scene._actorWindows) {
                SceneManager._scene._actorWindows.forEach(window => {
                    if (window !== this) {
                        window._selected = false;
                        window._index = -1;
                        window.deactivate();
                        window.refreshCursor();
                    }
                });
            }
            
            this._selected = true;
            this._index = 0;
            this.activate();
            this.refreshCursor();
            
            if (!lastSelected) {
                this.refresh();
            }
        }
    };

    Window_MenuActor.prototype.isMouseInsideFrame = function() {
        const touchPos = new Point(TouchInput.x, TouchInput.y);
        const localPos = this.worldTransform.applyInverse(touchPos);
        return this.innerRect.contains(localPos.x, localPos.y);
    };

    Window_MenuActor.prototype.processTouch = function() {
        if (this.isOpen() && this.visible) {
            if (TouchInput.isTriggered() && this.isMouseInsideFrame()) {
                this.onTouchSelect();
            } else if (TouchInput.isClicked() && this.isMouseInsideFrame()) {
                if (this._selected && this._index >= 0) {
                    this.processOk();
                }
            }
        }
    };

    Window_MenuActor.prototype.processCursorMove = function() {
        if (this.isCursorMovable()) {
            const lastIndex = this._index;
            if (Input.isRepeated('left')) {
                this.processLeft();
            }
            if (Input.isRepeated('right')) {
                this.processRight();
            }
            if (this._index !== lastIndex) {
                this.playCursorSound();
            }
        }
    };

    Window_MenuActor.prototype.processHandling = function() {
        if (this.isOpen() && this.active) {
            if (Input.isTriggered('ok')) {
                this.processOk();
            } else if (Input.isTriggered('cancel')) {
                this.processCancel();
            } else {
                this.processCursorMove();
            }
        }
    };

    Window_MenuActor.prototype.processOk = function() {
        if (this.isCurrentItemEnabled()) {
            this.playOkSound();
            this.updateInputData();
            this.deactivate();
            this.callOkHandler();
        } else {
            this.playBuzzerSound();
        }
    };

    Window_MenuActor.prototype.processLeft = function() {
        const windows = SceneManager._scene._actorWindows;
        if (!windows) return;
        
        const currentIndex = windows.indexOf(this);
        if (currentIndex > 0) {
            const prevWindow = windows[currentIndex - 1];
            if (prevWindow.visible && prevWindow._actor) {
                this.deselect();
                this.deactivate();
                prevWindow.activate();
                prevWindow.select(0);
                prevWindow.setSelected(true);
            }
        } else if (SceneManager._scene._scrollIndex > 0) {
            SceneManager._scene.scrollLeft();
        }
    };

    Window_MenuActor.prototype.processRight = function() {
        const windows = SceneManager._scene._actorWindows;
        if (!windows) return;
        
        const currentIndex = windows.indexOf(this);
        if (currentIndex < windows.length - 1) {
            const nextWindow = windows[currentIndex + 1];
            if (nextWindow.visible && nextWindow._actor) {
                this.deselect();
                this.deactivate();
                nextWindow.activate();
                nextWindow.select(0);
                nextWindow.setSelected(true);
            }
        } else {
            const totalActors = $gameParty.members().length;
            const currentLastIndex = (SceneManager._scene._scrollIndex || 0) + windows.length;
            if (currentLastIndex < totalActors) {
                SceneManager._scene.scrollRight();
            }
        }
    };

    Window_MenuActor.prototype.processCancel = function() {
        this.playOkSound();
        this.updateInputData();
        this.deactivate();
        this.callCancelHandler();
    };

    Window_MenuActor.prototype.isCursorMovable = function() {
        return this.isActive();
    };

    Window_MenuActor.prototype.activate = function() {
        Window_Selectable.prototype.activate.call(this);
    };

    Window_MenuActor.prototype.deactivate = function() {
        Window_Selectable.prototype.deactivate.call(this);
        if (this._selected) {
            this.setSelected(false);
        }
    };

    Window_MenuActor.prototype.setSelected = function(selected) {
        if (this._selected !== selected) {
            this._selected = selected;
            this.refresh();
        }
    };

    Window_MenuActor.prototype.refresh = function() {
        if (!this.contents) return;
        this.contents.clear();
        this._destroyAdditionalSprites();
        if (this._actor) {
            this.drawActorInfo();
        }
    };

    Window_MenuActor.prototype._destroyAdditionalSprites = function() {
        if (this._additionalSprites) {
            Object.values(this._additionalSprites).forEach(sprite => {
                if (sprite && sprite.destroy) {
                    sprite.destroy();
                }
            });
            this._additionalSprites = {};
        }
    };

    Window_MenuActor.prototype.drawActorInfo = function() {
        const displaySettings = parsedParams.displaySettings;
        if (!displaySettings) return;

        if (displaySettings.faceSettings && displaySettings.faceSettings.show) {
            const fs = displaySettings.faceSettings;
            this.drawActorFace(
                this._actor,
                Number(fs.x),
                Number(fs.y),
                Number(fs.width),
                Number(fs.height)
            );
        }

        if (displaySettings.nameSettings && displaySettings.nameSettings.show) {
            const ns = displaySettings.nameSettings;
            this.contents.fontSize = Number(ns.fontSize);
            this.drawActorName(
                this._actor,
                Number(ns.x),
                Number(ns.y),
                Number(ns.width)
            );
        }

        if (displaySettings.levelSettings && displaySettings.levelSettings.show) {
            const ls = displaySettings.levelSettings;
            this.contents.fontSize = Number(ls.fontSize);
            this.drawActorLevel(
                this._actor,
                Number(ls.x),
                Number(ls.y),
                Number(ls.width)
            );
        }

        if (displaySettings.gaugeSettings && displaySettings.gaugeSettings.show) {
            const gs = displaySettings.gaugeSettings;
            this.contents.fontSize = Number(gs.fontSize);
            this.drawGauges(gs);
        }

        if (displaySettings.paramSettings && displaySettings.paramSettings.show) {
            const ps = displaySettings.paramSettings;
            this.contents.fontSize = Number(ps.fontSize);
            this.drawParameters(ps);
        }

        if (displaySettings.equipmentSettings && displaySettings.equipmentSettings.show) {
            const es = displaySettings.equipmentSettings;
            this.contents.fontSize = Number(es.fontSize);
            this.drawEquipments(es);
        }

        this.resetFontSettings();
    };

    Window_MenuActor.prototype.drawGauges = function(settings) {
        let y = Number(settings.y);
        
        if (settings.showHP) {
            this.drawGauge(settings.x, y, settings.width, "hp", settings.showValue);
            y += Number(settings.spacing);
        }
        
        if (settings.showMP) {
            this.drawGauge(settings.x, y, settings.width, "mp", settings.showValue);
            y += Number(settings.spacing);
        }
        
        if (settings.showTP && $dataSystem.optDisplayTp) {
            this.drawGauge(settings.x, y, settings.width, "tp", settings.showValue);
        }
    };

    Window_MenuActor.prototype.drawGauge = function(x, y, width, type, showValue) {
        const rate = this._actor[type + "Rate"]();
        const color1 = ColorManager[type + "GaugeColor1"]();
        const color2 = ColorManager[type + "GaugeColor2"]();
        
        this.drawGaugeRect(Number(x), Number(y), Number(width), rate, color1, color2);
        
        if (showValue) {
            const current = this._actor[type];
            const max = this._actor["max" + type.toUpperCase()];
            const valueWidth = this.textWidth('0000');
            this.drawText(current, Number(x) + Number(width) - valueWidth * 2, Number(y), valueWidth, 'right');
            this.drawText("/", Number(x) + Number(width) - valueWidth, Number(y), valueWidth, 'center');
            this.drawText(max, Number(x) + Number(width), Number(y), valueWidth, 'right');
        }
    };

    Window_MenuActor.prototype.drawParameters = function(settings) {
    this.contents.fontSize = Number(settings.fontSize);
    const params = [2, 3, 4, 5, 6, 7];
    
    params.forEach((paramId, index) => {
        const row = Math.floor(index / 2);
        const col = index % 2;
        const x = Number(settings.startX) + (col * (Number(settings.width) + Number(settings.spacing)));
        const y = Number(settings.startY) + (row * Number(settings.fontSize));
        
        this.changeTextColor(ColorManager.systemColor());
        this.drawText($dataSystem.terms.params[paramId], x, y, Number(settings.width) - 60);
        
        this.resetTextColor();
        const value = this._actor.param(paramId);
        this.drawText(value, x + Number(settings.width) - 60, y, 60, 'right');
    });
};

Window_MenuActor.prototype.drawGauges = function(settings) {
    let y = Number(settings.y);
    
    if (settings.showHP) {
        this.placeGauge(this._actor, "hp", Number(settings.x), y);
        y += Number(settings.spacing);
    }
    
    if (settings.showMP) {
        this.placeGauge(this._actor, "mp", Number(settings.x), y);
        y += Number(settings.spacing);
    }
    
    if (settings.showTP && $dataSystem.optDisplayTp) {
        this.placeGauge(this._actor, "tp", Number(settings.x), y);
    }
};

Window_MenuActor.prototype.placeGauge = function(actor, type, x, y) {
    const key = "actor" + actor.actorId() + type;
    const sprite = this.createInnerSprite(key, Sprite_Gauge);
    sprite.setup(actor, type);
    sprite.move(x, y);
    sprite.show();
};

Window_MenuActor.prototype.createInnerSprite = function(key, spriteClass) {
    const dict = this._additionalSprites;
    if (dict[key]) {
        dict[key].destroy();
    }
    dict[key] = new spriteClass();
    this.addInnerChild(dict[key]);
    return dict[key];
};

Window_MenuActor.prototype.drawEquipments = function(settings) {
    this.contents.fontSize = Number(settings.fontSize);
    const equips = this._actor.equips();
    const slots = this._actor.equipSlots();
    
    slots.forEach((slotName, i) => {
        const slotId = i;
        const y = Number(settings.y) + this.lineHeight() * (i + 1);
        
        this.changeTextColor(ColorManager.systemColor());
        this.drawText($dataSystem.equipTypes[slotId + 1], Number(settings.x), y, 120);
        this.resetTextColor();
        
        if (equips[slotId]) {
            this.drawItemName(
                equips[slotId],
                Number(settings.x) + 120,
                y,
                Number(settings.width) - 120
            );
        } else {
            this.drawText('-', Number(settings.x) + 120, y, 60);
        }
    });
};

Window_MenuActor.prototype.drawActorInfo = function() {
    const displaySettings = parsedParams.displaySettings;
    if (!displaySettings) return;

    if (displaySettings.faceSettings && displaySettings.faceSettings.show) {
        const fs = displaySettings.faceSettings;
        this.drawActorFace(
            this._actor,
            Number(fs.x),
            Number(fs.y),
            Number(fs.width),
            Number(fs.height)
        );
    }

    if (displaySettings.nameSettings && displaySettings.nameSettings.show) {
        const ns = displaySettings.nameSettings;
        this.contents.fontSize = Number(ns.fontSize);
        this.drawText(this._actor.name(), Number(ns.x), Number(ns.y), Number(ns.width));
    }

    if (displaySettings.levelSettings && displaySettings.levelSettings.show) {
        const ls = displaySettings.levelSettings;
        this.contents.fontSize = Number(ls.fontSize);
        this.changeTextColor(ColorManager.systemColor());
        this.drawText(TextManager.levelA, Number(ls.x), Number(ls.y), 48);
        this.resetTextColor();
        this.drawText(this._actor.level, Number(ls.x) + 48, Number(ls.y), Number(ls.width) - 48, 'right');
    }

    if (displaySettings.gaugeSettings && displaySettings.gaugeSettings.show) {
        this.drawGauges(displaySettings.gaugeSettings);
    }

    if (displaySettings.paramSettings && displaySettings.paramSettings.show) {
        this.drawParameters(displaySettings.paramSettings);
    }

    if (displaySettings.equipmentSettings && displaySettings.equipmentSettings.show) {
        this.drawEquipments(displaySettings.equipmentSettings);
    }

    this.resetFontSettings();
};

    Window_MenuActor.prototype.update = function() {
        Window_StatusBase.prototype.update.call(this);
        Window_Selectable.prototype.update.call(this);
        this.processHandling();
        this.processTouch();
    };

    Window_MenuActor.prototype.updateBackOpacity = function() {
        this.backOpacity = this._selected ? 192 : 255;
    };

    //-----------------------------------------------------------------------------
    // Scene_Menu
    //-----------------------------------------------------------------------------
    Scene_Menu.prototype.create = function() {
        Scene_MenuBase.prototype.create.call(this);
        this.createCommandWindow();
        this.createGoldWindow();
        this.createActorWindows();
        this.updateActorSelection();
    };

    Scene_Menu.prototype.start = function() {
        Scene_MenuBase.prototype.start.call(this);
        if (this._commandWindow) {
            this._commandWindow.refresh();
        }
    };

    Scene_Menu.prototype.createCommandWindow = function() {
        const layout = parsedParams.commandLayoutSettings;
        const rect = new Rectangle(
            Number(layout.startX),
            Number(layout.startY),
            Number(layout.width),
            Number(layout.height)
        );
        this._commandWindow = new Window_MenuCommand(rect);
        this._commandWindow.setHandler("item", this.commandItem.bind(this));
        this._commandWindow.setHandler("skill", this.selectActorSelection.bind(this));
        this._commandWindow.setHandler("equip", this.selectActorSelection.bind(this));
        this._commandWindow.setHandler("status", this.selectActorSelection.bind(this));
        this._commandWindow.setHandler("formation", this.commandFormation.bind(this));
        this._commandWindow.setHandler("options", this.commandOptions.bind(this));
        this._commandWindow.setHandler("save", this.commandSave.bind(this));
        this._commandWindow.setHandler("gameEnd", this.commandGameEnd.bind(this));
        this._commandWindow.setHandler("cancel", this.popScene.bind(this));
        this.addWindow(this._commandWindow);
        this._commandWindow.activate();
    };

    Scene_Menu.prototype.createGoldWindow = function() {
        const settings = parseWindowSettings(parsedParams.goldSettings);
        const rect = new Rectangle(
            settings.x,
            settings.y,
            settings.width,
            settings.height || this.calcGoldWindowHeight()
        );
        this._goldWindow = new Window_Gold(rect);
        this.addWindow(this._goldWindow);
    };

    Scene_Menu.prototype.calcGoldWindowHeight = function() {
        return this.calcWindowHeight(1, false);
    };

    Scene_Menu.prototype.createActorWindows = function() {
        this._actorWindows = [];
        this._scrollIndex = 0;
        const layout = parsedParams.actorLayoutSettings;
        
        const maxWindows = this.calculateMaxActorWindows(layout);
        
        for (let i = 0; i < maxWindows; i++) {
            let x = Number(layout.startX);
            let y = Number(layout.startY);
            const spacing = Number(layout.spacing);
            
            if (layout.direction === 'horizontal') {
                x += (Number(layout.width) + spacing) * i;
            } else {
                y += (Number(layout.height) + spacing) * i;
            }

            const rect = new Rectangle(
                x,
                y,
                Number(layout.width),
                Number(layout.height)
            );
            
            const window = new Window_MenuActor(rect);
            window.visible = layout.visible !== 'false';
            window.deactivate();
            window.setHandler("ok", this.onActorOk.bind(this, i));
            window.setHandler("cancel", this.onActorCancel.bind(this));
            this.addWindow(window);
            this._actorWindows.push(window);
        }
        
        this.refreshActorWindows();
        this.createScrollButtons();
    };

    Scene_Menu.prototype.calculateMaxActorWindows = function(layout) {
        const maxBattleMembers = $gameParty.maxBattleMembers();
        const screenWidth = Graphics.boxWidth;
        const screenHeight = Graphics.boxHeight;
        
        if (layout.direction === 'horizontal') {
            return Math.min(maxBattleMembers, Math.floor((screenWidth - Number(layout.startX)) / (Number(layout.width) + Number(layout.spacing))));
        } else {
            return Math.min(maxBattleMembers, Math.floor((screenHeight - Number(layout.startY)) / (Number(layout.height) + Number(layout.spacing))));
        }
    };

    Scene_Menu.prototype.createScrollButtons = function() {
        const layout = parsedParams.actorLayoutSettings;
        if (this.needsScrollButtons()) {
            this._scrollLeftButton = new Sprite_Button('pageup');
            this._scrollRightButton = new Sprite_Button('pagedown');
            
            if (layout.direction === 'horizontal') {
                this._scrollLeftButton.x = Number(layout.startX) - 48;
                this._scrollRightButton.x = Number(layout.startX) + this.totalVisibleWidth() + 4;
                this._scrollLeftButton.y = this._scrollRightButton.y = Number(layout.startY) + Number(layout.height) / 2 - 24;
            } else {
                this._scrollLeftButton.y = Number(layout.startY) - 48;
                this._scrollRightButton.y = Number(layout.startY) + this.totalVisibleHeight() + 4;
                this._scrollLeftButton.x = this._scrollRightButton.x = Number(layout.startX) + Number(layout.width) / 2 - 24;
            }
            
            this.addChild(this._scrollLeftButton);
            this.addChild(this._scrollRightButton);
            
            this._scrollLeftButton.setClickHandler(this.scrollLeft.bind(this));
            this._scrollRightButton.setClickHandler(this.scrollRight.bind(this));
        }
    };

    Scene_Menu.prototype.totalVisibleWidth = function() {
        const layout = parsedParams.actorLayoutSettings;
        return (Number(layout.width) + Number(layout.spacing)) * this._actorWindows.length;
    };

    Scene_Menu.prototype.totalVisibleHeight = function() {
        const layout = parsedParams.actorLayoutSettings;
        return (Number(layout.height) + Number(layout.spacing)) * this._actorWindows.length;
    };

    Scene_Menu.prototype.needsScrollButtons = function() {
        return $gameParty.members().length > this._actorWindows.length;
    };

    Scene_Menu.prototype.scrollLeft = function() {
        if (this._scrollIndex > 0) {
            this._scrollIndex--;
            this.refreshActorWindows();
            
            const activeWindow = this._actorWindows.find(window => window.active);
            if (activeWindow) {
                const windowIndex = this._actorWindows.indexOf(activeWindow);
                this.updateActiveActorWindow(windowIndex);
            }
        }
    };

    Scene_Menu.prototype.scrollRight = function() {
        const maxScroll = Math.max(0, $gameParty.members().length - this._actorWindows.length);
        if (this._scrollIndex < maxScroll) {
            this._scrollIndex++;
            this.refreshActorWindows();
            
            const activeWindow = this._actorWindows.find(window => window.active);
            if (activeWindow) {
                const windowIndex = this._actorWindows.indexOf(activeWindow);
                this.updateActiveActorWindow(windowIndex);
            }
        }
    };

    Scene_Menu.prototype.updateActiveActorWindow = function(windowIndex) {
        const actorIndex = this._scrollIndex + windowIndex;
        const actor = $gameParty.members()[actorIndex];
        if (actor) {
            const window = this._actorWindows[windowIndex];
            window.setActor(actor);
            window.activate();
            window.select(0);
            window.setSelected(true);
        }
    };

    Scene_Menu.prototype.refreshActorWindows = function() {
        const actors = $gameParty.members();
        let hasValidWindow = false;
        
        this._actorWindows.forEach((window, index) => {
            const actorIndex = (this._scrollIndex || 0) + index;
            const actor = actors[actorIndex];
            window.setActor(actor);
            window.visible = !!actor && parsedParams.actorLayoutSettings.visible !== 'false';
            
            if (window.visible && actor && !hasValidWindow) {
                hasValidWindow = true;
                if (window.active) {
                    window.select(0);
                    window.setSelected(true);
                }
            }
        });
        
        if (this._scrollLeftButton) {
            this._scrollLeftButton.visible = this._scrollIndex > 0;
        }
        if (this._scrollRightButton) {
            const maxScroll = Math.max(0, actors.length - this._actorWindows.length);
            this._scrollRightButton.visible = this._scrollIndex < maxScroll;
        }
    };

    Scene_Menu.prototype.commandItem = function() {
        SceneManager.push(Scene_Item);
    };

    Scene_Menu.prototype.selectActorSelection = function() {
        if (!this._actorWindows || !this._commandWindow) return;
        
        this._commandWindow.deactivate();
        this._actorWindows.forEach(window => {
            window.deselect();
            window.deactivate();
        });
        
        const firstValidWindow = this._actorWindows.find(window => window.visible && window._actor);
        if (firstValidWindow) {
            firstValidWindow.select(0);
            firstValidWindow.setSelected(true);
            firstValidWindow.activate();
        }
    };

    Scene_Menu.prototype.updateActorSelection = function() {
        if (!this._actorWindows || !this._commandWindow) return;
        
        this._actorWindows.forEach((window, i) => {
            window.setSelected(false);
            window.deactivate();
        });

        if (this._commandWindow.active) {
            const index = this._commandWindow.index();
            if (this._actorWindows[index]) {
                this._actorWindows[index].setSelected(true);
            }
        }
    };

    Scene_Menu.prototype.onActorOk = function(windowIndex) {
        const actorIndex = (this._scrollIndex || 0) + windowIndex;
        const actor = $gameParty.members()[actorIndex];
        if (!actor) return;
        
        $gameParty.setMenuActor(actor);
        
        switch (this._commandWindow.currentSymbol()) {
            case 'skill':
                SceneManager.push(Scene_Skill);
                break;
            case 'equip':
                SceneManager.push(Scene_Equip);
                break;
            case 'status':
                SceneManager.push(Scene_Status);
                break;
        }
    };

    Scene_Menu.prototype.onActorCancel = function() {
        this._actorWindows.forEach(window => {
            window.deactivate();
            window.deselect();
            window.setSelected(false);
        });
        this._commandWindow.activate();
    };

    Scene_Menu.prototype.commandFormation = function() {
        SceneManager.push(Scene_Formation);
    };

    Scene_Menu.prototype.commandOptions = function() {
        SceneManager.push(Scene_Options);
    };

    Scene_Menu.prototype.commandSave = function() {
        SceneManager.push(Scene_Save);
    };

    Scene_Menu.prototype.commandGameEnd = function() {
        SceneManager.push(Scene_GameEnd);
    };

    Scene_Menu.prototype.update = function() {
        Scene_MenuBase.prototype.update.call(this);
        if (this._commandWindow.active) {
            this.updateActorSelection();
        }
        this.updateActorWindows();
    };

    Scene_Menu.prototype.updateActorWindows = function() {
        if ($gameParty.needsRefresh()) {
            this.refreshActorWindows();
            $gameParty.clearRefresh();
        }
    };

    const _Game_Party_addActor = Game_Party.prototype.addActor;
    Game_Party.prototype.addActor = function(actorId) {
        _Game_Party_addActor.call(this, actorId);
        this._needsRefresh = true;
    };

    const _Game_Party_removeActor = Game_Party.prototype.removeActor;
    Game_Party.prototype.removeActor = function(actorId) {
        _Game_Party_removeActor.call(this, actorId);
        this._needsRefresh = true;
    };

    Game_Party.prototype.needsRefresh = function() {
        return !!this._needsRefresh;
    };

    Game_Party.prototype.clearRefresh = function() {
        this._needsRefresh = false;
    };

})();