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,
        };
        this.externallySetActiveToggle = null;
        /**
         * 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 `true`, the toggle button group will display with an outline.
         */
        this.outline = true;
        /**
         * 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.handleHostFocus = ({ target, relatedTarget }) => {
            var _a;
            if (this.disabled) {
                target === null || target === void 0 ? void 0 : target.blur();
                return;
            }
            if (this.loading)
                return;
            const el = target;
            const relEl = relatedTarget;
            const toggleButtons = Array.from((el === null || el === void 0 ? void 0 : el.querySelectorAll("ic-toggle-button")) || []);
            const noToggleButtonsChecked = toggleButtons.every((el) => !el.checked);
            const { shift } = this.lastKeyPressed;
            if (((noToggleButtonsChecked || this.selectType !== "single") && !shift) ||
                (noToggleButtonsChecked && shift && (relEl === null || relEl === void 0 ? void 0 : relEl.tagName) == TOGGLE_GROUP)) {
                (_a = toggleButtons[0]) === null || _a === void 0 ? void 0 : _a.focus();
            }
            else if (!shift || (relEl === null || relEl === void 0 ? void 0 : relEl.tagName) == TOGGLE_GROUP) {
                // if checked is true and selectMethod is "single", focus that toggle
                toggleButtons.filter((el) => el.checked)[0].focus();
            }
        };
        this.handleKeyDown = ({ key }) => {
            if (key !== "ArrowDown" &&
                key !== "ArrowRight" &&
                key !== "ArrowLeft" &&
                key !== "ArrowUp")
                return;
            const toggleButtonOptions = this.getAllToggleButtons();
            let targetToggle;
            if (this.externallySetActiveToggle) {
                targetToggle =
                    toggleButtonOptions[this.getNextItemToSelect(toggleButtonOptions.indexOf(toggleButtonOptions.filter((el) => el === this.externallySetActiveToggle)[0]), key === "ArrowDown" || key === "ArrowRight")];
            }
            else {
                targetToggle =
                    toggleButtonOptions[this.getNextItemToSelect(toggleButtonOptions.indexOf(toggleButtonOptions.filter((el) => el === document.activeElement)[0]), key === "ArrowDown" || key === "ArrowRight")];
            }
            if (this.selectMethod === "auto") {
                // trigger selectHandler when unable to add 'target'
                targetToggle.checked = true;
                this.selectHandler(new CustomEvent("icToggleChecked", {
                    detail: {
                        checked: targetToggle.checked,
                    },
                }), targetToggle);
            }
            else {
                targetToggle.focus();
            }
        };
        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;
        };
        this.getAllToggleButtons = () => Array.from(this.el.querySelectorAll("ic-toggle-button"));
    }
    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;
        });
    }
    watchOutlineHandler() {
        this.getAllToggleButtons().forEach((el) => {
            el.outline = this.outline;
        });
    }
    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;
        if (tabTarget)
            tabTarget.focus(); // tabTarget used in proxySelectHandler
        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 = allToggles.filter((el) => el.checked && !el.disabled);
            this.icChange.emit({
                checked: toggledOptions.map((opt) => opt.checked),
                toggledOptions: toggledOptions.map((opt) => ({
                    toggleButton: opt,
                })),
                selectedOption: clickedToggle,
            });
        }
    }
    /**
     * @internal Used to enable other components to set the active toggle button when toggle button group is in a shadow dom.
     */
    async setActiveToggle(toggle) {
        this.externallySetActiveToggle = toggle;
    }
    componentWillLoad() {
        if (this.selectType === "multi")
            this.selectMethod = "manual";
        if (this.selectMethod === "auto")
            this.selectType === "single";
        document.addEventListener("keydown", this.keyListener);
        removeDisabledFalse(this.disabled, this.el);
    }
    componentDidLoad() {
        this.getAllToggleButtons().forEach((el, i) => {
            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");
            if (btn) {
                const btnAriaLabel = btn.getAttribute("aria-label");
                const aria = btnAriaLabel ? `${btnAriaLabel}, ` : "";
                btn.setAttribute("aria-label", `${aria}${this.accessibleLabel}`);
            }
            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);
    }
    render() {
        const { accessibleLabel, disabled, fullWidth, loading, monochrome, outline, theme, } = this;
        return (h(Host, { key: '1238ec0b93b309a3945791eff6f847fb10b0abf5', role: "group", "aria-label": accessibleLabel, tabindex: disabled ? -1 : 0, class: {
                "ic-toggle-button-group-disabled": disabled,
                "ic-toggle-button-group-full-width": fullWidth,
                "ic-toggle-button-group-loading": loading,
                "ic-toggle-button-group-monochrome": monochrome,
                "ic-toggle-button-group-hide-outline": !outline,
                [`ic-theme-${theme}`]: theme !== "inherit",
            }, onFocus: this.handleHostFocus }, h("slot", { key: '6dfd004b9e0c386362d8172334dfca2f1e6274fc' })));
    }
    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",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "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",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "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": "IcIconPlacementOptions",
                    "resolved": "\"left\" | \"right\" | \"top\" | undefined",
                    "references": {
                        "IcIconPlacementOptions": {
                            "location": "import",
                            "path": "../../utils/types",
                            "id": "src/utils/types.ts::IcIconPlacementOptions"
                        }
                    }
                },
                "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",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "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",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "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"
            },
            "outline": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "If `true`, the toggle button group will display with an outline."
                },
                "getter": false,
                "setter": false,
                "attribute": "outline",
                "reflect": false,
                "defaultValue": "true"
            },
            "selectMethod": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "IcSelectMethodTypes",
                    "resolved": "\"auto\" | \"manual\"",
                    "references": {
                        "IcSelectMethodTypes": {
                            "location": "import",
                            "path": "../../utils/types",
                            "id": "src/utils/types.ts::IcSelectMethodTypes"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "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\"",
                    "references": {
                        "IcSelectTypes": {
                            "location": "import",
                            "path": "../../utils/types",
                            "id": "src/utils/types.ts::IcSelectTypes"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "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\"",
                    "references": {
                        "IcSizes": {
                            "location": "import",
                            "path": "../../utils/types",
                            "id": "src/utils/types.ts::IcSizes"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "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\"",
                    "references": {
                        "IcThemeMode": {
                            "location": "import",
                            "path": "../../utils/types",
                            "id": "src/utils/types.ts::IcThemeMode"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "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": {},
            "externallySetActiveToggle": {}
        };
    }
    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 methods() {
        return {
            "setActiveToggle": {
                "complexType": {
                    "signature": "(toggle: HTMLIcToggleButtonElement) => Promise<void>",
                    "parameters": [{
                            "name": "toggle",
                            "type": "HTMLIcToggleButtonElement",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "HTMLIcToggleButtonElement": {
                            "location": "global",
                            "id": "global::HTMLIcToggleButtonElement"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": [{
                            "name": "internal",
                            "text": "Used to enable other components to set the active toggle button when toggle button group is in a shadow dom."
                        }]
                }
            }
        };
    }
    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": "outline",
                "methodName": "watchOutlineHandler"
            }, {
                "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
