import { Host, h } from "@stencil/core";
import { autoUpdate, computePosition, flip, offset, shift } from "@floating-ui/dom";
import { configStore } from "../../store/store";
export class ZMultiDropdownInput {
    el;
    label;
    placeholder = '';
    value = [];
    options = [];
    disabled = false;
    enableSearch = true;
    disabledOptions = [];
    showClearButton = false;
    valueChange;
    isOpen = false;
    searchQuery = '';
    isPositioned = false;
    triggerEl;
    popperEl;
    cleanup;
    componentDidLoad() {
        document.addEventListener('click', this.handleClickOutside);
    }
    componentDidRender() {
        if (this.isOpen && this.popperEl && !this.cleanup) {
            this.updatePosition();
        }
    }
    disconnectedCallback() {
        document.removeEventListener('click', this.handleClickOutside);
        if (this.cleanup) {
            this.cleanup();
            this.cleanup = undefined;
        }
    }
    handleClickOutside = (e) => {
        if (!this.isOpen)
            return;
        const path = e.composedPath();
        if (!path.includes(this.triggerEl) && !path.includes(this.popperEl)) {
            this.isOpen = false;
            this.searchQuery = '';
        }
    };
    updatePosition() {
        if (!this.triggerEl || !this.popperEl)
            return;
        if (this.cleanup) {
            this.cleanup();
        }
        this.cleanup = autoUpdate(this.triggerEl, this.popperEl, () => {
            computePosition(this.triggerEl, this.popperEl, {
                placement: 'bottom-start',
                strategy: 'fixed',
                middleware: [
                    offset(4),
                    flip(),
                    shift({ padding: 5 })
                ],
            }).then(({ x, y }) => {
                Object.assign(this.popperEl.style, {
                    left: `${x}px`,
                    top: `${y}px`,
                    position: 'fixed',
                    opacity: '1',
                });
                if (!this.isPositioned) {
                    this.isPositioned = true;
                    if (this.enableSearch) {
                        this.popperEl?.querySelector('input')?.focus();
                    }
                }
            });
        });
    }
    watchIsOpen(isOpen) {
        if (isOpen) {
            this.isPositioned = false;
        }
        else {
            if (this.cleanup) {
                this.cleanup();
                this.cleanup = undefined;
            }
            this.searchQuery = '';
            this.isPositioned = false;
        }
    }
    toggleDropdown = () => {
        if (this.disabled)
            return;
        this.isOpen = !this.isOpen;
    };
    handleSearch = (e) => {
        this.searchQuery = e.target.value;
    };
    handleToggleSelect = (val, e) => {
        if (e)
            e.stopPropagation();
        const newValue = [...this.value];
        const index = newValue.indexOf(val);
        if (index > -1) {
            newValue.splice(index, 1);
        }
        else {
            newValue.push(val);
        }
        this.valueChange.emit(newValue);
    };
    handleClearAll = (e) => {
        e.stopPropagation();
        this.valueChange.emit([]);
        this.isOpen = false;
    };
    handleRemoveChip = (val, e) => {
        e.stopPropagation();
        this.handleToggleSelect(val);
    };
    render() {
        const theme = configStore.get('theme');
        const filteredOptions = this.options.filter(opt => {
            if (!this.searchQuery)
                return true;
            return opt.label.toLowerCase().includes(this.searchQuery.toLowerCase());
        });
        const selectedOptions = this.options.filter(opt => this.value.includes(opt.value));
        return (h(Host, { "data-theme": theme }, this.label && h("label", { class: "z-input-label mb-1 block text-sm font-medium text-surface" }, this.label), h("div", { class: "block" }, h("div", { class: `z-input border-divider bg-background text-surface min-h-10 w-full flex items-center justify-between px-3 py-1.5 border rounded-md cursor-pointer ${this.disabled ? 'opacity-50 cursor-not-allowed' : ''}`, onClick: this.toggleDropdown, ref: (el) => (this.triggerEl = el) }, h("div", { class: "flex flex-wrap gap-1.5 flex-1 items-center mr-2" }, selectedOptions.length > 0 ? (selectedOptions.map(opt => (h("div", { class: "flex items-center gap-1 px-2.5 py-0.5 bg-surface/10 rounded-full text-sm shrink-0", onClick: (e) => e.stopPropagation() }, h("span", { class: "truncate max-w-[120px]" }, opt.label), h("div", { class: "ml-1 cursor-pointer hover:text-primary transition-colors flex items-center justify-center p-0.5", onClick: (e) => this.handleRemoveChip(opt.value, e) }, h("svg", { class: "w-3 h-3 fill-current", viewBox: "0 0 24 24" }, h("path", { d: "M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" }))))))) : (h("span", { class: "text-surface/50 truncate py-0.5" }, this.placeholder))), h("div", { class: "flex items-center gap-1 shrink-0" }, this.showClearButton && this.value.length > 0 && !this.disabled && (h("div", { class: "p-1 hover:bg-surface/10 rounded-full transition-colors cursor-pointer", onClick: this.handleClearAll }, h("svg", { class: "h-4 w-4 fill-current opacity-50 shrink-0", viewBox: "0 0 24 24" }, h("path", { d: "M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" })))), h("svg", { class: "h-4 w-4 fill-current opacity-50 shrink-0", xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20" }, h("path", { d: "M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" })))), this.isOpen && (h("div", { class: "bg-background border border-divider rounded-lg shadow-xl flex flex-col mt-1 overflow-hidden", ref: (el) => (this.popperEl = el), style: {
                position: 'fixed',
                zIndex: '9999',
                width: this.triggerEl ? `${this.triggerEl.offsetWidth}px` : 'auto',
                maxHeight: '240px',
                opacity: this.isPositioned ? '1' : '0',
            } }, this.enableSearch && (h("div", { class: "p-2 border-b border-divider bg-background shrink-0" }, h("input", { type: "text", class: "w-full px-2 py-1 text-sm text-surface border border-divider rounded outline-none focus:border-primary bg-background", placeholder: "Search...", value: this.searchQuery, onInput: this.handleSearch, onClick: (e) => e.stopPropagation() }))), h("div", { class: "overflow-y-auto flex-1 py-1" }, filteredOptions.length > 0 ? (filteredOptions.map(opt => {
            const isDisabled = this.disabledOptions?.includes(opt.value);
            const isSelected = this.value.includes(opt.value);
            return (h("div", { class: `flex items-center gap-3 px-3 py-2 text-sm transition-colors
                          ${isDisabled ? 'opacity-50 cursor-not-allowed text-surface/50' : 'cursor-pointer hover:bg-surface/10 text-surface'}
                          ${isSelected ? 'bg-surface/5 font-medium' : ''}`, onClick: (e) => !isDisabled && this.handleToggleSelect(opt.value, e) }, h("div", { class: `flex items-center justify-center w-4 h-4 rounded border shrink-0 transition-colors
                          ${isSelected ? 'bg-primary border-primary text-white' : 'border-divider bg-transparent'}
                        ` }, isSelected && (h("svg", { class: "w-3 h-3 fill-current", viewBox: "0 0 24 24" }, h("path", { d: "M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z" })))), h("span", { class: "truncate" }, opt.label)));
        })) : (h("div", { class: "px-3 py-4 text-sm text-surface/50 text-center" }, "No options found"))))))));
    }
    static get is() { return "z-multi-dropdown-input"; }
    static get originalStyleUrls() {
        return {
            "$": ["z-multi-dropdown-input.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["z-multi-dropdown-input.css"]
        };
    }
    static get properties() {
        return {
            "label": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "label"
            },
            "placeholder": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "placeholder",
                "defaultValue": "''"
            },
            "value": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "string[]",
                    "resolved": "string[]",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "defaultValue": "[]"
            },
            "options": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "OptionValue[]",
                    "resolved": "OptionValue[]",
                    "references": {
                        "OptionValue": {
                            "location": "import",
                            "path": "../../store/zdesk.type",
                            "id": "src/store/zdesk.type.ts::OptionValue",
                            "referenceLocation": "OptionValue"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "defaultValue": "[]"
            },
            "disabled": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "disabled",
                "defaultValue": "false"
            },
            "enableSearch": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "enable-search",
                "defaultValue": "true"
            },
            "disabledOptions": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "string[]",
                    "resolved": "string[]",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "defaultValue": "[]"
            },
            "showClearButton": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "show-clear-button",
                "defaultValue": "false"
            }
        };
    }
    static get states() {
        return {
            "isOpen": {},
            "searchQuery": {},
            "isPositioned": {}
        };
    }
    static get events() {
        return [{
                "method": "valueChange",
                "name": "valueChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "string[]",
                    "resolved": "string[]",
                    "references": {}
                }
            }];
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "isOpen",
                "methodName": "watchIsOpen"
            }];
    }
}
