var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import { AcApDocManager, AcApSettingManager } from '../../../app';
import { AcApI18n } from '../../../i18n';
import { AcEdKeywordSession } from '../session';
/**
 * AutoCAD-style floating command line with Promise-based execution.
 *
 * Features:
 *  - Floating command bar with left terminal glyph + down toggle and right up toggle
 *  - Command history popup
 *  - Message panel above the bar
 *  - Enter repeats last command if input empty
 *  - Esc cancels current command
 *  - Inline clickable options
 *  - Keyboard navigation
 *  - Promise-based execution for async command handling
 *  - Auto-complete popup for matching commands
 */
var AcEdCommandLine = /** @class */ (function () {
    function AcEdCommandLine(container) {
        if (container === void 0) { container = document.body; }
        var _this = this;
        this.isPromptActive = false;
        this.container = container;
        this.history = [];
        this.historyIndex = -1;
        this.lastExecuted = null;
        this.isCmdPopupOpen = false;
        this.isMsgPanelOpen = false;
        this.minWidth = 420;
        this.widthRatio = 0.66;
        this.autoCompleteIndex = -1;
        this.injectCSS();
        this.createUI();
        this.bindEvents();
        this.resizeHandler();
        window.addEventListener('resize', function () { return _this.resizeHandler(); });
        this.resizeObserver = new ResizeObserver(function () { return _this.resizeHandler(); });
        this.resizeObserver.observe(this.container);
        AcApI18n.events.localeChanged.addEventListener(function () { return _this.refreshLocale(); });
    }
    Object.defineProperty(AcEdCommandLine.prototype, "visible", {
        /** Visibility of the command line */
        get: function () {
            return this.cliContainer.style.display !== 'none';
        },
        set: function (val) {
            this.cliContainer.style.display = val ? 'block' : 'none';
        },
        enumerable: false,
        configurable: true
    });
    AcEdCommandLine.prototype.setPrompt = function (message) {
        this.isPromptActive = true;
        this.promptEl.innerHTML = message !== null && message !== void 0 ? message : '';
        this.textInput.placeholder = '';
    };
    AcEdCommandLine.prototype.clear = function () {
        this.clearPrompt();
        this.clearInput();
    };
    AcEdCommandLine.prototype.clearPrompt = function () {
        this.promptEl.innerHTML = '';
        this.isPromptActive = false;
    };
    AcEdCommandLine.prototype.clearInput = function () {
        this.textInput.value = '';
        this.textInput.placeholder = this.isPromptActive
            ? ''
            : this.localize('main.commandLine.placeholder');
    };
    AcEdCommandLine.prototype.focusInput = function () {
        this.textInput.focus();
    };
    AcEdCommandLine.prototype.setInputReadOnly = function (readOnly) {
        this.textInput.readOnly = readOnly;
    };
    /**
     * Displays a non-error message in the command line history panel.
     *
     * This is a lightweight public wrapper around the internal history/message
     * rendering pipeline so other editor components can surface prompt feedback
     * without needing direct access to the private printing helpers.
     *
     * @param message - Message text to append to the command line message panel
     * @param msgKey - Optional localization key stored with the rendered entry
     */
    AcEdCommandLine.prototype.showMessage = function (message, msgKey) {
        this.printMessage(message, msgKey);
    };
    /**
     * Displays an error message in the command line history panel.
     *
     * Prompt workflows such as entity picking use this to report rejected input
     * while keeping the current interaction active. The rendered line is styled
     * as an error entry so it is visually distinct from normal informational
     * messages.
     *
     * @param message - Error text to append to the command line message panel
     * @param msgKey - Optional localization key stored with the rendered entry
     */
    AcEdCommandLine.prototype.showError = function (message, msgKey) {
        this.printError(message, msgKey);
    };
    AcEdCommandLine.prototype.cancelActiveSession = function () {
        if (!this.activeSession)
            return;
        this.activeSession.handleEscape();
        this.activeSession = undefined;
    };
    AcEdCommandLine.prototype.getKeywords = function (options_1) {
        return __awaiter(this, arguments, void 0, function (options, allowTyping) {
            var result;
            if (allowTyping === void 0) { allowTyping = true; }
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.activeSession = new AcEdKeywordSession(this, options, allowTyping);
                        return [4 /*yield*/, this.activeSession.start()];
                    case 1:
                        result = _a.sent();
                        this.activeSession = undefined;
                        return [2 /*return*/, result];
                }
            });
        });
    };
    /**
     * Localize a text key using AcApI18n.t().
     *
     * This helper centralizes localization calls for the class and makes
     * it easier to adjust localization behavior in one place if needed.
     *
     * @param key - Localization key (flat key style, e.g. "command.placeholder")
     * @param defaultText - Default English (or fallback) text to use if the key is missing
     * @returns localized string from AcApI18n or the provided defaultText
     */
    AcEdCommandLine.prototype.localize = function (key, defaultText) {
        return AcApI18n.t(key, { fallback: defaultText });
    };
    /** Refresh all messages when locale changes */
    AcEdCommandLine.prototype.refreshLocale = function () {
        var _this = this;
        Array.from(this.msgPanel.children).forEach(function (child) {
            var _a, _b, _c, _d, _e, _f;
            var div = child;
            var key = div.dataset.msgKey;
            if (key) {
                if (key === 'main.commandLine.executed') {
                    // Preserve the command name part
                    var cmdName = (_c = (_b = (_a = div.textContent) === null || _a === void 0 ? void 0 : _a.split(':')[1]) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : '';
                    div.textContent = "".concat(_this.localize(key), ": ").concat(cmdName);
                }
                else if (key === 'main.commandLine.unknownCommand') {
                    var cmd = (_f = (_e = (_d = div.textContent) === null || _d === void 0 ? void 0 : _d.split(':')[1]) === null || _e === void 0 ? void 0 : _e.trim()) !== null && _f !== void 0 ? _f : '';
                    div.textContent = "".concat(_this.localize(key), ": ").concat(cmd);
                }
                else {
                    div.textContent = _this.localize(key);
                }
            }
        });
        // Refresh input placeholder
        this.centerEl.setAttribute('data-placeholder', this.localize('main.commandLine.placeholder'));
        if (!this.isPromptActive && !this.textInput.value) {
            this.textInput.placeholder = this.localize('main.commandLine.placeholder');
        }
        // Refresh button titles
        this.downBtn.title = this.localize('main.commandLine.showHistory');
        this.upBtn.title = this.localize('main.commandLine.showMessages');
    };
    /**
     * Execute a command line string.
     * Returns a Promise that resolves when the command is completed.
     * @param cmdLine - Command string
     * @returns Promise<void>
     */
    AcEdCommandLine.prototype.executeCommand = function (cmdLine) {
        if (!cmdLine || !cmdLine.trim()) {
            if (this.lastExecuted)
                cmdLine = this.lastExecuted;
            else {
                this.printMessage(this.localize('main.commandLine.noLast', '(no last command)'));
                return;
            }
        }
        var command = this.resolveCommand(cmdLine);
        if (!command) {
            var unknown = this.localize('main.commandLine.unknownCommand');
            this.printError("".concat(unknown, ": ").concat(cmdLine));
            return;
        }
        this.history.push(command.globalName);
        this.historyIndex = this.history.length;
        this.lastExecuted = command.globalName;
        this.printHistoryLine(cmdLine);
        var executed = this.localize('main.commandLine.executed');
        this.printMessage("".concat(executed, ": ").concat(command.localName));
        AcApDocManager.instance.sendStringToExecute(cmdLine);
        this.clearInput();
    };
    /** Inject CSS styles */
    AcEdCommandLine.prototype.injectCSS = function () {
        var style = document.createElement('style');
        style.textContent = "\n      .ml-cli-container {\n        position: fixed;\n        bottom: 45px;\n        left: 50%;\n        transform: translateX(-50%);\n        font-family: \"Segoe UI\", Arial, sans-serif;\n        font-size: 13px;\n        box-sizing: border-box;\n        user-select: none;\n      }\n\n      .ml-cli-bar {\n        display: flex;\n        align-items: center;\n        gap: 6px;\n        border-radius: 6px;\n        background: var(--ml-ui-bg, linear-gradient(#ededed, #e0e0e0));\n        border: 1px solid var(--ml-ui-border, rgba(0, 0, 0, 0.35));\n        box-shadow: var(--ml-ui-shadow, 0 2px 6px rgba(0, 0, 0, 0.25));\n        min-width: 300px;\n        height: 30px;\n      }\n\n      .ml-cli-left {\n        display: flex;\n        align-items: center;\n        gap: 4px;\n        background: var(--ml-ui-bg, rgba(0, 0, 0, 0.06));\n        border-radius: 4px;\n        border: 1px solid var(--ml-ui-border, rgba(0, 0, 0, 0.08));\n        height: 100%;\n      }\n\n      .ml-cli-close-btn {\n        width: 18px;\n        height: 16px;\n        display: inline-flex;\n        align-items: center;\n        justify-content: center;\n        font-weight: 700;\n        color: var(--ml-ui-text, #222);\n        font-size: 12px;\n        background: transparent;\n        cursor: pointer;\n        padding: 0;\n      }\n\n      .ml-cli-close-btn:hover {\n        background: var(--ml-ui-border, rgba(0, 0, 0, 0.10));\n      }\n\n      .ml-cli-down,\n      .ml-cli-up {\n        width: 16px;\n        height: 16px;\n        display: inline-flex;\n        align-items: center;\n        justify-content: center;\n        border-radius: 3px;\n        background: transparent;\n        border: none;\n        cursor: pointer;\n        font-size: 16px;\n        color: var(--ml-ui-text, #222);\n        padding: 0;\n      }\n\n      .ml-cli-up {\n        transform: rotate(180deg);\n        transform-origin: center;\n      }\n\n      .ml-cli-right {\n        display: flex;\n        align-items: center;\n        justify-content: center;\n        background: var(--ml-ui-bg, rgba(0, 0, 0, 0.06));\n        border-radius: 4px;\n        border: 1px solid var(--ml-ui-border, rgba(0, 0, 0, 0.08));\n        height: 100%;\n      }\n\n      .ml-cli-center {\n        display: flex;\n        align-items: center;\n        flex: 1;\n        min-width: 0;\n        color: var(--ml-ui-text-muted, #333);\n        height: 100%; \n      }\n\n      .ml-cli-prompt {\n        display: flex;\n        align-items: center;\n        white-space: nowrap;\n        user-select: none;\n        margin-right: 4px;\n        line-height: 1;\n        font-family: \"Microsoft YaHei\", \"PingFang SC\", \"Segoe UI\", Arial, sans-serif;\n        font-size: 12px;\n        letter-spacing: 0;\n        word-spacing: 0;\n      }\n\n      .ml-cli-text {\n        flex: 1;\n        height: 100%;\n        border: none;\n        outline: none;\n        background: transparent;\n\n        font-family: \"Microsoft YaHei\", \"PingFang SC\", \"Segoe UI\", Arial, sans-serif;\n        font-size: 13px;\n        line-height: 1;\n        letter-spacing: 0;\n        word-spacing: 0;\n        padding: 0;\n        margin: 0;\n\n        display: flex;\n        align-items: center;\n        color: var(--ml-ui-text-muted, #333);\n      }\n\n      .ml-cli-option {\n        display: inline-block;\n        background: var(--ml-ui-bg, #f7f7f7);\n        border: 1px solid var(--ml-ui-border, rgba(0, 0, 0, 0.06));\n        padding: 1px 4px;\n        border-radius: 3px;\n        margin: 0 1px;\n        cursor: pointer;\n        font-size: 12px;\n        line-height: 1.1;\n        letter-spacing: 0;\n        word-spacing: 0;\n      }\n\n      .ml-cli-option:hover {\n        background: var(--ml-ui-border, #eaeaea);\n      }\n\n      .ml-cli-cmd-popup {\n        position: absolute;\n        bottom: 100%;\n        left: 0;\n        transform: translate(0, 0);\n        max-height: 220px;\n        overflow-y: auto;\n        background: var(--ml-ui-bg, #333);\n        border: 1px solid var(--ml-ui-border, rgba(0, 0, 0, 0.5));\n        box-shadow: var(--ml-ui-shadow, 0 6px 18px rgba(0, 0, 0, 0.35));\n        border-radius: 4px;\n        padding: 6px 0;\n        color: var(--ml-ui-text, #fff);\n      }\n\n      .ml-cli-cmd-popup .item {\n        padding: 8px 14px;\n        cursor: pointer;\n        color: var(--ml-ui-text, #fff);\n        font-size: 14px;\n      }\n\n      .ml-cli-cmd-popup .item:hover {\n        background: var(--ml-ui-border, #444);\n      }\n\n      .ml-cli-msg-panel {\n        position: absolute;\n        bottom: 100%;\n        left: 0;\n        transform: translate(0, 0);\n        max-height: 340px;\n        overflow-y: auto;\n        background: var(--ml-ui-bg, #333);\n        border: 1px solid var(--ml-ui-border, rgba(0, 0, 0, 0.5));\n        box-shadow: var(--ml-ui-shadow, 0 6px 18px rgba(0, 0, 0, 0.35));\n        border-radius: 4px;\n        padding: 6px 0;\n        font-family: \"Microsoft YaHei\", Arial, sans-serif;\n        color: var(--ml-ui-text, #fff);\n        font-size: 14px;\n        white-space: pre-wrap;\n        line-height: 1.35;\n      }\n\n      .ml-cli-history-line {\n        padding: 4px 6px;\n        color: var(--ml-ui-text, #fff);\n      }\n\n      .ml-cli-msg-error {\n        color: var(--ml-ui-danger, #ff5555);\n      }\n\n      .ml-cli-wrapper {\n        position: relative;\n        width: 100%;\n      }\n\n      .hidden {\n        display: none !important;\n      }\n\n      .ml-cli-cmd-popup::-webkit-scrollbar,\n      .ml-cli-msg-panel::-webkit-scrollbar {\n        width: 10px;\n      }\n\n      .ml-cli-cmd-popup::-webkit-scrollbar-thumb,\n      .ml-cli-msg-panel::-webkit-scrollbar-thumb {\n        background: var(--ml-ui-border, rgba(255, 255, 255, 0.2));\n        border-radius: 6px;\n      }\n    ";
        document.head.appendChild(style);
    };
    /** Create the command line UI elements */
    AcEdCommandLine.prototype.createUI = function () {
        this.cliContainer = document.createElement('div');
        this.cliContainer.className = 'ml-cli-container';
        this.cliContainer.style.position = this.useViewportPositioning()
            ? 'fixed'
            : 'absolute';
        if (!this.useViewportPositioning()) {
            var containerPosition = getComputedStyle(this.container).position;
            if (containerPosition === 'static') {
                this.container.style.position = 'relative';
            }
        }
        this.wrapper = document.createElement('div');
        this.wrapper.className = 'ml-cli-wrapper';
        this.cliContainer.appendChild(this.wrapper);
        this.bar = document.createElement('div');
        this.bar.className = 'ml-cli-bar';
        this.wrapper.appendChild(this.bar);
        /* ---------- left group ---------- */
        this.leftGroup = document.createElement('div');
        this.leftGroup.className = 'ml-cli-left';
        this.bar.appendChild(this.leftGroup);
        this.closeBtn = document.createElement('div');
        this.closeBtn.className = 'ml-cli-close-btn';
        this.closeBtn.innerHTML = '&#10005;';
        this.leftGroup.appendChild(this.closeBtn);
        this.downBtn = document.createElement('button');
        this.downBtn.className = 'ml-cli-down';
        this.downBtn.innerHTML = '&#9662;';
        this.leftGroup.appendChild(this.downBtn);
        /* ---------- center (prompt + input) ---------- */
        this.centerEl = document.createElement('div');
        this.centerEl.className = 'ml-cli-center';
        this.bar.appendChild(this.centerEl);
        this.promptEl = document.createElement('div');
        this.promptEl.className = 'ml-cli-prompt';
        this.centerEl.appendChild(this.promptEl);
        this.textInput = document.createElement('input');
        this.textInput.className = 'ml-cli-text';
        this.textInput.type = 'text';
        this.textInput.spellcheck = false;
        this.textInput.autocomplete = 'off';
        this.textInput.placeholder = this.localize('main.commandLine.placeholder');
        this.centerEl.appendChild(this.textInput);
        /* ---------- right group ---------- */
        var rightGroup = document.createElement('div');
        rightGroup.className = 'ml-cli-right';
        this.bar.appendChild(rightGroup);
        this.upBtn = document.createElement('button');
        this.upBtn.className = 'ml-cli-up';
        this.upBtn.innerHTML = '&#9662;';
        rightGroup.appendChild(this.upBtn);
        /* ---------- popups ---------- */
        this.cmdPopup = document.createElement('div');
        this.cmdPopup.className = 'ml-cli-cmd-popup hidden';
        this.wrapper.appendChild(this.cmdPopup);
        this.msgPanel = document.createElement('div');
        this.msgPanel.className = 'ml-cli-msg-panel hidden';
        this.wrapper.appendChild(this.msgPanel);
        this.container.appendChild(this.cliContainer);
    };
    /** Bind event listeners */
    AcEdCommandLine.prototype.bindEvents = function () {
        var _this = this;
        // Close command line when clicking the button
        this.closeBtn.addEventListener('click', function (e) {
            e.stopPropagation();
            _this.visible = false;
            AcApSettingManager.instance.isShowCommandLine = false;
        });
        this.downBtn.addEventListener('click', function (e) {
            e.stopPropagation();
            _this.isCmdPopupOpen = !_this.isCmdPopupOpen;
            _this.updatePopups({ showCmd: _this.isCmdPopupOpen, showMsg: false });
            if (_this.isCmdPopupOpen)
                _this.showCommandHistoryPopup();
        });
        this.upBtn.addEventListener('click', function (e) {
            e.stopPropagation();
            _this.isMsgPanelOpen = !_this.isMsgPanelOpen;
            _this.updatePopups({ showCmd: false, showMsg: _this.isMsgPanelOpen });
            if (_this.isMsgPanelOpen)
                _this.showMessagePanel();
        });
        document.addEventListener('click', function (e) {
            if (!_this.cliContainer.contains(e.target)) {
                _this.updatePopups({ showCmd: false, showMsg: false });
            }
        });
        this.textInput.addEventListener('keydown', function (e) { return _this.handleKeyDown(e); });
        this.textInput.addEventListener('input', function () { return _this.handleInputChange(); });
        this.centerEl.addEventListener('focus', function () {
            return _this.updatePopups({ showCmd: false, showMsg: false });
        });
        this.cmdPopup.addEventListener('click', function (e) {
            var item = e.target.closest('.item');
            if (item) {
                _this.setInputText(item.dataset.value || '');
                _this.centerEl.focus();
                _this.updatePopups({ showCmd: false, showMsg: false });
            }
        });
    };
    /** Handle Enter/Escape keys */
    AcEdCommandLine.prototype.handleKeyDown = function (e) {
        // IME / composition safety (important!)
        if (e.isComposing)
            return;
        switch (e.key) {
            case 'Enter': {
                e.preventDefault();
                e.stopImmediatePropagation();
                if (this.activeSession) {
                    var handled = this.activeSession.handleEnter(this.getInputText());
                    if (!handled) {
                        this.printError(this.localize('main.commandLine.invalidKeyword'));
                    }
                    return;
                }
                this.executeCommand(this.getInputText());
                this.historyIndex = this.history.length;
                this.updatePopups({ showCmd: false, showMsg: false });
                return;
            }
            case 'Escape': {
                e.preventDefault();
                e.stopImmediatePropagation();
                if (this.activeSession) {
                    this.activeSession.handleEscape();
                    this.activeSession = undefined;
                    return;
                }
                this.clear();
                this.printMessage(this.localize('main.commandLine.canceled'));
                this.updatePopups({ showCmd: false, showMsg: false });
                return;
            }
            case 'ArrowUp': {
                e.preventDefault();
                if (this.isCmdPopupOpen)
                    this.navigateAutoComplete(-1);
                else
                    this.navigateHistory(-1);
                return;
            }
            case 'ArrowDown': {
                e.preventDefault();
                if (this.isCmdPopupOpen)
                    this.navigateAutoComplete(1);
                else
                    this.navigateHistory(1);
                return;
            }
            case 'Backspace':
            case 'Delete': {
                // Let the input handle deletion, but do not bubble to global handlers
                // that might delete selected entities.
                e.stopPropagation();
                e.stopImmediatePropagation();
                return;
            }
        }
    };
    /** Handle input change to show auto-complete */
    AcEdCommandLine.prototype.handleInputChange = function () {
        var _this = this;
        var text = this.getInputText();
        if (!text) {
            this.updatePopups({ showCmd: false });
            return;
        }
        var matches = AcApDocManager.instance.searchCommandsByPrefix(text);
        if (matches.length) {
            this.autoCompleteIndex = -1;
            this.cmdPopup.innerHTML = '';
            matches.forEach(function (item, idx) {
                var div = document.createElement('div');
                div.className = 'item';
                div.dataset.value = item.command.globalName;
                var description = AcApI18n.cmdDescription(item.commandGroup, item.command.globalName);
                var aliases = AcApDocManager.instance.commandManager.getCommandAliases(item.command, item.commandGroup);
                var aliasText = aliases.length ? "(".concat(aliases.join(', '), ")") : '';
                div.innerHTML = "<strong>".concat(item.command.globalName).concat(aliasText, " - ").concat(description, "</strong>");
                if (idx === _this.autoCompleteIndex)
                    div.classList.add('selected');
                _this.cmdPopup.appendChild(div);
            });
            this.updatePopups({ showCmd: true });
        }
        else {
            this.updatePopups({ showCmd: false });
        }
    };
    /** Navigate auto-complete list with arrow keys */
    AcEdCommandLine.prototype.navigateAutoComplete = function (dir) {
        var _this = this;
        var _a;
        var items = Array.from(this.cmdPopup.querySelectorAll('.item'));
        if (!items.length)
            return;
        this.autoCompleteIndex += dir;
        if (this.autoCompleteIndex < 0)
            this.autoCompleteIndex = 0;
        if (this.autoCompleteIndex >= items.length)
            this.autoCompleteIndex = items.length - 1;
        items.forEach(function (el, idx) {
            el.classList.toggle('selected', idx === _this.autoCompleteIndex);
        });
        var selected = items[this.autoCompleteIndex];
        if (selected) {
            this.setInputText((_a = selected.dataset.value) !== null && _a !== void 0 ? _a : '');
        }
    };
    /** Navigate command history */
    AcEdCommandLine.prototype.navigateHistory = function (dir) {
        if (!this.history.length)
            return;
        if (this.historyIndex === -1)
            this.historyIndex = this.history.length;
        this.historyIndex += dir;
        if (this.historyIndex < 0)
            this.historyIndex = 0;
        if (this.historyIndex > this.history.length)
            this.historyIndex = this.history.length;
        if (this.historyIndex >= 0 && this.historyIndex < this.history.length) {
            this.setInputText(this.history[this.historyIndex]);
        }
        else {
            this.setInputText('');
        }
    };
    /** Get current input text */
    AcEdCommandLine.prototype.getInputText = function () {
        return this.textInput.value.trim();
    };
    /** Set input text */
    AcEdCommandLine.prototype.setInputText = function (text) {
        if (text === void 0) { text = ''; }
        this.textInput.value = text;
        this.textInput.focus();
    };
    /** Render prompt message and keyword options in command line */
    AcEdCommandLine.prototype.renderKeywordPrompt = function (options, onClick) {
        var _this = this;
        var _a;
        this.promptEl.innerHTML = '';
        this.isPromptActive = true;
        // Hide default placeholder when showing a prompt/keyword message.
        this.textInput.placeholder = '';
        if (options.message) {
            this.promptEl.append(options.message.trim() + ' ');
        }
        var promptFormat = options.getKeywordPromptFormat();
        if (!promptFormat.visibleKeywords.length)
            return;
        var keywords = (_a = options.keywords) === null || _a === void 0 ? void 0 : _a.toArray().filter(function (k) { return k.visible; });
        if (!(keywords === null || keywords === void 0 ? void 0 : keywords.length))
            return;
        this.promptEl.append('[');
        keywords.forEach(function (kw, i) {
            if (i > 0)
                _this.promptEl.append('/');
            var span = document.createElement('span');
            span.className = 'ml-cli-option';
            span.textContent = kw.displayName;
            if (!kw.enabled) {
                span.style.opacity = '0.45';
                span.style.pointerEvents = 'none';
            }
            else {
                span.onclick = function () { return onClick(kw.globalName); };
            }
            _this.promptEl.append(span);
        });
        this.promptEl.append(']');
        if (promptFormat.defaultKeyword) {
            this.promptEl.append(" <".concat(promptFormat.defaultKeyword, ">"));
        }
        this.promptEl.append(': ');
    };
    /** Resolve command name */
    AcEdCommandLine.prototype.resolveCommand = function (cmdLine) {
        var parts = cmdLine.trim().split(/\s+/);
        var cmdStr = parts[0].toUpperCase();
        // TODO: Should look up local cmd too
        return AcApDocManager.instance.lookupLocalCmd(cmdStr);
    };
    /** Show or hide popups */
    AcEdCommandLine.prototype.updatePopups = function (_a) {
        var _b = _a === void 0 ? {} : _a, _c = _b.showCmd, showCmd = _c === void 0 ? false : _c, _d = _b.showMsg, showMsg = _d === void 0 ? false : _d;
        this.isCmdPopupOpen = showCmd;
        this.isMsgPanelOpen = showMsg;
        this.cmdPopup.classList.toggle('hidden', !showCmd);
        this.msgPanel.classList.toggle('hidden', !showMsg);
        if (showCmd)
            this.positionCmdPopup();
        if (showMsg)
            this.positionMsgPanel();
    };
    /** Show command history popup */
    AcEdCommandLine.prototype.showCommandHistoryPopup = function () {
        this.cmdPopup.innerHTML = '';
        if (!this.history.length) {
            var empty = document.createElement('div');
            empty.className = 'item';
            empty.textContent = this.localize('main.commandLine.noHistory');
            this.cmdPopup.appendChild(empty);
        }
        else {
            for (var i = this.history.length - 1; i >= 0; i--) {
                var item = document.createElement('div');
                item.className = 'item';
                item.dataset.value = this.history[i];
                item.textContent = this.history[i];
                this.cmdPopup.appendChild(item);
            }
        }
        this.positionCmdPopup();
    };
    /** Position command history popup */
    AcEdCommandLine.prototype.positionCmdPopup = function () {
        this.cmdPopup.style.left = '0px';
        this.cmdPopup.style.width = this.bar.offsetWidth + 'px';
    };
    /** Show message panel */
    AcEdCommandLine.prototype.showMessagePanel = function () {
        // If there is no message history, show a localized "no history" placeholder
        if (!this.msgPanel.children.length) {
            var empty = document.createElement('div');
            empty.className = 'ml-cli-history-line';
            empty.textContent = this.localize('main.commandLine.noHistory');
            empty.dataset.msgKey = 'main.commandLine.noHistory';
            this.msgPanel.appendChild(empty);
        }
        this.msgPanel.scrollTop = this.msgPanel.scrollHeight;
        this.positionMsgPanel();
    };
    /** Position message panel */
    AcEdCommandLine.prototype.positionMsgPanel = function () {
        this.msgPanel.style.width = this.bar.offsetWidth + 'px';
    };
    /** Remove "no history" placeholder if present */
    AcEdCommandLine.prototype.clearNoHistoryPlaceholder = function () {
        var _this = this;
        Array.from(this.msgPanel.children).forEach(function (child) {
            var div = child;
            if (div.dataset.msgKey === 'main.commandLine.noHistory') {
                _this.msgPanel.removeChild(div);
            }
        });
    };
    /** Print message to message panel with optional localization key */
    AcEdCommandLine.prototype.printMessage = function (msg, msgKey) {
        this.clearNoHistoryPlaceholder();
        var div = document.createElement('div');
        div.className = 'ml-cli-history-line';
        div.textContent = msg;
        if (msgKey)
            div.dataset.msgKey = msgKey;
        this.msgPanel.appendChild(div);
        this.showMessagePanel();
    };
    /** Print error message with optional localization key */
    AcEdCommandLine.prototype.printError = function (msg, msgKey) {
        this.clearNoHistoryPlaceholder();
        var div = document.createElement('div');
        div.className = 'ml-cli-history-line ml-cli-msg-error';
        div.textContent = msg;
        if (msgKey)
            div.dataset.msgKey = msgKey;
        this.msgPanel.appendChild(div);
        this.showMessagePanel();
    };
    /** Print executed command line to history */
    AcEdCommandLine.prototype.printHistoryLine = function (cmdLine) {
        this.clearNoHistoryPlaceholder();
        var div = document.createElement('div');
        div.className = 'ml-cli-history-line';
        div.textContent = '> ' + cmdLine;
        // For executed command messages, also store msgKey
        div.dataset.msgKey = 'main.commandLine.executed';
        this.msgPanel.appendChild(div);
        this.showMessagePanel();
    };
    /** Handle window resize */
    AcEdCommandLine.prototype.resizeHandler = function () {
        var hostWidth = this.useViewportPositioning()
            ? window.innerWidth
            : this.container.getBoundingClientRect().width;
        // Calculate desired width based on ratio and minimum width
        var w = Math.max(this.minWidth, hostWidth * this.widthRatio);
        // Clamp width so it never exceeds the host container width
        w = Math.min(w, Math.max(200, hostWidth - 20));
        this.bar.style.width = w + 'px';
        // Reposition popups to match new width
        this.positionMsgPanel();
        this.positionCmdPopup();
    };
    AcEdCommandLine.prototype.useViewportPositioning = function () {
        return this.container === document.body;
    };
    return AcEdCommandLine;
}());
export { AcEdCommandLine };
//# sourceMappingURL=AcEdCommandLine.js.map