import { Host, h, } from "@stencil/core";
import { removeDisabledFalse } from "../../utils/helpers";
const TOGGLE_GROUP = "IC-TOGGLE-BUTTON-GROUP";
export class ToggleButtonGroup {
    constructor() {
        this.lastKeyPressed = {
            key: null,
            shift: false,
        };
        /**
         * The accessible label of the toggle button group component to provide context for screen reader users.
         */
        this.accessibleLabel = "Toggle button group";
        /**
         * If `true`, the toggle button group will be set to the disabled state.
         */
        this.disabled = false;
        /**
         * If `true`, the toggle button group will fill the width of the container.
         */
        this.fullWidth = false;
        /**
         * If `true`, the toggle button group will be in loading state.
         */
        this.loading = false;
        /**
         * If `true`, the toggle button group will display as black in the light theme, and white in dark theme.
         */
        this.monochrome = false;
        /**
         * If `auto`, controls are toggled automatically when navigated to. If `manual`, the controls must be actioned to change their toggled state. The value of this prop is ignored if `selectType` is set to`multi`.
         */
        this.selectMethod = "manual";
        /**
         * Sets whether single or multiple options can be toggled. If `multi`, then the `selectMethod` is always `manual`.
         */
        this.selectType = "single";
        /**
         * The size of the toggle buttons to be displayed. This does not affect the font size of the accessible label.
         */
        this.size = "medium";
        /**
         * Sets the theme color to the dark or light theme color. "inherit" will set the color based on the system settings or ic-theme component.
         */
        this.theme = "inherit";
        /**
         * The position of the tooltip in relation to the toggle buttons.
         */
        this.tooltipPlacement = "bottom";
        /**
         * The variant of the toggle button.
         */
        this.variant = "default";
        this.keyListener = (ev) => {
            this.lastKeyPressed = {
                key: ev.key,
                shift: ev.shiftKey,
            };
        };
        this.setSlottedAria = (el) => {
            var _a, _b, _c;
            const btn = (_c = (_b = (_a = el.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector("ic-button")) === null || _b === void 0 ? void 0 : _b.shadowRoot) === null || _c === void 0 ? void 0 : _c.querySelector("button");
            let aria = btn.getAttribute("aria-label") || "";
            aria += ", ";
            aria += this.accessibleLabel;
            btn.setAttribute("aria-label", aria);
        };
        this.handleHostFocus = (ev) => {
            if (this.loading || this.disabled) {
                return null;
            }
            const el = ev.target;
            const relEl = ev.relatedTarget;
            const toggleButtons = Array.from(el.querySelectorAll("ic-toggle-button"));
            if (((toggleButtons.every((el) => !el.checked) ||
                this.selectType !== "single") &&
                this.lastKeyPressed.shift === false) ||
                (toggleButtons.every((el) => !el.checked) &&
                    this.lastKeyPressed.shift === true &&
                    relEl.tagName == TOGGLE_GROUP)) {
                toggleButtons[0].focus();
            }
            else if (this.lastKeyPressed.shift === false ||
                (this.lastKeyPressed.shift === true && relEl.tagName == TOGGLE_GROUP)) {
                // if checked is true and selectMethod is "single", focus that toggle
                const toggledButton = toggleButtons.filter((el) => el.checked);
                toggledButton[0].focus();
            }
        };
        this.handleKeyDown = (event) => {
            const toggleButtonOptions = this.getAllToggleButtons();
            const focussedChild = toggleButtonOptions.indexOf(toggleButtonOptions.filter((el) => el === document.activeElement)[0]);
            switch (event.key) {
                case "ArrowDown":
                case "ArrowRight":
                    this.selectMethod === "auto"
                        ? this.proxySelectHandler(toggleButtonOptions[this.getNextItemToSelect(focussedChild, true)])
                        : toggleButtonOptions[this.getNextItemToSelect(focussedChild, true)].focus();
                    break;
                case "ArrowUp":
                case "ArrowLeft":
                    this.selectMethod === "auto"
                        ? this.proxySelectHandler(toggleButtonOptions[this.getNextItemToSelect(focussedChild, false)])
                        : toggleButtonOptions[this.getNextItemToSelect(focussedChild, false)].focus();
                    break;
                case "Tab":
                    break;
            }
        };
        this.getNextItemToSelect = (currentItem, movingDown) => {
            const toggleButtonOptions = this.getAllToggleButtons();
            const numToggles = toggleButtonOptions.length - 1;
            if (currentItem < 1) {
                currentItem = 0;
            }
            let nextItem = movingDown ? currentItem + 1 : currentItem - 1;
            if (nextItem < 0) {
                nextItem = numToggles;
            }
            else if (nextItem > numToggles) {
                nextItem = 0;
            }
            if (toggleButtonOptions[nextItem].disabled) {
                nextItem = this.getNextItemToSelect(nextItem, movingDown);
            }
            return nextItem;
        };
    }
    watchDisabledHandler() {
        this.getAllToggleButtons().forEach((el) => {
            el.disabled = this.disabled;
        });
        removeDisabledFalse(this.disabled, this.el);
    }
    watchFullWidthHandler() {
        this.getAllToggleButtons().forEach((el) => {
            el.fullWidth = this.fullWidth;
        });
    }
    watchLoadingHandler() {
        this.getAllToggleButtons().forEach((el) => {
            el.loading = this.loading;
        });
    }
    watchMonochromeHandler() {
        this.getAllToggleButtons().forEach((el) => {
            el.monochrome = this.monochrome;
        });
    }
    watchSizeHandler() {
        this.getAllToggleButtons().forEach((el) => {
            el.size = this.size;
        });
    }
    watchThemeHandler() {
        this.getAllToggleButtons().forEach((el) => {
            el.theme = this.theme;
        });
    }
    watchTooltipPlacementHandler() {
        this.getAllToggleButtons().forEach((el) => {
            el.tooltipPlacement = this.tooltipPlacement;
        });
    }
    watchVariantHandler() {
        this.getAllToggleButtons().forEach((el) => {
            el.variant = this.variant;
        });
    }
    selectHandler(ev, tabTarget) {
        const allToggles = this.getAllToggleButtons();
        let clickedToggle = ev.target;
        // tabTarget used in proxySelectHandler
        tabTarget && tabTarget.focus();
        if (this.selectType === "single") {
            if (!clickedToggle && tabTarget) {
                clickedToggle = tabTarget;
            }
            allToggles.forEach((el) => {
                if (el.id !== clickedToggle.id && el.checked) {
                    el.checked = false;
                }
            });
            this.icChange.emit({
                checked: ev.detail.checked,
                selectedOption: clickedToggle,
            });
        }
        else {
            const toggledOptions = this.getAllToggleButtons().filter((el) => el.checked && !el.disabled);
            this.icChange.emit({
                checked: toggledOptions.map((opt) => opt.checked),
                toggledOptions: toggledOptions.map((opt) => ({
                    toggleButton: opt,
                })),
                selectedOption: clickedToggle,
            });
        }
    }
    componentWillLoad() {
        this.selectType === "multi" && (this.selectMethod = "manual");
        this.selectMethod === "auto" && this.selectType === "single";
        document.addEventListener("keydown", this.keyListener);
        removeDisabledFalse(this.disabled, this.el);
    }
    componentDidLoad() {
        this.getAllToggleButtons().forEach((el, i) => {
            this.setSlottedAria(el);
            el.id = i.toString();
            el.tabIndex = -1;
            el.addEventListener("keydown", (ev) => {
                this.handleKeyDown(ev);
            });
            el.classList.add("expand-toggle-group-child");
        });
    }
    disconnectedCallback() {
        document === null || document === void 0 ? void 0 : document.removeEventListener("keydown", this.keyListener);
    }
    // trigger selectHandler when unable to add 'target'
    proxySelectHandler(toggle) {
        toggle.checked = true;
        const customEv = new CustomEvent("icToggleChecked", {
            detail: {
                checked: toggle.checked,
            },
        });
        this.selectHandler(customEv, toggle);
    }
    getAllToggleButtons() {
        return Array.from(this.el.querySelectorAll("ic-toggle-button"));
    }
    render() {
        return (h(Host, { key: '5ff90397f901e294f15f3f560eac22d575b61c62', role: "group", "aria-label": this.accessibleLabel, tabindex: 0, class: {
                [`ic-theme-${this.theme}`]: this.theme !== "inherit",
                ["ic-toggle-button-group-full-width"]: !!this.fullWidth,
                ["ic-toggle-button-group-loading"]: !!this.loading,
                ["ic-toggle-button-group-disabled"]: this.disabled,
                [`ic-toggle-button-group-monochrome`]: !!this.monochrome,
                [`ic-theme-${this.theme}`]: this.theme !== "inherit",
            }, onFocus: this.handleHostFocus }, h("slot", { key: 'c30679fee25ec96c7d28123d9758173737922e18' })));
    }
    static get is() { return "ic-toggle-button-group"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["ic-toggle-button-group.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["ic-toggle-button-group.css"]
        };
    }
    static get properties() {
        return {
            "accessibleLabel": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string | undefined",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "The accessible label of the toggle button group component to provide context for screen reader users."
                },
                "getter": false,
                "setter": false,
                "attribute": "accessible-label",
                "reflect": false,
                "defaultValue": "\"Toggle button group\""
            },
            "disabled": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "If `true`, the toggle button group will be set to the disabled state."
                },
                "getter": false,
                "setter": false,
                "attribute": "disabled",
                "reflect": false,
                "defaultValue": "false"
            },
            "fullWidth": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean | undefined",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "If `true`, the toggle button group will fill the width of the container."
                },
                "getter": false,
                "setter": false,
                "attribute": "full-width",
                "reflect": false,
                "defaultValue": "false"
            },
            "iconPlacement": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "\"left\" | \"right\" | \"top\"",
                    "resolved": "\"left\" | \"right\" | \"top\" | undefined",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "The placement of the icons in relation to the toggle button labels."
                },
                "getter": false,
                "setter": false,
                "attribute": "icon-placement",
                "reflect": false
            },
            "loading": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean | undefined",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "If `true`, the toggle button group will be in loading state."
                },
                "getter": false,
                "setter": false,
                "attribute": "loading",
                "reflect": false,
                "defaultValue": "false"
            },
            "monochrome": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean | undefined",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "If `true`, the toggle button group will display as black in the light theme, and white in dark theme."
                },
                "getter": false,
                "setter": false,
                "attribute": "monochrome",
                "reflect": false,
                "defaultValue": "false"
            },
            "selectMethod": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "IcSelectMethodTypes",
                    "resolved": "\"auto\" | \"manual\" | undefined",
                    "references": {
                        "IcSelectMethodTypes": {
                            "location": "import",
                            "path": "../../utils/types",
                            "id": "src/utils/types.ts::IcSelectMethodTypes"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "If `auto`, controls are toggled automatically when navigated to. If `manual`, the controls must be actioned to change their toggled state. The value of this prop is ignored if `selectType` is set to`multi`."
                },
                "getter": false,
                "setter": false,
                "attribute": "select-method",
                "reflect": false,
                "defaultValue": "\"manual\""
            },
            "selectType": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "IcSelectTypes",
                    "resolved": "\"multi\" | \"single\" | undefined",
                    "references": {
                        "IcSelectTypes": {
                            "location": "import",
                            "path": "../../utils/types",
                            "id": "src/utils/types.ts::IcSelectTypes"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Sets whether single or multiple options can be toggled. If `multi`, then the `selectMethod` is always `manual`."
                },
                "getter": false,
                "setter": false,
                "attribute": "select-type",
                "reflect": false,
                "defaultValue": "\"single\""
            },
            "size": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "IcSizes",
                    "resolved": "\"large\" | \"medium\" | \"small\" | undefined",
                    "references": {
                        "IcSizes": {
                            "location": "import",
                            "path": "../../utils/types",
                            "id": "src/utils/types.ts::IcSizes"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "The size of the toggle buttons to be displayed. This does not affect the font size of the accessible label."
                },
                "getter": false,
                "setter": false,
                "attribute": "size",
                "reflect": false,
                "defaultValue": "\"medium\""
            },
            "theme": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "IcThemeMode",
                    "resolved": "\"dark\" | \"inherit\" | \"light\" | undefined",
                    "references": {
                        "IcThemeMode": {
                            "location": "import",
                            "path": "../../utils/types",
                            "id": "src/utils/types.ts::IcThemeMode"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Sets the theme color to the dark or light theme color. \"inherit\" will set the color based on the system settings or ic-theme component."
                },
                "getter": false,
                "setter": false,
                "attribute": "theme",
                "reflect": false,
                "defaultValue": "\"inherit\""
            },
            "tooltipPlacement": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "IcButtonTooltipPlacement",
                    "resolved": "\"bottom\" | \"left\" | \"right\" | \"top\"",
                    "references": {
                        "IcButtonTooltipPlacement": {
                            "location": "import",
                            "path": "../../utils/types",
                            "id": "src/utils/types.ts::IcButtonTooltipPlacement"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The position of the tooltip in relation to the toggle buttons."
                },
                "getter": false,
                "setter": false,
                "attribute": "tooltip-placement",
                "reflect": false,
                "defaultValue": "\"bottom\""
            },
            "variant": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "\"default\" | \"icon\"",
                    "resolved": "\"default\" | \"icon\"",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The variant of the toggle button."
                },
                "getter": false,
                "setter": false,
                "attribute": "variant",
                "reflect": true,
                "defaultValue": "\"default\""
            }
        };
    }
    static get states() {
        return {
            "lastKeyPressed": {}
        };
    }
    static get events() {
        return [{
                "method": "icChange",
                "name": "icChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when a toggle button is selected."
                },
                "complexType": {
                    "original": "IcChangeEventDetail",
                    "resolved": "IcChangeEventDetail",
                    "references": {
                        "IcChangeEventDetail": {
                            "location": "import",
                            "path": "./ic-toggle-button-group.types",
                            "id": "src/components/ic-toggle-button-group/ic-toggle-button-group.types.ts::IcChangeEventDetail"
                        }
                    }
                }
            }];
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "disabled",
                "methodName": "watchDisabledHandler"
            }, {
                "propName": "fullWidth",
                "methodName": "watchFullWidthHandler"
            }, {
                "propName": "loading",
                "methodName": "watchLoadingHandler"
            }, {
                "propName": "monochrome",
                "methodName": "watchMonochromeHandler"
            }, {
                "propName": "size",
                "methodName": "watchSizeHandler"
            }, {
                "propName": "theme",
                "methodName": "watchThemeHandler"
            }, {
                "propName": "tooltipPlacement",
                "methodName": "watchTooltipPlacementHandler"
            }, {
                "propName": "variant",
                "methodName": "watchVariantHandler"
            }];
    }
    static get listeners() {
        return [{
                "name": "icToggleChecked",
                "method": "selectHandler",
                "target": undefined,
                "capture": false,
                "passive": false
            }];
    }
}
//# sourceMappingURL=ic-toggle-button-group.js.map
