import { h } from "@stencil/core";
import { createClickOutsideHandler } from "../../utils/click-outside";
import { handleListKeyboard } from "../../utils/a11y";
/**
 * Select 选择器组件
 * 当选项过多时，使用下拉菜单展示并选择内容
 */
export class Select {
    el;
    /**
     * 绑定值
     */
    modelValue;
    /**
     * 可选项数据源
     */
    options = [];
    /**
     * 输入框占位文本
     */
    placeholder = '请选择';
    /**
     * 是否禁用
     * @default false
     */
    disabled = false;
    /**
     * 输入框尺寸
     */
    size = 'default';
    /**
     * 是否可清空
     * @default false
     */
    clearable = false;
    /**
     * 是否多选
     * @default false
     */
    multiple = false;
    /**
     * 是否可搜索
     * @default false
     */
    filterable = false;
    /**
     * 自定义过滤方法
     */
    filterMethod;
    /**
     * 是否默认展开
     * @default false
     */
    defaultFirstOption = false;
    /**
     * 是否允许创建新条目
     * @default false
     */
    allowCreate = false;
    /**
     * 多选时是否将选中值按文字的形式展示
     * @default false
     */
    collapseTags = false;
    /**
     * 多选时最多显示多少个tag
     */
    maxCollapseTags;
    isOpen = false;
    inputValue = '';
    searchValue = '';
    filteredOptions = [];
    /** 键盘高亮的选项索引（-1 表示无） */
    activeOptionIndex = -1;
    /**
     * 值改变事件
     */
    hbChange;
    /**
     * 下拉框出现/隐藏时触发
     */
    hbVisibleChange;
    clickOutside = createClickOutsideHandler({
        host: null,
        isOpen: () => this.isOpen,
        onClose: () => { this.isOpen = false; this.hbVisibleChange.emit(false); },
    });
    componentDidLoad() {
        this.clickOutside = createClickOutsideHandler({
            host: this.el,
            isOpen: () => this.isOpen,
            onClose: () => { this.isOpen = false; this.hbVisibleChange.emit(false); },
        });
        this.clickOutside.connect();
        this.updateInputValue();
        if (this.filterable) {
            this.filteredOptions = this.options;
        }
    }
    disconnectedCallback() {
        this.clickOutside.disconnect();
    }
    handleValueChange() {
        this.updateInputValue();
    }
    handleOptionsChange() {
        if (this.filterable) {
            this.filteredOptions = this.options;
        }
    }
    updateInputValue() {
        if (!this.modelValue) {
            this.inputValue = '';
            return;
        }
        if (this.multiple && Array.isArray(this.modelValue)) {
            const labels = this.modelValue.map(val => {
                const option = this.options.find(opt => opt.value === val);
                return option ? option.label : String(val);
            });
            this.inputValue = labels.join(', ');
        }
        else {
            const option = this.options.find(opt => opt.value === this.modelValue);
            this.inputValue = option ? option.label : String(this.modelValue);
        }
    }
    handleInputClick = () => {
        if (this.disabled)
            return;
        this.isOpen = !this.isOpen;
        if (this.isOpen)
            this.activeOptionIndex = -1;
        this.hbVisibleChange.emit(this.isOpen);
    };
    handleWrapperKeydown = (e) => {
        if (this.disabled)
            return;
        const displayOptions = this.filterable ? this.filteredOptions : this.options;
        if (!this.isOpen) {
            // 关闭态：Enter / Space / 方向键 展开
            if (e.key === 'Enter' || e.key === ' ' || e.key === 'Spacebar' ||
                e.key === 'ArrowDown' || e.key === 'ArrowUp') {
                e.preventDefault();
                this.isOpen = true;
                this.activeOptionIndex = -1;
                this.hbVisibleChange.emit(true);
            }
            return;
        }
        const action = handleListKeyboard(e, {
            activeIndex: this.activeOptionIndex,
            itemCount: displayOptions.length,
            loop: true,
        });
        switch (action.type) {
            case 'navigate':
                e.preventDefault();
                this.activeOptionIndex = action.index;
                break;
            case 'select': {
                e.preventDefault();
                const opt = displayOptions[action.index];
                if (opt && !opt.disabled)
                    this.handleSelect(opt);
                break;
            }
            case 'close':
                e.preventDefault();
                this.isOpen = false;
                this.hbVisibleChange.emit(false);
                break;
            default:
                break;
        }
    };
    handleSelect = (option) => {
        if (option.disabled)
            return;
        if (this.multiple) {
            const currentValue = this.modelValue || [];
            const index = currentValue.indexOf(option.value);
            if (index > -1) {
                currentValue.splice(index, 1);
            }
            else {
                currentValue.push(option.value);
            }
            this.modelValue = [...currentValue];
        }
        else {
            this.modelValue = option.value;
            this.isOpen = false;
            this.hbVisibleChange.emit(false);
        }
        this.updateInputValue();
        this.hbChange.emit(this.modelValue);
    };
    handleClear = (e) => {
        e.stopPropagation();
        this.modelValue = this.multiple ? [] : undefined;
        this.inputValue = '';
        this.isOpen = false;
        this.hbChange.emit(this.modelValue);
        this.hbVisibleChange.emit(false);
    };
    handleSearch = (e) => {
        const target = e.target;
        this.searchValue = target.value;
        if (this.filterMethod) {
            this.filterMethod(target.value);
        }
        else {
            this.filteredOptions = this.options.filter(opt => opt.label.toLowerCase().includes(target.value.toLowerCase()));
        }
    };
    isSelected(option) {
        if (this.multiple && Array.isArray(this.modelValue)) {
            return this.modelValue.includes(option.value);
        }
        return this.modelValue === option.value;
    }
    render() {
        const displayOptions = this.filterable ? this.filteredOptions : this.options;
        const showClear = this.clearable && this.modelValue !== undefined &&
            (this.multiple ? this.modelValue.length > 0 : true);
        return (h("div", { key: '74d4a02c34f152b6795a11a54a276a2325e28fc8', class: {
                'hb-select': true,
                'hb-select--open': this.isOpen,
                'hb-select--disabled': this.disabled,
                [`hb-select--${this.size}`]: true,
            }, "aria-haspopup": "listbox", "aria-expanded": this.isOpen ? 'true' : 'false' }, h("div", { key: 'acc60d9dd0cafa2264fae4bb2e468f9921eaf210', class: "hb-select__input-wrapper", onClick: this.handleInputClick, onKeyDown: this.handleWrapperKeydown }, this.multiple && Array.isArray(this.modelValue) && this.modelValue.length > 0 ? (h("div", { class: "hb-select__tags" }, this.modelValue.slice(0, this.collapseTags && this.maxCollapseTags ? this.maxCollapseTags : undefined).map((val) => {
            const option = this.options.find(opt => opt.value === val);
            return (h("span", { class: "hb-select__tag" }, h("span", { class: "hb-select__tag-text" }, option ? option.label : val), h("span", { class: "hb-select__tag-close", role: "button", "aria-label": "\u79FB\u9664\u6807\u7B7E", onClick: (e) => {
                    e.stopPropagation();
                    this.handleSelect(option || { value: val, label: String(val) });
                } }, "\u00D7")));
        }), this.collapseTags && this.maxCollapseTags && this.modelValue.length > this.maxCollapseTags && (h("span", { class: "hb-select__tag" }, h("span", { class: "hb-select__tag-text" }, "+", this.modelValue.length - this.maxCollapseTags))))) : (h("input", { type: "text", class: "hb-select__input", placeholder: this.placeholder, value: this.filterable && this.isOpen ? this.searchValue : this.inputValue, disabled: this.disabled, readonly: !this.filterable || !this.isOpen, onInput: this.handleSearch, "aria-haspopup": "listbox", "aria-expanded": this.isOpen ? 'true' : 'false', role: "combobox" })), h("span", { key: 'af18dc75d5ae183d953ff4c1ae9a1c437f5cb4f9', class: "hb-select__suffix" }, showClear && (h("span", { key: '23d6891fa82878f78de89dea464c1a1787be6695', class: "hb-select__clear", role: "button", "aria-label": "\u6E05\u7A7A", onClick: this.handleClear }, "\u00D7")), h("span", { key: '45bef57ec15707fe4f9c9b5fa4699eb8082b27d4', class: "hb-select__arrow" }, "\u25BC"))), this.isOpen && (h("div", { key: 'a359fae561a9a25f85a72437f88f6ab11abcd90a', class: "hb-select__dropdown" }, h("ul", { key: 'f599eb59c8ff2f7e3effe395253a11c7934b41b8', class: "hb-select__menu", role: "listbox" }, displayOptions.length === 0 ? (h("li", { class: "hb-select__menu-item hb-select__menu-item--empty", "aria-disabled": "true" }, "\u65E0\u6570\u636E")) : (displayOptions.map((option, index) => (h("li", { class: {
                'hb-select__menu-item': true,
                'hb-select__menu-item--selected': this.isSelected(option),
                'hb-select__menu-item--disabled': option.disabled,
                'hb-select__menu-item--divided': option.divided,
                'hb-select__menu-item--active': index === this.activeOptionIndex,
            }, role: "option", "aria-selected": this.isSelected(option) ? 'true' : 'false', "aria-disabled": option.disabled ? 'true' : undefined, onClick: () => this.handleSelect(option) }, this.multiple && (h("span", { class: "hb-select__menu-item-checkbox" }, this.isSelected(option) ? '✓' : '')), h("span", { class: "hb-select__menu-item-label" }, option.label))))))))));
    }
    static get is() { return "hb-select"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["select.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["select.css"]
        };
    }
    static get properties() {
        return {
            "modelValue": {
                "type": "any",
                "mutable": true,
                "complexType": {
                    "original": "string | number | (string | number)[]",
                    "resolved": "(string | number)[] | number | string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "\u7ED1\u5B9A\u503C"
                },
                "getter": false,
                "setter": false,
                "attribute": "model-value",
                "reflect": false
            },
            "options": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "SelectOption[]",
                    "resolved": "SelectOption[]",
                    "references": {
                        "SelectOption": {
                            "location": "local",
                            "path": "/Users/vscoderwhy/Desktop/product/web-common/huibo-ui/src/components/Select/Select.tsx",
                            "id": "src/components/Select/Select.tsx::SelectOption"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "\u53EF\u9009\u9879\u6570\u636E\u6E90"
                },
                "getter": false,
                "setter": false,
                "defaultValue": "[]"
            },
            "placeholder": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "\u8F93\u5165\u6846\u5360\u4F4D\u6587\u672C"
                },
                "getter": false,
                "setter": false,
                "attribute": "placeholder",
                "reflect": false,
                "defaultValue": "'\u8BF7\u9009\u62E9'"
            },
            "disabled": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "default",
                            "text": "false"
                        }],
                    "text": "\u662F\u5426\u7981\u7528"
                },
                "getter": false,
                "setter": false,
                "attribute": "disabled",
                "reflect": false,
                "defaultValue": "false"
            },
            "size": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "'large' | 'default' | 'small'",
                    "resolved": "\"default\" | \"large\" | \"small\"",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "\u8F93\u5165\u6846\u5C3A\u5BF8"
                },
                "getter": false,
                "setter": false,
                "attribute": "size",
                "reflect": false,
                "defaultValue": "'default'"
            },
            "clearable": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "default",
                            "text": "false"
                        }],
                    "text": "\u662F\u5426\u53EF\u6E05\u7A7A"
                },
                "getter": false,
                "setter": false,
                "attribute": "clearable",
                "reflect": false,
                "defaultValue": "false"
            },
            "multiple": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "default",
                            "text": "false"
                        }],
                    "text": "\u662F\u5426\u591A\u9009"
                },
                "getter": false,
                "setter": false,
                "attribute": "multiple",
                "reflect": false,
                "defaultValue": "false"
            },
            "filterable": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "default",
                            "text": "false"
                        }],
                    "text": "\u662F\u5426\u53EF\u641C\u7D22"
                },
                "getter": false,
                "setter": false,
                "attribute": "filterable",
                "reflect": false,
                "defaultValue": "false"
            },
            "filterMethod": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "(query: string) => void",
                    "resolved": "(query: string) => void",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "\u81EA\u5B9A\u4E49\u8FC7\u6EE4\u65B9\u6CD5"
                },
                "getter": false,
                "setter": false
            },
            "defaultFirstOption": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "default",
                            "text": "false"
                        }],
                    "text": "\u662F\u5426\u9ED8\u8BA4\u5C55\u5F00"
                },
                "getter": false,
                "setter": false,
                "attribute": "default-first-option",
                "reflect": false,
                "defaultValue": "false"
            },
            "allowCreate": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "default",
                            "text": "false"
                        }],
                    "text": "\u662F\u5426\u5141\u8BB8\u521B\u5EFA\u65B0\u6761\u76EE"
                },
                "getter": false,
                "setter": false,
                "attribute": "allow-create",
                "reflect": false,
                "defaultValue": "false"
            },
            "collapseTags": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "default",
                            "text": "false"
                        }],
                    "text": "\u591A\u9009\u65F6\u662F\u5426\u5C06\u9009\u4E2D\u503C\u6309\u6587\u5B57\u7684\u5F62\u5F0F\u5C55\u793A"
                },
                "getter": false,
                "setter": false,
                "attribute": "collapse-tags",
                "reflect": false,
                "defaultValue": "false"
            },
            "maxCollapseTags": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "\u591A\u9009\u65F6\u6700\u591A\u663E\u793A\u591A\u5C11\u4E2Atag"
                },
                "getter": false,
                "setter": false,
                "attribute": "max-collapse-tags",
                "reflect": false
            }
        };
    }
    static get states() {
        return {
            "isOpen": {},
            "inputValue": {},
            "searchValue": {},
            "filteredOptions": {},
            "activeOptionIndex": {}
        };
    }
    static get events() {
        return [{
                "method": "hbChange",
                "name": "hbChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "\u503C\u6539\u53D8\u4E8B\u4EF6"
                },
                "complexType": {
                    "original": "string | number | (string | number)[]",
                    "resolved": "(string | number)[] | number | string",
                    "references": {}
                }
            }, {
                "method": "hbVisibleChange",
                "name": "hbVisibleChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "\u4E0B\u62C9\u6846\u51FA\u73B0/\u9690\u85CF\u65F6\u89E6\u53D1"
                },
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                }
            }];
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "modelValue",
                "methodName": "handleValueChange"
            }, {
                "propName": "options",
                "methodName": "handleOptionsChange"
            }];
    }
}
//# sourceMappingURL=Select.js.map
