'use strict';

var index = require('./index-pX0sBY0-.js');
var domUtils = require('./dom-utils-BdvOgC2b.js');
var tracking = require('./tracking-BPjaTlNR.js');

const chipCss = () => `:host{display:inline-block}.chip{position:relative}.chip__wrapper{display:inline-flex;align-items:center;justify-content:center;gap:8px;box-sizing:border-box;border-radius:9999px;background:#FFFFFF;cursor:pointer;transition:border 100ms ease;font:400 0.875rem/1.25rem "Source Sans 3"}.chip__wrapper .icon__wrapper{display:flex}.chip__wrapper.outlined,.chip__wrapper.filled-dark,.chip__wrapper.filled-light{outline:2px solid transparent}.chip__wrapper.outlined:focus-visible,.chip__wrapper.filled-dark:focus-visible,.chip__wrapper.filled-light:focus-visible{outline:2px solid #0A8276;outline-offset:2px}.chip__wrapper.outlined.chip__wrapper--opened .wrapper__open-button,.chip__wrapper.filled-dark.chip__wrapper--opened .wrapper__open-button,.chip__wrapper.filled-light.chip__wrapper--opened .wrapper__open-button{transform:rotate(-180deg)}.chip__wrapper.outlined.chip__wrapper--selected .wrapper__label .label__selected-options,.chip__wrapper.filled-dark.chip__wrapper--selected .wrapper__label .label__selected-options,.chip__wrapper.filled-light.chip__wrapper--selected .wrapper__label .label__selected-options{font:400 0.875rem/1.25rem "Source Sans 3"}.chip__wrapper.filled-dark.chip__wrapper--selected:not(.read-only),.chip__wrapper.filled-light.chip__wrapper--selected:not(.read-only){background-color:#0A8276;color:white}.chip__wrapper.filled-dark.chip__wrapper--selected:not(.read-only):hover,.chip__wrapper.filled-light.chip__wrapper--selected:not(.read-only):hover{background-color:#08665C}.chip__wrapper.filled-dark.chip__wrapper--selected:not(.read-only):hover.disabled,.chip__wrapper.filled-light.chip__wrapper--selected:not(.read-only):hover.disabled{background-color:#0A8276}.chip__wrapper.outlined{border:1px solid #8D8786}.chip__wrapper.outlined:hover:not(.read-only){border-color:#575352;background-color:#F7F7F7}.chip__wrapper.outlined:active:not(.read-only){border-color:#575352;background-color:#BFBBBB}.chip__wrapper.outlined.chip__wrapper--opened{border:1px solid #0A8276}.chip__wrapper.outlined.chip__wrapper--selected{outline:3px solid #0A8276;border:1px solid transparent;background-color:white}.chip__wrapper.outlined.chip__wrapper--selected:focus-visible{outline-offset:0px}.chip__wrapper.outlined.chip__wrapper--selected:hover:not(.read-only){outline-color:#08665C}.chip__wrapper.outlined.chip__wrapper--selected.read-only{outline:none;border:1px solid black}.chip__wrapper.outlined.chip__wrapper--selected.read-only.disabled{border:1px solid #BFBBBB}.chip__wrapper.outlined.disabled{outline:none;color:#BFBBBB;border:1px solid #BFBBBB}.chip__wrapper.outlined.disabled:hover{outline:none;border-color:#BFBBBB;background-color:white}.chip__wrapper.outlined.read-only{border:1px solid #8D8786}.chip__wrapper.outlined.read-only:focus-visible{outline:2px solid #0A8276;outline-offset:2px}.chip__wrapper.outlined.read-only.disabled{border:1px solid #BFBBBB}.chip__wrapper.filled-dark{background-color:#3C3A39;color:white}.chip__wrapper.filled-dark:hover:not(.chip__wrapper--selected,.disabled,.read-only){background-color:#575352}.chip__wrapper.filled-dark:active:not(.chip__wrapper--selected,.disabled,.read-only){background-color:#8D8786;color:black}.chip__wrapper.filled-dark.disabled{outline:none;color:#BFBBBB}.chip__wrapper.filled-dark.disabled:hover:not(.chip__wrapper--selected){background-color:#3C3A39}.chip__wrapper.filled-dark.chip__wrapper--selected.read-only{border:1px solid #8D8786}.chip__wrapper.filled-dark.read-only{border:1px solid #8D8786}.chip__wrapper.filled-light{background-color:#EEEDED}.chip__wrapper.filled-light:hover:not(.read-only){background-color:#BFBBBB}.chip__wrapper.filled-light:active:not(.read-only){background-color:#8D8786}.chip__wrapper.filled-light.disabled{outline:none;color:#BFBBBB}.chip__wrapper.filled-light.disabled:hover:not(.chip__wrapper--selected){background-color:#EEEDED}.chip__wrapper.filled-light.chip__wrapper--selected.read-only{border:1px solid black}.chip__wrapper.filled-light.chip__wrapper--selected.read-only.disabled{border:none}.chip__wrapper.filled-light.read-only{border:1px solid black}.chip__wrapper.filled-light.read-only.disabled{border:none}.chip__wrapper.chip__wrapper--small{padding:4px 8px;height:24px}.chip__wrapper.chip__wrapper--medium{padding:4px 12px;height:28px}.chip__wrapper.chip__wrapper--large{padding:8px 12px;height:36px}.wrapper__label{display:inline-flex;align-items:center;gap:4px}.wrapper__label .label__selected-options{font:600 0.875rem/1.25rem "Source Sans 3"}.wrapper__open-button{display:flex;align-items:center}.wrapper__unselect-button{display:flex;align-items:center}.chip__dropdown{position:absolute;z-index:1;box-shadow:0px 6px 9px 0px rgba(29, 29, 29, 0.1019607843);border:1px solid #EEEDED;border-radius:1px;padding:8px 0;min-width:222px;background-color:#FFFFFF}`;

const Chip = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.ifxChange = index.createEvent(this, "ifxChange", 7);
    }
    get chip() { return index.getElement(this); }
    /** Fires on selection change. */
    ifxChange;
    /** Placeholder text */
    placeholder = "";
    /** Component size */
    size = "medium";
    /** Current selection (mutable) */
    value = undefined;
    /** Selection mode */
    variant = "single";
    /** Visual theme */
    theme = "outlined";
    /** Read-only state */
    readOnly = false;
    /** ARIA Label text */
    ariaLabelText;
    /** Disabeled state */
    disabled = false;
    /** Sets Icon */
    icon = "";
    opened = false;
    selectedOptions = [];
    handleValueChange(newValue) {
        this.syncSelectedOptionsWithProp(newValue);
    }
    handleReadOnlyChange(newValue) {
        if (newValue) {
            this.opened = false;
        }
    }
    closeDropdownOnOutsideClick(event) {
        const path = event.composedPath();
        const chipWrapper = this.chip.shadowRoot.querySelector(".chip__wrapper");
        const chipDropdown = this.chip.shadowRoot.querySelector(".chip__dropdown");
        if (!path.includes(chipDropdown) &&
            !path.includes(chipWrapper) &&
            this.opened) {
            this.toggleDropdownMenu();
        }
    }
    /* @Listen("keydown") */
    handleKeyDown(event) {
        // override behavior of all keys except Tab. Users should be able to tab out of the component.
        if (event.code !== "Tab") {
            event.preventDefault();
        }
        if (event.target.tagName === "IFX-CHIP") {
            this.handleWrapperKeyDown(event);
        }
        else if (event.target.tagName === "IFX-CHIP-ITEM") {
            this.handleDropdownKeyDown(event);
        }
    }
    updateSelectedOptions(event) {
        const eventDetail = event.detail;
        const previousSelection = [
            ...this.selectedOptions,
        ];
        if (this.variant !== "multi") {
            if (eventDetail.selected) {
                this.opened = false;
                const chipItems = this.getChipItems();
                chipItems.forEach((chipItem) => {
                    if (chipItem.selected && chipItem !== event.target) {
                        chipItem.chipState = {
                            ...chipItem.chipState,
                            emitIfxChipItemSelect: false,
                        };
                        chipItem.selected = false;
                    }
                });
                this.selectedOptions = [eventDetail];
            }
            else {
                this.selectedOptions = [];
            }
            this.value = this.selectedOptions[0]
                ? this.selectedOptions[0].value
                : undefined;
        }
        else {
            if (eventDetail.selected) {
                // Prevent duplicate entries
                if (!this.selectedOptions.find((option) => option.value === eventDetail.value)) {
                    this.selectedOptions = [...this.selectedOptions, eventDetail];
                }
            }
            else {
                this.selectedOptions = this.selectedOptions.filter((option) => option.value !== eventDetail.value);
            }
            this.value = this.selectedOptions.map((option) => option.value);
        }
        if (eventDetail.emitIfxChange) {
            this.ifxChange.emit({
                previousSelection: previousSelection,
                currentSelection: this.selectedOptions,
                name: this.placeholder,
            });
        }
    }
    getChipItems() {
        return this.chip.querySelectorAll("ifx-chip-item");
    }
    getSelectedOptions() {
        if (this.variant !== "multi") {
            return this.selectedOptions.map((option) => option.label).join("");
        }
        return this.selectedOptions
            .slice(0, 2)
            .map((option) => option.label)
            .join(", ");
    }
    toggleDropdownMenu() {
        if (this.readOnly)
            return;
        this.opened = !this.opened;
    }
    /**
     * Focuses the chip item at the specified index.
     * @param index the index of the chip item to focus. -1 will focus the last chip item.
     */
    focusChipItemAt(index = 0) {
        this.opened = true;
        const chipItems = this.getChipItems();
        let item;
        if (index === -1) {
            item = chipItems.item(chipItems.length - 1);
        }
        else if (index >= 0 && index < chipItems.length) {
            item = chipItems.item(index);
        }
        else {
            console.error(`Invalid index: ${index}`);
            return;
        }
        const shadowItem = item.shadowRoot.querySelector(".chip-item");
        if (shadowItem) {
            // Delay needed for the shadow item to be rendered.
            setTimeout(() => {
                shadowItem.focus();
            }, 1);
        }
    }
    focusChip() {
        const chipWrapper = this.chip.shadowRoot.querySelector(".chip__wrapper");
        chipWrapper.focus();
    }
    handleUnselectButtonClick(event) {
        event.stopPropagation();
        this.opened = false;
        let itemGotUnselected = false;
        const chipItems = this.getChipItems();
        chipItems.forEach((chipItem) => {
            if (chipItem.selected) {
                itemGotUnselected = true;
                chipItem.chipState = {
                    ...chipItem.chipState,
                    emitIfxChipItemSelect: false,
                };
                chipItem.selected = false;
            }
        });
        /* Emit event only if at least one item was unselected. */
        if (itemGotUnselected) {
            const previousSelection = this.selectedOptions;
            this.selectedOptions = [];
            this.value = [];
            this.ifxChange.emit({
                previousSelection: previousSelection,
                currentSelection: [],
                name: this.placeholder,
            });
        }
    }
    handleWrapperClick() {
        if (!this.readOnly) {
            this.toggleDropdownMenu();
        }
    }
    handleWrapperKeyDown(event) {
        // Keymap oriented at https://www.w3.org/WAI/ARIA/apg/patterns/combobox/#keyboard_interaction
        if (this.readOnly)
            return;
        if (!this.opened) {
            switch (event.code) {
                case "Space":
                case "Enter":
                case "ArrowDown":
                    this.focusChipItemAt(0);
                    break;
                case "ArrowUp":
                    this.focusChipItemAt(-1);
                    break;
            }
        }
        else {
            switch (event.code) {
                case "Escape":
                    this.opened = false;
                    this.focusChip();
                    break;
            }
        }
    }
    handleDropdownKeyDown(event) {
        const chipitems = this.getChipItems();
        const targetIndex = Array.from(chipitems).indexOf(event.target);
        if (targetIndex === -1) {
            console.error("Target not found in chip items");
            return;
        }
        switch (event.code) {
            case "ArrowDown":
                if (targetIndex === chipitems.length - 1)
                    break;
                this.focusChipItemAt(targetIndex + 1);
                break;
            case "ArrowUp":
                if (targetIndex === 0)
                    break;
                this.focusChipItemAt(targetIndex - 1);
                break;
            case "Escape":
                this.opened = false;
                this.focusChip();
                break;
            case "Space":
                // selection is handled by the chip-item component
                if (this.variant === "single") {
                    // only close dropdown if single select
                    this.opened = false;
                    this.focusChip();
                }
                break;
            case "Enter":
                // selection is handled by the chip-item component
                this.opened = false;
                this.focusChip();
                break;
        }
    }
    syncChipState() {
        const chipItems = this.getChipItems();
        let key = 0;
        chipItems.forEach((chipItem) => {
            chipItem.chipState = {
                emitIfxChipItemSelect: true,
                size: this.size ? this.size : "medium",
                variant: this.variant === "multi" ? "multi" : "single",
                key: key++,
            };
        });
    }
    syncSelectedOptionsWithProp(newValue) {
        // Clear old selected options
        this.selectedOptions = [];
        const generateKey = (() => {
            let count = 0;
            return () => count++;
        })();
        if (Array.isArray(newValue)) {
            this.selectedOptions = newValue.map((value) => ({
                value,
                label: value,
                selected: true,
                key: generateKey(),
                emitIfxChange: true,
            }));
        }
        else if (typeof newValue === "string") {
            this.selectedOptions = [
                {
                    value: newValue,
                    label: newValue,
                    selected: true,
                    key: generateKey(),
                    emitIfxChange: true,
                },
            ];
        }
        this.syncChipState();
    }
    componentWillLoad() {
        this.syncSelectedOptionsWithProp(this.value);
    }
    async componentDidLoad() {
        if (!domUtils.isNestedInIfxComponent(this.chip)) {
            const framework = tracking.detectFramework();
            tracking.trackComponent("ifx-chip", await framework);
        }
    }
    render() {
        return (index.h(index.Host, { key: 'b2a9cf66e703236a7d1ac3cab4142b1485793483', OnKeyDown: this.handleKeyDown }, index.h("div", { key: '6220cac71e25083e1804b1365b4b8a0d9195e8c1', class: "chip", part: "chip" }, index.h("div", { key: '4a1541910629625e88180f43e8dc9fecec83529d', class: `chip__wrapper chip__wrapper--${this.size ? this.size : "medium"}
                  chip__wrapper--${this.variant === "multi" ? "multi" : "single"}
                  ${this.opened && !this.readOnly ? "chip__wrapper--opened" : ""}
                  ${this.selectedOptions.length ? "chip__wrapper--selected" : ""}
                  ${this.theme ? this.theme : "outlined"}
                  ${this.disabled ? "disabled" : ""}
                  ${this.readOnly ? "read-only" : ""}`, tabIndex: 0, onClick: !this.readOnly && !this.disabled
                ? () => {
                    this.handleWrapperClick();
                }
                : undefined, role: "combobox", "aria-label-text": this.ariaLabelText, "aria-value": this.getSelectedOptions(), "aria-haspopup": !this.readOnly ? "listbox" : undefined, "aria-expanded": !this.readOnly ? this.opened.toString() : undefined, "aria-controls": !this.readOnly ? "dropdown" : undefined, "aria-readonly": this.readOnly ? "true" : undefined, "aria-multiselectable": this.variant === "multi" ? "true" : undefined, part: "label-wrapper" }, this.icon && (index.h("div", { key: '835af90b43d8db0b48b738eb37e56953dcaea5f4', class: "icon__wrapper" }, index.h("ifx-icon", { key: 'bf862d4ef5fc04ebac55f73a478aa69da6c5d3b5', icon: this.icon }))), index.h("div", { key: '64905c9ebc56df0552563f55e117ca473a307f39', class: "wrapper__label", part: "label" }, this.selectedOptions.length === 0 && `${this.placeholder}`, this.selectedOptions.length !== 0 &&
            this.variant === "multi" &&
            this.placeholder !== "" &&
            `${this.placeholder}:`, this.selectedOptions.length !== 0 && (index.h("div", { key: 'd8aa569742b34eab4379f244980a150bd0899e5e', class: "label__selected-options" }, this.getSelectedOptions())), this.selectedOptions.length > 2 && this.variant === "multi" && (index.h("ifx-indicator", { key: 'c6699fa70c11fefb14e7a4b13236bc69ce7f01fb', variant: "number", inverted: this.theme === "outlined" ? false : true, number: this.selectedOptions.length - 2 }))), !this.readOnly &&
            (this.variant !== "multi" ||
                (this.variant === "multi" &&
                    this.selectedOptions.length === 0)) && (index.h("div", { key: 'e614b584038e35e5e5e1695d7bbbe82b32951747', class: "wrapper__open-button" }, index.h("ifx-icon", { key: 1, icon: `chevron-down-16` }))), this.selectedOptions.length >= 1 && this.variant === "multi" && (index.h("div", { key: 'e2a723b2ac07d969359a23e2843c8d593e5d04ae', class: "wrapper__unselect-button", onClick: !this.readOnly && !this.disabled
                ? (e) => {
                    this.handleUnselectButtonClick(e);
                }
                : undefined }, index.h("ifx-icon", { key: 2, icon: `cross16` })))), this.opened && !this.readOnly && (index.h("div", { key: 'a1fc7cb6da87b6f8b81ca694cdce1a145e33711d', id: "dropdown", role: "listbox", class: "chip__dropdown" }, index.h("slot", { key: '35042c304886e75b568dcdae71dc16915d69e28e' }))))));
    }
    static get watchers() { return {
        "value": [{
                "handleValueChange": 0
            }],
        "readOnly": [{
                "handleReadOnlyChange": 0
            }]
    }; }
};
Chip.style = chipCss();

exports.ifx_chip = Chip;
