class CustomSelect {
    constructor(element) {
        this.element = element instanceof HTMLElement ? element : document.querySelector(element);
        this.rootNode = this.element.getRootNode();
        this.isShadowDOM = this.rootNode instanceof ShadowRoot;
        this.CONFIG = {
            SEARCH_MIN_HEIGHT: 120,
            SEARCHBOX_HEIGHT: 50,
            PADDING: 20,
            HORIZONTAL_PADDING: 20,
            SCROLL_SELECTED_OFFSET: 90,
            THROTTLE_DELAY: 100,
            SEARCH_FOCUS_DELAY: 100,
            DROPDOWN_APPEND_TO_BODY: true
        };
        this.trigger = this.element.querySelector(".select-trigger");
        this.triggerText = this.trigger ? this.trigger.querySelector(".select-trigger-text") : null;
        if (this.triggerText && this.triggerText.classList.contains("select-trigger-text-nochange")) {
            this.triggerText = null;
        }
        this.dropdown = this.element.querySelector(".select-dropdown");
        if (!this.dropdown) {
            const dropdownId = this.element.getAttribute("data-dropdown-id");
            if (dropdownId) {
                this.dropdown = (this.element.getRootNode() || document).getElementById(dropdownId);
                this.isExternalDropdown = true;
            }
        }
        this.optionsContainer = this.dropdown ? this.dropdown.querySelector(".select-options") : null;
        this.options = this.optionsContainer ? Array.from(this.optionsContainer.querySelectorAll(".select-option")) : [];
        this.hasSearch = this.element.getAttribute("data-search") === "true";
        this.searchPlaceholder = this.element.getAttribute("data-search-placeholder") || (typeof getLang === "function" ? getLang("custom_select.search_placeholder", "Search...") : "Search...");
        this.searchAttr = this.element.getAttribute("data-search-attr") || "data-value";
        this.isMultiple = this.element.getAttribute("data-multiple") === "true";
        this.maxSelect = parseInt(this.element.getAttribute("data-max")) || 0;
        this.selectedValues = [];
        this.defaultText = this.element.getAttribute("data-default-text") || "";
        this.selectedValue = null;
        this.searchInput = null;
        this.isOpen = false;
        this.resizeObserver = null;
        this.overlayClickHandler = null;
        this.mobileOverlay = null;
        this.placement = this.element.getAttribute("data-placement") || "bottom";
        this.#init();
    }
    #init() {
        if (!this.trigger || !this.dropdown || !this.optionsContainer) {
            return;
        }
        if (this.isExternalDropdown) {
            this.dropdown.classList.add("external-dropdown");
            if (this.element.getAttribute("data-modal-escape") === "true") {
                this.dropdown.classList.add("modal-dropdown");
            }
        }
        if (this.isMultiple) {
            const selected = this.options.filter(opt => opt.classList.contains("selected"));
            this.selectedValues = selected.map(opt => opt.getAttribute("data-value"));
            this.#updateTriggerTextMultiple();
        } else {
            const selected = this.options.find(opt => opt.classList.contains("selected"));
            if (selected) {
                this.selectedValue = selected.getAttribute("data-value");
                if (this.triggerText) {
                    const optionHTML = selected.getAttribute("data-html") || selected.innerHTML;
                    if (this.defaultText) {
                        this.triggerText.innerHTML = this.defaultText + " ";
                        const tempSpan = document.createElement("span");
                        tempSpan.innerHTML = optionHTML;
                        this.triggerText.appendChild(tempSpan);
                    } else {
                        this.triggerText.innerHTML = optionHTML;
                    }
                }
            } else if (this.defaultText && this.triggerText) {
                this.triggerText.textContent = this.defaultText;
            }
        }
        if (this.hasSearch) {
            this.#initSearch();
        }
        this.#bindEvents();
        this.element.customSelectAPI = this;
    }
    #initSearch() {
        const html = `\n            <div class="search-box">\n                <div class="search-input-wrapper">\n                    <input type="text" class="search-input" placeholder="${this.searchPlaceholder}">\n                    <button class="search-select-clear-btn hidden" type="button"><svg width="18" height="18" fill="none" stroke="currentColor"><use href="#x"></use></svg></button>\n                </div>\n            </div>\n        `;
        this.dropdown.insertAdjacentHTML("afterbegin", html);
        const searchScope = this.isExternalDropdown ? this.dropdown : this.element;
        this.searchInput = searchScope.querySelector(".search-input");
        this.clearBtn = searchScope.querySelector(".search-select-clear-btn");
    }
    #bindEvents() {
        this.handleTriggerClick = this.handleTriggerClick.bind(this);
        this.trigger.addEventListener("click", this.handleTriggerClick);
        this.handleDocumentClick = e => {
            if (!this.isOpen) return;
            const target = e.target;
            if (this.trigger.contains(target)) return;
            const isInsideDropdown = this.isExternalDropdown ? this.dropdown.contains(target) : this.dropdown.contains(target);
            if (isInsideDropdown) {
                const clickedNestedTrigger = target.closest(".nested-select .select-trigger");
                if (clickedNestedTrigger) return;
                const openNestedDropdown = this.dropdown.querySelector(".nested-select > .select-dropdown.active");
                if (openNestedDropdown) {
                    const nestedElement = openNestedDropdown.closest(".dropdown-select");
                    if (nestedElement && !nestedElement.contains(target)) {
                        if (nestedElement.customSelectAPI) {
                            nestedElement.customSelectAPI.close();
                        }
                    }
                }
                return;
            }
            this.close();
        };
        this.rootNode.addEventListener("click", this.handleDocumentClick);
        if (this.rootNode instanceof ShadowRoot) {
            this.handleWindowClick = e => {
                if (!this.isOpen) return;
                const path = e.composedPath();
                if (path.includes(this.rootNode.host)) return;
                this.close();
            };
            window.addEventListener("click", this.handleWindowClick);
        }
        this.handleOptionsClick = e => {
            const option = e.target.closest(".select-option");
            if (option && !option.classList.contains("hidden")) {
                this.#selectOption(option);
            }
        };
        this.optionsContainer.addEventListener("click", this.handleOptionsClick);
        if (this.hasSearch) {
            this.#bindSearchEvents();
        }
        this.wasMobile = window.innerWidth <= 576;
        this.handleResize = this.#throttle(() => {
            const isMobile = window.innerWidth <= 576;
            if (isMobile !== this.wasMobile) {
                this.wasMobile = isMobile;
                if (this.isOpen) {
                    this.close();
                }
                if (this.isExternalDropdown) {
                    this.dropdown.style.removeProperty("top");
                    this.dropdown.style.removeProperty("left");
                    this.dropdown.style.removeProperty("bottom");
                    this.dropdown.style.removeProperty("right");
                    this.dropdown.style.removeProperty("transition");
                    this.dropdown.style.removeProperty("--dropdown-min-width");
                    this.dropdown.classList.remove("placement-bottom", "placement-top", "placement-left", "placement-right");
                }
                return;
            }
            if (this.isOpen) {
                this.#calculatePosition();
            }
        }, this.CONFIG.THROTTLE_DELAY);
        window.addEventListener("resize", this.handleResize);
        window.addEventListener("scroll", this.handleResize, {
            passive: true
        });
    }
    #bindSearchEvents() {
        if (!this.searchInput) {
            console.warn("CustomSelect: Search enabled but search input not found", this.element);
            return;
        }
        this.searchInput.addEventListener("input", e => {
            const value = e.target.value;
            this.#filterOptions(value);
            if (this.clearBtn) {
                if (value.trim()) {
                    this.clearBtn.classList.remove("hidden");
                } else {
                    this.clearBtn.classList.add("hidden");
                }
            }
        });
        if (this.clearBtn) {
            this.clearBtn.addEventListener("click", e => {
                e.stopPropagation();
                this.searchInput.value = "";
                this.#filterOptions("");
                this.clearBtn.classList.add("hidden");
                this.searchInput.focus();
            });
        }
        this.searchInput.addEventListener("click", e => {
            e.stopPropagation();
        });
        this.searchInput.addEventListener("keydown", e => {
            if (e.key === "Escape") this.close();
        });
    }
    handleTriggerClick(e) {
        const isNestedSelect = this.element.classList.contains("nested-select");
        if (!isNestedSelect) {
            this.element.setAttribute("data-current-select", "true");
            CustomSelect.closeAll(this.rootNode);
            this.element.removeAttribute("data-current-select");
        }
        this.isOpen ? this.close() : this.open();
    }
    open() {
        this.isOpen = true;
        this.trigger.classList.add("active");
        this.dropdown.classList.add("active");
        const hasOverlay = this.#hasMobileOverlay();
        if (hasOverlay) {
            this.#enableMobileMode();
        }
        this.#calculatePosition();
        this.#watchDropdownSize();
        if (this.hasSearch && this.searchInput && !hasOverlay) {
            requestAnimationFrame(() => {
                this.searchInput.focus();
            });
        }
        this.#scrollToSelected();
        const openEvent = new CustomEvent("customSelectOpen", {
            detail: {
                element: this.element
            },
            bubbles: true
        });
        this.element.dispatchEvent(openEvent);
    }
    close() {
        this.isOpen = false;
        this.trigger.classList.remove("active");
        this.dropdown.classList.remove("active");
        this.dropdown.classList.remove("search-expanded");
        if (this.trigger) {
            this.trigger.blur();
        }
        if (this.isExternalDropdown) {
            this.dropdown.style.removeProperty("--dropdown-top");
            this.dropdown.style.removeProperty("--dropdown-top-up");
            this.dropdown.style.removeProperty("--dropdown-left");
            this.dropdown.style.removeProperty("--dropdown-min-width");
        }
        this.#disableMobileMode();
        if (this.resizeObserver) {
            this.resizeObserver.disconnect();
            this.resizeObserver = null;
        }
        if (this.hasSearch && this.searchInput) {
            this.searchInput.value = "";
            this.#filterOptions("");
            if (this.clearBtn) {
                this.clearBtn.classList.add("hidden");
            }
        }
    }
    #hasMobileOverlay() {
        if (this.element.classList.contains("nested-select")) return false;
        if (this.isExternalDropdown) {
            return window.innerWidth <= 576;
        }
        if (this.isShadowDOM) return false;
        const beforeStyle = window.getComputedStyle(this.element, "::before");
        const content = beforeStyle.getPropertyValue("content");
        return content !== "none" && content !== "";
    }
    #enableMobileMode() {
        if (!this.element.classList.contains("nested-select")) {
            document.body.classList.add("select-open");
        }
        if (this.isExternalDropdown && !this.mobileOverlay) {
            this.mobileOverlay = document.createElement("div");
            this.mobileOverlay.className = "external-select-overlay";
            document.body.appendChild(this.mobileOverlay);
        }
        this.overlayClickHandler = e => {
            const target = e.target;
            const path = e.composedPath ? e.composedPath() : [];
            if (this.mobileOverlay && target === this.mobileOverlay) {
                e.preventDefault();
                e.stopPropagation();
                this.close();
                return;
            }
            const isInside = this.dropdown.contains(target) || this.trigger.contains(target) || path.includes(this.dropdown) || path.includes(this.trigger);
            if (isInside) {
                const openNestedSelect = this.element.querySelector(".dropdown-select.nested-select > .select-dropdown.active");
                if (openNestedSelect) {
                    const nestedSelectElement = openNestedSelect.closest(".dropdown-select");
                    if (nestedSelectElement && !nestedSelectElement.contains(target)) {
                        if (nestedSelectElement.customSelectAPI) {
                            nestedSelectElement.customSelectAPI.close();
                        }
                    }
                }
                return;
            }
            const openNestedSelect = this.element.querySelector(".dropdown-select.nested-select > .select-dropdown.active");
            if (openNestedSelect) {
                const nestedSelectElement = openNestedSelect.closest(".dropdown-select");
                if (nestedSelectElement && nestedSelectElement.customSelectAPI) {
                    nestedSelectElement.customSelectAPI.close();
                }
            }
            e.preventDefault();
            e.stopPropagation();
            this.close();
        };
        document.addEventListener("touchstart", this.overlayClickHandler, {
            passive: false
        });
        document.addEventListener("click", this.overlayClickHandler);
    }
    #disableMobileMode() {
        if (!this.element.classList.contains("nested-select")) {
            document.body.classList.remove("select-open");
        }
        if (this.mobileOverlay) {
            this.mobileOverlay.remove();
            this.mobileOverlay = null;
        }
        if (this.overlayClickHandler) {
            document.removeEventListener("touchstart", this.overlayClickHandler);
            document.removeEventListener("click", this.overlayClickHandler);
            this.overlayClickHandler = null;
        }
    }
    #watchDropdownSize() {
        if (this.resizeObserver) {
            this.resizeObserver.disconnect();
        }
        this.resizeObserver = new ResizeObserver(() => {
            if (this.isOpen) {
                this.#calculatePosition();
            }
        });
        this.resizeObserver.observe(this.dropdown);
    }
    #scrollToSelected() {
        const selected = this.optionsContainer.querySelector(".select-option.selected");
        if (!selected) {
            this.optionsContainer.scrollTop = 0;
            return;
        }
        const optionTop = selected.offsetTop;
        const containerHeight = this.optionsContainer.clientHeight;
        const scrollPosition = optionTop - this.CONFIG.SCROLL_SELECTED_OFFSET;
        const maxScroll = this.optionsContainer.scrollHeight - containerHeight;
        this.optionsContainer.scrollTop = Math.max(0, Math.min(scrollPosition, maxScroll));
    }
    #calculatePosition() {
        const triggerRect = this.trigger.getBoundingClientRect();
        const isModalEscape = this.element.getAttribute("data-modal-escape") === "true";
        const modal = isModalEscape ? null : this.element.closest(".modal");
        const rootNode = this.element.getRootNode();
        const shadowHost = rootNode instanceof ShadowRoot ? rootNode.host : null;
        let containerTop = 0;
        let containerBottom = window.innerHeight;
        let containerLeft = 0;
        let containerRight = window.innerWidth;
        if (shadowHost) {
            const hostRect = shadowHost.getBoundingClientRect();
            containerLeft = hostRect.left;
            containerRight = hostRect.right;
        }
        if (modal) {
            const modalBody = modal.querySelector(".modal-body");
            if (modalBody) {
                const rect = modalBody.getBoundingClientRect();
                containerTop = rect.top;
                containerBottom = rect.bottom;
                containerLeft = rect.left;
                containerRight = rect.right;
            }
        }
        const spaceBelow = containerBottom - triggerRect.bottom;
        const spaceAbove = triggerRect.top - containerTop;
        const searchBoxHeight = this.hasSearch ? this.CONFIG.SEARCHBOX_HEIGHT : 0;
        let availableSpace;
        if (spaceBelow > spaceAbove) {
            availableSpace = spaceBelow - this.CONFIG.PADDING;
            this.dropdown.classList.remove("open-top");
            this.dropdown.classList.add("open-bottom");
        } else {
            availableSpace = spaceAbove - this.CONFIG.PADDING;
            this.dropdown.classList.remove("open-bottom");
            this.dropdown.classList.add("open-top");
        }
        const offset = parseInt(this.optionsContainer.getAttribute("data-max-height-offset")) || 0;
        const optimalHeight = availableSpace - searchBoxHeight - offset;
        this.optionsContainer.style.maxHeight = Math.max(this.CONFIG.SEARCH_MIN_HEIGHT, optimalHeight) + "px";
        const dropdownRect = this.dropdown.getBoundingClientRect();
        const dropdownWidth = dropdownRect.width;
        const spaceOnRight = containerRight - triggerRect.left - this.CONFIG.HORIZONTAL_PADDING;
        const spaceOnLeft = triggerRect.right - containerLeft - this.CONFIG.HORIZONTAL_PADDING;
        this.dropdown.style.transition = "none";
        this.dropdown.classList.remove("open-left", "open-center");
        this.dropdown.style.left = "";
        const isInModal = modal !== null;
        if (isInModal) {
            if (dropdownWidth <= spaceOnRight) {} else {
                this.dropdown.classList.add("open-left");
            }
        } else {
            if (dropdownWidth <= spaceOnRight) {} else if (dropdownWidth <= spaceOnLeft) {
                this.dropdown.classList.add("open-left");
            } else {
                this.dropdown.classList.add("open-center");
                const triggerCenter = triggerRect.left + triggerRect.width / 2;
                const dropdownHalfWidth = dropdownWidth / 2;
                const idealLeft = triggerCenter - dropdownHalfWidth;
                let finalLeft = Math.max(containerLeft + this.CONFIG.HORIZONTAL_PADDING, idealLeft);
                finalLeft = Math.min(finalLeft, containerRight - dropdownWidth - this.CONFIG.HORIZONTAL_PADDING);
                this.dropdown.style.left = finalLeft - triggerRect.left + "px";
            }
        }
        if (this.isExternalDropdown) {
            const isMobile = window.innerWidth <= 576;
            if (isMobile) {
                this.dropdown.style.removeProperty("top");
                this.dropdown.style.removeProperty("left");
                this.dropdown.style.removeProperty("bottom");
                this.dropdown.style.removeProperty("right");
                this.dropdown.style.removeProperty("transition");
                this.dropdown.style.removeProperty("--dropdown-min-width");
                this.dropdown.classList.remove("placement-bottom", "placement-top", "placement-left", "placement-right");
                return;
            }
            const dropdownHeight = this.dropdown.offsetHeight;
            const dropdownWidth = this.dropdown.offsetWidth;
            const gap = 5;
            const screenWidth = window.innerWidth;
            const screenHeight = window.innerHeight;
            const spaceBottom = screenHeight - triggerRect.bottom - gap;
            const spaceTop = triggerRect.top - gap;
            const spaceRight = screenWidth - triggerRect.right;
            const spaceLeft = triggerRect.left;
            let finalTop, finalLeft;
            let actualPlacement = this.placement;
            const isBottomLeft = this.placement === "bottom-left";
            const isBottomRight = this.placement === "bottom-right";
            const isVertical = this.placement === "bottom" || this.placement === "top" || isBottomLeft || isBottomRight;
            if (isVertical) {
                const preferBottom = this.placement === "bottom" || isBottomLeft || isBottomRight;
                if (preferBottom) {
                    if (spaceBottom >= dropdownHeight || spaceBottom >= spaceTop) {
                        finalTop = triggerRect.bottom + gap;
                        actualPlacement = isBottomLeft ? "bottom-left" : isBottomRight ? "bottom-right" : "bottom";
                    } else {
                        finalTop = triggerRect.top - dropdownHeight - gap;
                        actualPlacement = "top";
                    }
                } else {
                    if (spaceTop >= dropdownHeight || spaceTop >= spaceBottom) {
                        finalTop = triggerRect.top - dropdownHeight - gap;
                        actualPlacement = "top";
                    } else {
                        finalTop = triggerRect.bottom + gap;
                        actualPlacement = "bottom";
                    }
                }
                if (isBottomLeft) {
                    finalLeft = triggerRect.left;
                } else if (isBottomRight) {
                    finalLeft = triggerRect.right - dropdownWidth;
                } else {
                    finalLeft = triggerRect.left;
                    if (finalLeft + dropdownWidth > screenWidth - this.CONFIG.HORIZONTAL_PADDING) {
                        finalLeft = triggerRect.right - dropdownWidth;
                    }
                }
                if (finalLeft + dropdownWidth > screenWidth - this.CONFIG.HORIZONTAL_PADDING) {
                    finalLeft = screenWidth - dropdownWidth - this.CONFIG.HORIZONTAL_PADDING;
                }
                if (finalLeft < this.CONFIG.HORIZONTAL_PADDING) {
                    finalLeft = this.CONFIG.HORIZONTAL_PADDING;
                }
            } else {
                if (this.placement === "right") {
                    if (spaceRight >= dropdownWidth + gap || spaceRight >= spaceLeft) {
                        finalLeft = triggerRect.right + gap;
                        actualPlacement = "right";
                    } else {
                        finalLeft = triggerRect.left - dropdownWidth - gap;
                        actualPlacement = "left";
                    }
                } else {
                    if (spaceLeft >= dropdownWidth + gap || spaceLeft >= spaceRight) {
                        finalLeft = triggerRect.left - dropdownWidth - gap;
                        actualPlacement = "left";
                    } else {
                        finalLeft = triggerRect.right + gap;
                        actualPlacement = "right";
                    }
                }
                const maxAvailableHeight = screenHeight - this.CONFIG.PADDING * 2;
                const searchBoxHeight = this.hasSearch ? this.CONFIG.SEARCHBOX_HEIGHT : 0;
                const offset = parseInt(this.optionsContainer.getAttribute("data-max-height-offset")) || 0;
                const dropdownPadding = 10;
                const optimalHeight = maxAvailableHeight - searchBoxHeight - offset - dropdownPadding;
                this.optionsContainer.style.maxHeight = Math.max(this.CONFIG.SEARCH_MIN_HEIGHT, optimalHeight) + "px";
                const actualDropdownHeight = this.dropdown.offsetHeight;
                const triggerCenterY = triggerRect.top + triggerRect.height / 2;
                const dropdownHalfHeight = actualDropdownHeight / 2;
                let idealTop = triggerCenterY - dropdownHalfHeight;
                const minTop = this.CONFIG.PADDING;
                const maxTop = screenHeight - actualDropdownHeight - this.CONFIG.PADDING;
                finalTop = Math.max(minTop, Math.min(idealTop, maxTop));
                finalLeft = Math.max(this.CONFIG.HORIZONTAL_PADDING, finalLeft);
            }
            finalLeft = Math.max(this.CONFIG.HORIZONTAL_PADDING, Math.min(finalLeft, screenWidth - dropdownWidth - this.CONFIG.HORIZONTAL_PADDING));
            this.dropdown.style.setProperty("top", finalTop + "px", "important");
            this.dropdown.style.setProperty("left", finalLeft + "px", "important");
            this.dropdown.style.setProperty("bottom", "auto", "important");
            this.dropdown.style.setProperty("right", "auto", "important");
            this.dropdown.style.setProperty("--dropdown-min-width", triggerRect.width + "px");
            this.dropdown.classList.remove("placement-bottom", "placement-top", "placement-left", "placement-right");
            this.dropdown.classList.add("placement-" + actualPlacement);
        }
    }
    #selectOption(option) {
        if (this.isMultiple) {
            const value = option.getAttribute("data-value");
            if (option.classList.contains("selected")) {
                option.classList.remove("selected");
                this.selectedValues = this.selectedValues.filter(v => v !== value);
            } else {
                if (this.maxSelect && this.selectedValues.length >= this.maxSelect) return;
                option.classList.add("selected");
                this.selectedValues.push(value);
            }
            this.#updateTriggerTextMultiple();
            const event = new CustomEvent("customSelectChange", {
                detail: {
                    values: this.selectedValues,
                    texts: this.#getSelectedTexts(),
                    selectElement: this.element
                },
                bubbles: true
            });
            this.element.dispatchEvent(event);
        } else {
            const allOptions = this.optionsContainer.querySelectorAll(".select-option");
            for (let i = 0; i < allOptions.length; i++) {
                allOptions[i].classList.remove("selected");
            }
            option.classList.add("selected");
            const optionHTML = option.getAttribute("data-html") || option.innerHTML;
            if (this.triggerText) {
                if (this.defaultText) {
                    this.triggerText.innerHTML = this.defaultText + " ";
                    const tempSpan = document.createElement("span");
                    tempSpan.innerHTML = optionHTML;
                    this.triggerText.appendChild(tempSpan);
                } else {
                    this.triggerText.innerHTML = optionHTML;
                }
            }
            this.selectedValue = option.getAttribute("data-value");
            const event = new CustomEvent("customSelectChange", {
                detail: {
                    value: this.selectedValue,
                    text: option.textContent.trim(),
                    html: optionHTML,
                    selectElement: this.element
                },
                bubbles: true
            });
            this.element.dispatchEvent(event);
            this.close();
        }
    }
    #updateTriggerTextMultiple() {
        if (!this.triggerText) return;
        const count = this.selectedValues.length;
        const existingBadge = this.trigger.querySelector(".select-trigger-text-count");
        if (existingBadge) {
            existingBadge.remove();
        }
        if (count === 0) {
            if (this.defaultText) {
                this.triggerText.textContent = this.defaultText;
            } else {
                this.triggerText.textContent = typeof getLang === "function" ? getLang("custom_select.select_options", "Select options") : "Select options";
            }
        } else if (count === 1) {
            const selected = this.options.find(opt => opt.getAttribute("data-value") === this.selectedValues[0]);
            if (selected) {
                const optionHTML = selected.getAttribute("data-html") || selected.innerHTML;
                if (this.defaultText) {
                    this.triggerText.innerHTML = this.defaultText + " ";
                    const tempSpan = document.createElement("span");
                    tempSpan.innerHTML = optionHTML;
                    this.triggerText.appendChild(tempSpan);
                } else {
                    this.triggerText.innerHTML = optionHTML;
                }
            }
        } else {
            if (this.defaultText) {
                this.triggerText.textContent = this.defaultText.replace(":", "").trim();
            } else {
                this.triggerText.textContent = typeof getLang === "function" ? getLang("custom_select.selected", "Selected") : "Selected";
            }
            const badge = document.createElement("span");
            badge.className = "select-trigger-text-count";
            badge.textContent = count;
            const arrow = this.trigger.querySelector(".select-arrow");
            if (arrow) {
                this.trigger.insertBefore(badge, arrow);
            } else {
                this.trigger.appendChild(badge);
            }
        }
    }
    #getSelectedTexts() {
        return this.selectedValues.map(value => {
            const option = this.options.find(opt => opt.getAttribute("data-value") === value);
            return option ? option.textContent : "";
        });
    }
    #filterOptions(term) {
        if (!this.hasSearch) return;
        const search = term.toLowerCase().trim();
        let hasResults = false;
        const currentOptions = this.optionsContainer.querySelectorAll(".select-option");
        for (let i = 0; i < currentOptions.length; i++) {
            const option = currentOptions[i];
            const text = option.textContent.toLowerCase();
            let attrValue = "";
            if (this.searchAttr) {
                attrValue = (option.getAttribute(this.searchAttr) || "").toLowerCase();
            }
            const matchFound = text.includes(search) || this.searchAttr && attrValue.includes(search);
            if (matchFound) {
                option.classList.remove("hidden");
                hasResults = true;
            } else {
                option.classList.add("hidden");
            }
        }
        this.#toggleNoResults(!hasResults);
        this.optionsContainer.scrollTop = 0;
    }
    #toggleNoResults(show) {
        let noResults = this.optionsContainer.querySelector(".no-results");
        if (show && !noResults) {
            const html = `\n                <div class="no-results">\n                    <div class="no-results-icon">\n                        <svg width="30" height="30" fill="none" stroke="currentColor">\n                            <use href="#search-error"></use>\n                        </svg>\n                    </div>\n                    <div>${typeof getLang === "function" ? getLang("custom_select.no_results", "No results found") : "No results found"}</div>\n                </div>\n            `;
            this.optionsContainer.insertAdjacentHTML("beforeend", html);
        } else if (!show && noResults) {
            noResults.remove();
        }
    }
    #throttle(func, delay) {
        let lastCall = 0;
        return function(...args) {
            const now = Date.now();
            if (now - lastCall >= delay) {
                lastCall = now;
                func.apply(this, args);
            }
        };
    }
    getValue() {
        return this.isMultiple ? this.selectedValues : this.selectedValue;
    }
    setValue(value) {
        if (this.isMultiple) {
            const values = Array.isArray(value) ? value : [ value ];
            this.options.forEach(opt => opt.classList.remove("selected"));
            this.selectedValues = [];
            values.forEach(val => {
                const option = this.optionsContainer.querySelector(`.select-option[data-value="${val}"]`);
                if (option) {
                    option.classList.add("selected");
                    this.selectedValues.push(val);
                }
            });
            this.#updateTriggerTextMultiple();
        } else {
            const option = this.optionsContainer.querySelector(`.select-option[data-value="${value}"]`);
            if (option) {
                const allOptions = this.optionsContainer.querySelectorAll(".select-option");
                allOptions.forEach(opt => opt.classList.remove("selected"));
                option.classList.add("selected");
                this.selectedValue = value;
                if (this.triggerText) {
                    const optionHTML = option.getAttribute("data-html") || option.innerHTML;
                    if (this.defaultText) {
                        this.triggerText.innerHTML = this.defaultText + " ";
                        const tempSpan = document.createElement("span");
                        tempSpan.innerHTML = optionHTML;
                        this.triggerText.appendChild(tempSpan);
                    } else {
                        this.triggerText.innerHTML = optionHTML;
                    }
                }
            }
        }
    }
    getText() {
        if (this.isMultiple) {
            return this.#getSelectedTexts();
        } else {
            return this.triggerText?.textContent;
        }
    }
    getHTML() {
        if (this.isMultiple) {
            return this.selectedValues.map(value => {
                const option = this.options.find(opt => opt.getAttribute("data-value") === value);
                return option ? option.getAttribute("data-html") || option.innerHTML : "";
            });
        } else {
            const selected = this.options.find(opt => opt.getAttribute("data-value") === this.selectedValue);
            return selected ? selected.getAttribute("data-html") || selected.innerHTML : "";
        }
    }
    clearSelections() {
        if (!this.isMultiple) return;
        this.options.forEach(opt => opt.classList.remove("selected"));
        this.selectedValues = [];
        this.#updateTriggerTextMultiple();
    }
    refresh() {
        this.options = Array.from(this.element.querySelectorAll(".select-option"));
    }
    destroy() {
        this.trigger.removeEventListener("click", this.handleTriggerClick);
        this.rootNode.removeEventListener("click", this.handleDocumentClick);
        this.optionsContainer.removeEventListener("click", this.handleOptionsClick);
        window.removeEventListener("resize", this.handleResize);
        window.removeEventListener("scroll", this.handleResize);
        if (this.handleWindowClick) {
            window.removeEventListener("click", this.handleWindowClick);
        }
        if (this.resizeObserver) {
            this.resizeObserver.disconnect();
            this.resizeObserver = null;
        }
        delete this.element.customSelectAPI;
    }
    static closeAll(rootNode = document) {
        const selects = rootNode.querySelectorAll(".dropdown-select");
        for (let i = 0; i < selects.length; i++) {
            const select = selects[i];
            if (select.getAttribute("data-current-select")) continue;
            if (select.classList.contains("nested-select")) continue;
            if (select.customSelectAPI && select.customSelectAPI.isOpen) {
                select.customSelectAPI.close();
            }
        }
    }
}

function initCustomSelects(container = null, rootNode = null) {
    let searchScope;
    if (container) {
        if (typeof container === "string") {
            const searchIn = rootNode || document;
            searchScope = searchIn.querySelector(container);
            if (!searchScope) {
                console.warn(`initCustomSelects: Container "${container}" not found`);
                return;
            }
        } else if (container instanceof HTMLElement || container instanceof ShadowRoot) {
            searchScope = container;
        } else {
            console.warn("initCustomSelects: Invalid container type");
            return;
        }
    } else {
        searchScope = rootNode || document;
    }
    const selects = searchScope.querySelectorAll(".dropdown-select");
    for (let i = 0; i < selects.length; i++) {
        if (!selects[i].customSelectAPI) {
            selects[i].customSelectAPI = new CustomSelect(selects[i]);
        }
    }
}

function autoInitCustomSelects() {
    if (window.LANG_LOADED) {
        initCustomSelects();
        return;
    }
    if (typeof getLang === "function") {
        window.addEventListener("langLoaded", () => initCustomSelects(), {
            once: true
        });
        setTimeout(() => {
            if (!window.LANG_LOADED) initCustomSelects();
        }, 500);
    } else {
        initCustomSelects();
    }
}

if (!document.querySelector('script[src*="vunelix-"]')) {
    if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", autoInitCustomSelects);
    } else {
        autoInitCustomSelects();
    }
}

export { CustomSelect, initCustomSelects };

if (typeof window !== "undefined") {
    window.CustomSelect = CustomSelect;
    window.initCustomSelects = initCustomSelects;
}