(() => {
    "use strict";
    const RM = Number(PluginManager.parameters("zz_wrap").rightMargin || 24);
    const ESC = "\x1b";
    const _conv = Window_Message.prototype.convertEscapeCharacters;
    Window_Message.prototype.convertEscapeCharacters = function(text) {
        const base = (_conv || Window_Base.prototype.convertEscapeCharacters);
        let t = base.call(this, text);
        try { t = wrap.call(this, t); } catch (e) {}
        return t;
    };
    function wrap(text) {
        if (!this.contents) return text;
        const maxRight = this.innerWidth - RM;
        const iconW = (ImageManager.iconWidth || 32) + 4;
        let out = "";
        let x = 0, left = 0;
        let i = 0;
        const n = text.length;
        while (i < n) {
            const ch = text[i];
            if (ch === "\n") { out += ch; x = left; i++; continue; }
            if (ch === ESC) {
                const m = /^[A-Za-z]+(\[\d+\])?/.exec(text.slice(i + 1));
                const code = m ? m[0] : (text[i + 1] || "");
                const tok = ESC + code;
                out += tok;
                i += tok.length;
                const um = code.toUpperCase();
                if (um.startsWith("PX")) {
                    const num = /\[(\d+)\]/.exec(code);
                    if (num) { x = left = Number(num[1]); }
                } else if (um.startsWith("I")) {
                    x += iconW;
                }
                continue;
            }
            let j = i;
            while (j < n && text[j] !== " " && text[j] !== "\n" && text[j] !== ESC) j++;
            let word = text.slice(i, j);
            let k = j;
            while (k < n && text[k] === " ") k++;
            const spaces = text.slice(j, k);
            const wWidth = this.textWidth(word);
            if (x + wWidth > maxRight && x > left) {
                out += "\n" + (left > 0 ? ESC + "PX[" + Math.round(left) + "]" : "");
                x = left;
            }
            out += word + spaces;
            x += wWidth + this.textWidth(spaces);
            i = k;
        }
        return out;
    }
})();
