import { p as proxyCustomElement, H, h, a as Host } from './index.js';
import { d as defineCustomElement$2 } from './p-CROLVxZq.js';
import { d as defineCustomElement$1 } from './p-Bm-eGlq5.js';

const multiselectOptionCss = ":host{display:block;width:100%}.option{display:flex;flex-direction:column;position:relative;cursor:pointer;list-style:none}.option.option--expanded{position:relative}.option.option--has-children{position:relative}.option.option--has-children .option-item>.chevron-wrapper{display:flex}.option--disabled{cursor:not-allowed;pointer-events:none;color:#BFBBBB}.option.search-hidden{display:none !important}.option.search-match .option-item .option-label .search-highlight{font-weight:bold}.option-item{display:flex;flex-direction:row;align-items:center;white-space:nowrap;min-height:20px;padding:4px 16px;background-color:#FFFFFF;transition:background-color 0.2s ease-in-out}.option-item:hover{background-color:#F7F7F7}.option--disabled .option-item:hover{background-color:transparent}.option-children{display:block}.chevron-wrapper{display:none;align-items:center;justify-content:center;margin-right:8px;width:20px;height:20px;flex-shrink:0}.chevron-wrapper:focus{outline:none}.chevron-wrapper:focus-visible{outline:2px solid #0A8276;outline-offset:2px;border-radius:1px}.option--has-children .chevron-wrapper{display:flex}.chevron-wrapper .chevron{transition:transform 0.2s ease-in-out;color:#3C3A39}.chevron-wrapper .chevron.chevron--expanded{transform:rotate(90deg)}.chevron-wrapper .chevron.chevron--collapsed{transform:rotate(0deg)}.checkbox-wrapper{display:flex;align-items:center;margin-right:8px;flex-shrink:0}.option-label{flex-grow:1;display:flex;align-items:center;cursor:pointer;padding:2px 0;font-size:0.875rem}.option-label:focus{outline:none}.option-label:focus-visible{outline:2px solid #0A8276;outline-offset:2px;border-radius:1px}.option--disabled .option-label{cursor:not-allowed;color:#BFBBBB}";

const MultiselectOption = /*@__PURE__*/ proxyCustomElement(class MultiselectOption extends H {
    constructor() {
        super();
        this.__registerHost();
        this.__attachShadow();
        this.selected = false;
        this.disabled = false;
        this.indeterminate = false;
        this.isExpanded = false;
        this.hasChildren = false;
        this.depth = 0;
        this.searchTerm = '';
        this.isSearchActive = false;
        this.isSearchDisabled = false;
        this.handleSearchFilter = (event) => {
            const { searchTerm, isActive } = event.detail;
            this.searchTerm = searchTerm.toLowerCase();
            this.isSearchActive = isActive;
            requestAnimationFrame(() => {
                this.updateSearchClasses();
            });
        };
        this.handleCheckboxClick = (event) => {
            if (this.disabled || (this.isSearchActive && this.isSearchDisabled))
                return;
            event.stopPropagation();
            let newSelectedState;
            if (this.indeterminate) {
                newSelectedState = true;
            }
            else {
                newSelectedState = !this.selected;
            }
            this.selected = newSelectedState;
            this.indeterminate = false;
            if (this.hasChildren) {
                this.isExpanded = newSelectedState;
                requestAnimationFrame(() => {
                    this.selectAllChildren(newSelectedState);
                    this.expandAllChildren(newSelectedState);
                });
            }
            this.updateParentStates();
            this.notifyMultiselect();
        };
        this.handleHeaderClick = (event) => {
            event.stopPropagation();
            if (!this.disabled && !(this.isSearchActive && this.isSearchDisabled)) {
                this.handleClick(event);
            }
        };
    }
    componentWillLoad() {
        this.hasChildren = this.el.children.length > 0;
        this.depth = this.calculateDepth();
        this.el.setAttribute('data-level', this.depth.toString());
        if (this.hasChildren) {
            const hasSelectedChildren = this.hasAnySelectedChildren();
            if (hasSelectedChildren) {
                this.isExpanded = true;
            }
        }
    }
    componentDidLoad() {
        this.el['__stencil_instance'] = this;
        this.notifyMultiselect();
        this.el.addEventListener('ifx-search-filter', this.handleSearchFilter);
    }
    componentWillUpdate() {
        this.notifyMultiselect();
    }
    disconnectedCallback() {
        this.el.removeEventListener('ifx-search-filter', this.handleSearchFilter);
    }
    updateSearchClasses() {
        var _a;
        const optionDiv = (_a = this.el.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector('.option');
        if (!optionDiv)
            return;
        if (!this.isSearchActive) {
            optionDiv.classList.remove('search-hidden', 'search-parent', 'search-match');
            this.removeHighlighting();
            this.isSearchDisabled = false;
            return;
        }
        const textContent = this.getTextContent().toLowerCase();
        const matchesSearch = textContent.includes(this.searchTerm);
        const hasMatchingParent = this.hasMatchingParent();
        requestAnimationFrame(() => {
            const hasMatchingChildren = this.hasMatchingChildren();
            optionDiv.classList.remove('search-hidden', 'search-parent', 'search-match');
            this.isSearchDisabled = false;
            if (matchesSearch && !this.hasChildren) {
                optionDiv.classList.add('search-match');
                this.highlightSearchTerm();
            }
            else if (matchesSearch && this.hasChildren) {
                optionDiv.classList.add('search-match');
                this.highlightSearchTerm();
                this.isExpanded = true;
            }
            else if (!matchesSearch && this.hasChildren && hasMatchingChildren) {
                optionDiv.classList.add('search-parent');
                this.removeHighlighting();
                this.isExpanded = true;
                this.isSearchDisabled = true;
            }
            else if (hasMatchingParent) {
                optionDiv.classList.add('search-match');
                this.removeHighlighting();
            }
            else {
                optionDiv.classList.add('search-hidden');
                this.removeHighlighting();
            }
        });
    }
    highlightSearchTerm() {
        var _a;
        if (!this.searchTerm)
            return;
        const labelElement = (_a = this.el.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector('.option-label');
        if (!labelElement)
            return;
        const slotElement = labelElement.querySelector('slot');
        if (!slotElement)
            return;
        this.removeHighlighting();
        const originalText = this.getTextContent();
        const searchTermLower = this.searchTerm.toLowerCase();
        const originalTextLower = originalText.toLowerCase();
        if (!originalTextLower.includes(searchTermLower))
            return;
        const searchIndex = originalTextLower.indexOf(searchTermLower);
        if (searchIndex === -1)
            return;
        const beforeMatch = originalText.substring(0, searchIndex);
        const matchText = originalText.substring(searchIndex, searchIndex + searchTermLower.length);
        const afterMatch = originalText.substring(searchIndex + searchTermLower.length);
        const highlightedContent = document.createElement('span');
        highlightedContent.className = 'highlighted-text';
        if (beforeMatch) {
            highlightedContent.appendChild(document.createTextNode(beforeMatch));
        }
        const boldElement = document.createElement('strong');
        boldElement.className = 'search-highlight';
        boldElement.textContent = matchText;
        highlightedContent.appendChild(boldElement);
        if (afterMatch) {
            highlightedContent.appendChild(document.createTextNode(afterMatch));
        }
        labelElement.setAttribute('data-original-content', 'true');
        slotElement.style.display = 'none';
        labelElement.appendChild(highlightedContent);
    }
    removeHighlighting() {
        var _a;
        const labelElement = (_a = this.el.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector('.option-label');
        if (!labelElement)
            return;
        const slotElement = labelElement.querySelector('slot');
        const highlightedElement = labelElement.querySelector('.highlighted-text');
        if (highlightedElement) {
            labelElement.removeChild(highlightedElement);
        }
        if (slotElement) {
            slotElement.style.display = '';
        }
        labelElement.removeAttribute('data-original-content');
    }
    getTextContent() {
        let text = '';
        Array.from(this.el.childNodes).forEach(node => {
            var _a;
            if (node.nodeType === Node.TEXT_NODE) {
                text += ((_a = node.textContent) === null || _a === void 0 ? void 0 : _a.trim()) || '';
            }
        });
        return text || this.value || '';
    }
    hasMatchingChildren() {
        if (!this.hasChildren)
            return false;
        const childOptions = Array.from(this.el.children)
            .filter(child => child.tagName === 'IFX-MULTISELECT-OPTION');
        return childOptions.some(child => {
            const childInstance = child['__stencil_instance'];
            if (!childInstance)
                return false;
            const childText = childInstance.getTextContent().toLowerCase();
            const childMatches = childText.includes(this.searchTerm);
            const grandChildrenMatch = childInstance.hasMatchingChildren();
            return childMatches || grandChildrenMatch;
        });
    }
    hasMatchingParent() {
        let parent = this.el.parentElement;
        while (parent && parent.tagName === 'IFX-MULTISELECT-OPTION') {
            const parentInstance = parent['__stencil_instance'];
            if (parentInstance) {
                const parentText = parentInstance.getTextContent().toLowerCase();
                if (parentText.includes(this.searchTerm)) {
                    return true;
                }
            }
            parent = parent.parentElement;
        }
        return false;
    }
    calculateDepth() {
        let depth = 0;
        let parent = this.el.parentElement;
        while (parent && parent.tagName !== 'IFX-MULTISELECT') {
            if (parent.tagName === 'IFX-MULTISELECT-OPTION') {
                depth++;
            }
            parent = parent.parentElement;
        }
        return depth;
    }
    handleClick(event) {
        if (this.disabled || (this.isSearchActive && this.isSearchDisabled))
            return;
        event.stopPropagation();
        if (event.type === 'click' && event.target.closest('.chevron-wrapper')) {
            this.toggleExpansion();
            return;
        }
        let newSelectedState;
        if (this.indeterminate) {
            newSelectedState = true;
        }
        else {
            newSelectedState = !this.selected;
        }
        this.selected = newSelectedState;
        this.indeterminate = false;
        if (this.hasChildren) {
            this.isExpanded = newSelectedState;
            requestAnimationFrame(() => {
                this.selectAllChildren(newSelectedState);
                this.expandAllChildren(newSelectedState);
            });
        }
        this.updateParentStates();
        this.notifyMultiselect();
    }
    handleKeyDown(event) {
        if (this.disabled || (this.isSearchActive && this.isSearchDisabled))
            return;
        const target = event.target;
        if (target.closest('.chevron-wrapper') || target.closest('.checkbox-wrapper')) {
            return;
        }
        if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') {
            event.stopPropagation();
        }
        if (event.key === 'ArrowRight' && this.hasChildren) {
            this.isExpanded = true;
        }
        if (event.key === 'ArrowLeft' && this.hasChildren) {
            this.isExpanded = false;
        }
    }
    notifyMultiselect() {
        const updateEvent = new CustomEvent('ifx-option-changed', {
            bubbles: true,
            detail: {
                value: this.value,
                selected: this.selected,
                indeterminate: this.indeterminate
            }
        });
        this.el.dispatchEvent(updateEvent);
    }
    selectAllChildren(selected) {
        const directChildren = Array.from(this.el.children)
            .filter(child => child.tagName === 'IFX-MULTISELECT-OPTION');
        directChildren.forEach((child) => {
            var _a;
            const childInstance = child['__stencil_instance'];
            if (childInstance) {
                childInstance.selected = selected;
                childInstance.indeterminate = false;
                if (childInstance.hasChildren) {
                    childInstance.isExpanded = selected;
                    childInstance.selectAllChildren(selected);
                }
                (_a = childInstance.notifyMultiselect) === null || _a === void 0 ? void 0 : _a.call(childInstance);
            }
        });
    }
    expandAllChildren(expanded) {
        const directChildren = Array.from(this.el.children)
            .filter(child => child.tagName === 'IFX-MULTISELECT-OPTION');
        directChildren.forEach((child) => {
            const childInstance = child['__stencil_instance'];
            if (childInstance && childInstance.hasChildren) {
                childInstance.isExpanded = expanded;
                childInstance.expandAllChildren(expanded);
            }
        });
    }
    updateParentStates() {
        var _a;
        let parent = this.el.parentElement;
        while (parent && parent.tagName === 'IFX-MULTISELECT-OPTION') {
            const parentInstance = parent['__stencil_instance'];
            if (!parentInstance) {
                parent = parent.parentElement;
                continue;
            }
            const siblings = Array.from(parent.children)
                .filter(child => child.tagName === 'IFX-MULTISELECT-OPTION')
                .map(child => child['__stencil_instance'])
                .filter(instance => instance !== null);
            const selectedCount = siblings.filter(sibling => sibling.selected).length;
            const indeterminateCount = siblings.filter(sibling => sibling.indeterminate).length;
            const totalCount = siblings.length;
            if (selectedCount === totalCount && indeterminateCount === 0) {
                parentInstance.selected = true;
                parentInstance.indeterminate = false;
            }
            else if (selectedCount === 0 && indeterminateCount === 0) {
                parentInstance.selected = false;
                parentInstance.indeterminate = false;
            }
            else {
                parentInstance.selected = false;
                parentInstance.indeterminate = true;
            }
            (_a = parentInstance.notifyMultiselect) === null || _a === void 0 ? void 0 : _a.call(parentInstance);
            parent = parent.parentElement;
        }
    }
    toggleExpansion() {
        this.isExpanded = !this.isExpanded;
    }
    hasAnySelectedChildren() {
        const childOptions = Array.from(this.el.children)
            .filter(child => child.tagName === 'IFX-MULTISELECT-OPTION');
        return childOptions.some(child => {
            const hasSelected = child.hasAttribute('selected');
            const hasSelectedDescendants = this.checkForSelectedDescendants(child);
            return hasSelected || hasSelectedDescendants;
        });
    }
    checkForSelectedDescendants(element) {
        const nestedOptions = Array.from(element.children)
            .filter(child => child.tagName === 'IFX-MULTISELECT-OPTION');
        return nestedOptions.some(nestedChild => {
            const isSelected = nestedChild.hasAttribute('selected');
            const hasSelectedNested = this.checkForSelectedDescendants(nestedChild);
            return isSelected || hasSelectedNested;
        });
    }
    render() {
        let isFlatMultiselect = false;
        const parentMultiselect = this.el.closest('ifx-multiselect');
        if (parentMultiselect) {
            const allOptions = Array.from(parentMultiselect.querySelectorAll('ifx-multiselect-option'));
            isFlatMultiselect = allOptions.every(option => option.children.length === 0);
        }
        const basePadding = this.depth * 28 + 16;
        const additionalPadding = this.hasChildren ? 0 : 28;
        let totalPadding = basePadding + additionalPadding;
        const optionItemStyle = isFlatMultiselect ? undefined : { paddingLeft: `${totalPadding}px` };
        return (h(Host, { key: '4dd008dabc4aec3070ad355aa877ff391e3883df' }, h("div", { key: '848afd2fa2a34c2b5763dc8c979d898b498b39b1', class: {
                'option': true,
                'option--has-children': this.hasChildren,
                'option--expanded': this.isExpanded,
                'option--disabled': this.disabled,
                'option--selected': this.selected,
            }, role: "option", "aria-expanded": this.hasChildren ? (this.isExpanded ? 'true' : 'false') : undefined, "aria-selected": this.selected ? 'true' : 'false', "aria-disabled": this.disabled ? 'true' : 'false', "data-level": this.depth, "data-value": this.value }, h("div", { key: '28fe299c78e8f42d9ef763ba14c84e0123276de8', class: "option-item", style: optionItemStyle }, h("div", { key: '891cd1a5c09c53df6c8079642aab48a893295cd8', class: "chevron-wrapper", tabIndex: this.hasChildren ? 0 : -1, role: this.hasChildren ? "button" : undefined, "aria-label": this.hasChildren ? (this.isExpanded ? "Collapse" : "Expand") : undefined, onClick: (e) => { e.stopPropagation(); this.toggleExpansion(); }, onKeyDown: (e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    e.stopPropagation();
                    this.toggleExpansion();
                }
            } }, this.hasChildren && (h("ifx-icon", { key: '7ddb0f0245f14fd8bc64fbfb3278c1d3a53f3834', class: `chevron ${this.isExpanded ? 'chevron--expanded' : 'chevron--collapsed'}`, icon: "chevron-right-16" }))), h("div", { key: 'a688fb56fd51cc1aefccf9b42d8f5c2a6ac271f8', class: "checkbox-wrapper", onClick: (e) => e.stopPropagation() }, h("ifx-checkbox", { key: '6ba8ea62a25285a59f3866dc0e7911b658477b3d', size: 's', checked: (this.isSearchActive && this.isSearchDisabled) ? false : (this.indeterminate ? false : this.selected), indeterminate: (this.isSearchActive && this.isSearchDisabled) ? false : this.indeterminate, onClick: this.handleCheckboxClick, disabled: this.disabled || (this.isSearchActive && this.isSearchDisabled), onKeyDown: (e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    e.stopPropagation();
                    this.handleCheckboxClick(e);
                }
            } })), h("div", { key: '63d0d6313ee94b3e80a2a0058fa1e79431becb29', class: "option-label", onClick: this.handleHeaderClick, tabIndex: -1 }, h("slot", { key: 'f503e85ef020cedec37931b6079a9164c1ce8d5d' }))), this.isExpanded && h("div", { key: '75297050484cdc4a9c80b2bff614119a7c18ff3f', class: "option-children" }, h("slot", { key: 'f33fbe0abb5e7c9277e24e0445838d8e4d0a6910', name: "children" })))));
    }
    get el() { return this; }
    static get style() { return multiselectOptionCss; }
}, [257, "ifx-multiselect-option", {
        "value": [1],
        "selected": [1540],
        "disabled": [1540],
        "indeterminate": [1540],
        "isExpanded": [32],
        "hasChildren": [32],
        "depth": [32],
        "searchTerm": [32],
        "isSearchActive": [32],
        "isSearchDisabled": [32]
    }, [[0, "click", "handleClick"], [0, "keydown", "handleKeyDown"]]]);
function defineCustomElement() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["ifx-multiselect-option", "ifx-checkbox", "ifx-icon"];
    components.forEach(tagName => { switch (tagName) {
        case "ifx-multiselect-option":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, MultiselectOption);
            }
            break;
        case "ifx-checkbox":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
        case "ifx-icon":
            if (!customElements.get(tagName)) {
                defineCustomElement$1();
            }
            break;
    } });
}

export { MultiselectOption as M, defineCustomElement as d };
//# sourceMappingURL=p-Bc_ZM813.js.map

//# sourceMappingURL=p-Bc_ZM813.js.map