import { h, Host } from "@stencil/core";
import { guid } from "../../utils";
import { SxStyleManager } from "../../utils/sx-style-manager";
export class DgaDropdown {
    constructor() {
        this.id = guid();
        this.size = 'lg';
        this.variant = 'default';
        this.error = false;
        this.disabled = false;
        this.readonly = false;
        this.multiSelect = false;
        this.options = [];
        this.optionLabel = 'name';
        this.trackBy = 'value';
        this.optionList = [];
        this.dropdownOpen = false;
        this.handleClickOutside = (event) => {
            if (this.containerRef && !this.containerRef.contains(event.target)) {
                this.closeDropdown();
            }
        };
        // Generate a unique ID if not provided
        this.componentId = `dga-dropdown-${Math.random().toString(36).substring(2, 9)}`;
        // Computed inline styles
        this.rootStyles = {};
    }
    handleValueChange(newValue) {
        if (newValue) {
            this.updateSelectedFromValue(newValue);
        }
    }
    initializeOptions() {
        const cloneList = [...this.options].map(option => (Object.assign(Object.assign({}, option), { selected: false })));
        this.optionList = cloneList;
        // If we have a value, update selections after options change
        if (this.value) {
            this.updateSelectedFromValue(this.value);
        }
    }
    updateSelectedFromValue(value) {
        const cloneList = [...this.optionList];
        if (this.multiSelect && Array.isArray(value)) {
            cloneList.forEach(option => {
                option.selected = value.includes(option[this.trackBy]);
            });
        }
        else if (!this.multiSelect && typeof value === 'string') {
            cloneList.forEach(option => {
                option.selected = option[this.trackBy] === value;
            });
        }
        this.optionList = cloneList;
        this.updateDropdownLabel();
    }
    updateDropdownLabel() {
        var _a;
        const selectedOptions = this.optionList.filter(opt => opt.selected);
        // Use the shadow root instead of el to query inside shadow DOM
        const dropdownLabel = (_a = this.el.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector('.dropdown__label');
        if (dropdownLabel) {
            if (selectedOptions.length > 0) {
                const labels = selectedOptions.map(opt => opt[this.optionLabel]);
                dropdownLabel.textContent = labels.join(', ');
                dropdownLabel.classList.add('dropdown__label--selection');
            }
            else {
                dropdownLabel.textContent = '';
                dropdownLabel.classList.remove('dropdown__label--selection');
            }
        }
    }
    componentWillLoad() {
        this.initializeOptions();
        // Initialize style manager with element reference
        this.sxStyleManager = new SxStyleManager(this.componentId, this.el);
    }
    componentDidLoad() {
        document.addEventListener('click', this.handleClickOutside);
        this.updateDropdownLabel();
        // Process styling after the component is fully loaded and shadow DOM is ready
        this.processStyling();
    }
    disconnectedCallback() {
        var _a;
        document.removeEventListener('click', this.handleClickOutside);
        // Clean up styles when component is removed
        (_a = this.sxStyleManager) === null || _a === void 0 ? void 0 : _a.cleanup();
    }
    handleAddPressed(e) {
        const target = e.currentTarget;
        target.classList.add('active');
    }
    handleRemovePressed(e) {
        const target = e.currentTarget;
        target.classList.remove('active');
    }
    toggleDropdown() {
        var _a, _b;
        this.dropdownOpen = !this.dropdownOpen;
        if (this.dropdownOpen) {
            (_a = this.btnRef) === null || _a === void 0 ? void 0 : _a.classList.add('open');
        }
        else {
            (_b = this.btnRef) === null || _b === void 0 ? void 0 : _b.classList.remove('open');
        }
    }
    closeDropdown() {
        var _a;
        this.dropdownOpen = false;
        (_a = this.btnRef) === null || _a === void 0 ? void 0 : _a.classList.remove('open');
    }
    handleToggleDropdown(e) {
        e.stopPropagation();
        this.toggleDropdown();
    }
    setSelectedOptions(option, index) {
        const cloneList = [...this.optionList];
        if (!this.multiSelect) {
            // Deselect all options for single select
            cloneList.forEach(opt => (opt.selected = false));
            cloneList[index].selected = true;
            if (this.onChange) {
                this.onChange(option[this.trackBy]);
            }
            if (this.getSelectedOptions) {
                this.getSelectedOptions(option);
            }
        }
        else {
            // Toggle selection for multi-select
            cloneList[index].selected = !cloneList[index].selected;
            if (this.onChange) {
                const selectedValues = cloneList
                    .filter(opt => opt.selected)
                    .map(opt => opt[this.trackBy]);
                this.onChange(selectedValues);
            }
            if (this.getSelectedOptions) {
                this.getSelectedOptions({
                    selectedList: cloneList.filter(opt => opt.selected),
                    selectedOption: option,
                    selectedIndex: index,
                });
            }
        }
        this.optionList = cloneList;
        this.updateDropdownLabel();
    }
    handleOptionClick(e, option, index) {
        e.stopPropagation();
        this.setSelectedOptions(option, index);
        // Close dropdown for single select after selection
        if (!this.multiSelect) {
            this.closeDropdown();
        }
    }
    handleSxChange() {
        this.processStyling();
    }
    componentDidUpdate() {
        // Re-process styling after updates
        this.processStyling();
    }
    processStyling() {
        if (!this.sx)
            return;
        // Handle both string and object formats
        const sxValue = typeof this.sx === 'string' ? JSON.parse(this.sx) : this.sx;
        this.rootStyles = this.sxStyleManager.processSxProp(sxValue);
    }
    render() {
        const dropdownClasses = {
            'dropdown': true,
            [`dropdown--${this.size}`]: true,
            'dropdown--error': this.error,
            [`dropdown--${this.variant}`]: this.variant !== 'default',
            'dropdown--disabled': this.disabled,
            'dropdown--readonly': this.readonly,
            'dropdown--multi-select': this.multiSelect,
            [this.extraClass]: !!this.extraClass
        };
        return (h(Host, { key: 'eaf5ad6f31bcb15dc710ef95c8210d8129c57a3f', id: this.componentId, style: this.rootStyles, dir: document.documentElement.getAttribute('dir') }, h("div", { key: '6163216d1d16b25c2a1ac0c1306de597544cc23c', id: this.id, ref: el => (this.containerRef = el), class: Object.keys(dropdownClasses)
                .filter(key => dropdownClasses[key])
                .join(' ') }, h("button", { key: '599e11ce2cd3d866845d0ce2ad5a5477536ee8e1', class: "dropdown__btn", ref: el => (this.btnRef = el), disabled: this.disabled || this.readonly, onClick: this.handleToggleDropdown.bind(this), onMouseDown: this.handleAddPressed.bind(this), onMouseUp: this.handleRemovePressed.bind(this), onMouseOut: this.handleRemovePressed.bind(this), type: "button" }, h("span", { key: '15937f4706391670a12a86d08c90f06b0172d0e6', class: "dropdown__label" }), h("span", { key: '20459a38f5421bf71bae4893023548cd3d2d974e', class: "dropdown__label-placeholder" }, this.placeholder), h("span", { key: 'c1baf1dc22bcf89b2c19e2a3d3e551b69e1fcb7f', class: "dropdown__chevron" }, h("dga-icon", { key: '3f7df02049cbf028c057725350f6601ce2b2fb83', icon: 'ArrowDown01Icon', variant: "stroke" }))), h("ul", { key: 'a50fe5934a2b7816041015c4a064153a3be784f5', class: "dropdown__list" }, this.optionList.map((option, index) => (h("li", { key: option[this.trackBy] || guid() }, h("button", { class: {
                'dropdown__option': true,
                'dropdown__option--checkbox': this.multiSelect,
                'selected': option.selected
            }, "data-value": option[this.trackBy], onClick: e => this.handleOptionClick(e, option, index), onMouseDown: this.handleAddPressed.bind(this), onMouseUp: this.handleRemovePressed.bind(this), onMouseOut: this.handleRemovePressed.bind(this), type: "button" }, this.multiSelect && (h("div", { class: "dropdown__option-icon-container" }, h("span", { class: "dropdown__option-icon" }, h("i", { class: "hgi-solid hgi-tick-02", style: { fontSize: "20px" } })))), h("span", { class: "dropdown__option-label" }, option[this.optionLabel] || ''), !this.multiSelect && option.selected && (h("span", { class: "dropdown__option-icon" }, h("dga-icon", { icon: 'Tick02Icon', variant: "solid" })))))))))));
    }
    static get is() { return "dga-dropdown"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["dga-dropdown.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["dga-dropdown.css"]
        };
    }
    static get properties() {
        return {
            "id": {
                "type": "string",
                "attribute": "id",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "guid()"
            },
            "placeholder": {
                "type": "string",
                "attribute": "placeholder",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "size": {
                "type": "string",
                "attribute": "size",
                "mutable": false,
                "complexType": {
                    "original": "'md' | 'lg'",
                    "resolved": "\"lg\" | \"md\"",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'lg'"
            },
            "variant": {
                "type": "string",
                "attribute": "variant",
                "mutable": false,
                "complexType": {
                    "original": "'default' | 'lighter' | 'darker'",
                    "resolved": "\"darker\" | \"default\" | \"lighter\"",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'default'"
            },
            "error": {
                "type": "boolean",
                "attribute": "error",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            },
            "disabled": {
                "type": "boolean",
                "attribute": "disabled",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            },
            "readonly": {
                "type": "boolean",
                "attribute": "readonly",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            },
            "multiSelect": {
                "type": "boolean",
                "attribute": "multi-select",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            },
            "options": {
                "type": "unknown",
                "attribute": "options",
                "mutable": false,
                "complexType": {
                    "original": "any[]",
                    "resolved": "any[]",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "defaultValue": "[]"
            },
            "optionLabel": {
                "type": "string",
                "attribute": "option-label",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'name'"
            },
            "trackBy": {
                "type": "string",
                "attribute": "track-by",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'value'"
            },
            "getSelectedOptions": {
                "type": "unknown",
                "attribute": "get-selected-options",
                "mutable": false,
                "complexType": {
                    "original": "(event: any) => void",
                    "resolved": "(event: any) => void",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "extraClass": {
                "type": "string",
                "attribute": "extra-class",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "value": {
                "type": "string",
                "attribute": "value",
                "mutable": false,
                "complexType": {
                    "original": "string | string[]",
                    "resolved": "string | string[]",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "onChange": {
                "type": "unknown",
                "attribute": "on-change",
                "mutable": false,
                "complexType": {
                    "original": "(value: string | string[]) => void",
                    "resolved": "(value: string | string[]) => void",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "sx": {
                "type": "string",
                "attribute": "sx",
                "mutable": false,
                "complexType": {
                    "original": "SxProps | string",
                    "resolved": "CSSProperties & NestedSelector | string",
                    "references": {
                        "SxProps": {
                            "location": "import",
                            "path": "../../utils/sx-system",
                            "id": "src/utils/sx-system.ts::SxProps"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            }
        };
    }
    static get states() {
        return {
            "optionList": {},
            "dropdownOpen": {}
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "value",
                "methodName": "handleValueChange"
            }, {
                "propName": "options",
                "methodName": "initializeOptions"
            }, {
                "propName": "sx",
                "methodName": "handleSxChange"
            }];
    }
}
