import { h, Host } from "@stencil/core";
import { trackComponent } from "../../global/utils/tracking";
import { isNestedInIfxComponent } from "../../global/utils/dom-utils";
import { detectFramework } from "../../global/utils/framework-detection";
export class ContentSwitcher {
    constructor() {
        this.activeIndex = -1;
        this.hoverIndex = -1;
        this.focusIndex = -1;
        this.dividers = Array();
        this.eventHandlers = new Map();
    }
    componentWillLoad() {
        this.items = Array.from(this.el.children);
        this.initializeDividers();
        this.addEventListeners();
        this.ensureSingleSelectedItem();
    }
    async componentDidLoad() {
        if (!isNestedInIfxComponent(this.el)) {
            const framework = detectFramework();
            trackComponent('ifx-content-switcher', await framework);
        }
    }
    disconnectedCallback() {
        this.removeEventListeners();
    }
    /**
     * Initialize the dividers between items.
     */
    initializeDividers() {
        this.items.forEach((item, index) => {
            if (index < this.items.length - 1) {
                const divider = document.createElement('div');
                divider.classList.add('ifx-content-switcher-divider');
                item.after(divider);
                this.dividers.push(divider);
            }
        });
    }
    /**
     * Add event listeners for each item.
     */
    addEventListeners() {
        this.items.forEach((item, index) => {
            const handlers = {
                click: () => this.selectItem(index),
                mouseenter: () => this.handleHover(index, true),
                mouseleave: () => this.handleHover(index, false),
                focus: () => this.handleFocus(index, true),
                blur: () => this.handleFocus(index, false),
            };
            Object.keys(handlers).forEach(event => {
                item.addEventListener(event, handlers[event]);
            });
            this.eventHandlers.set(item, handlers);
        });
    }
    /**
     * Remove all event listeners.
     */
    removeEventListeners() {
        this.eventHandlers.forEach((handlers, item) => {
            Object.keys(handlers).forEach(event => {
                item.removeEventListener(event, handlers[event]);
            });
        });
        this.eventHandlers.clear();
    }
    ensureSingleSelectedItem() {
        this.items.forEach((item, index) => {
            const isSelected = (item.getAttribute('selected') === 'true') || item.selected;
            if (isSelected) {
                if (this.activeIndex < 0) {
                    this.selectItem(index);
                }
                else {
                    item.removeAttribute('selected');
                    item.selected = false;
                }
            }
        });
    }
    /**
     * Handle hover events on an item.
     * @param index - Index of the item.
     * @param isActive - Whether the item is hovered.
     */
    handleHover(index, isActive) {
        this.hoverIndex = isActive ? index : -1;
        this.updateDividersOfItem(index);
    }
    /**
     * Handle hover events on an item.
     * @param index - Index of the item.
     * @param isActive - Whether the item is focused.
     */
    handleFocus(index, isActive) {
        this.focusIndex = isActive ? index : -1;
        this.updateDividersOfItem(index);
    }
    /**
     * Update visibility of dividers adjacent to a specific item.
     * @param itemIndex - Index of the item.
     */
    updateDividersOfItem(itemIndex) {
        if (itemIndex < this.items.length - 1) {
            this.updateDividerVisibility(itemIndex);
        }
        if (itemIndex > 0) {
            this.updateDividerVisibility(itemIndex - 1);
        }
    }
    /**
     * Update visibility of a specific divider.
     * @param dividerIndex - Index of the divider.
     */
    updateDividerVisibility(dividerIndex) {
        const hiddenDividers = new Set([this.activeIndex, this.activeIndex - 1, this.hoverIndex, this.hoverIndex - 1, this.focusIndex, this.focusIndex - 1]);
        this.setDividerVisibility(dividerIndex, hiddenDividers.has(dividerIndex));
    }
    /**
     * Set the visibility of a specific divider.
     * @param dividerIndex - Index of the divider.
     * @param hidden - Whether the divider should be hidden.
     */
    setDividerVisibility(dividerIndex, hidden) {
        if (this.dividers[dividerIndex]) {
            this.dividers[dividerIndex].classList.toggle('hidden', hidden);
        }
    }
    /**
     * Select a specific item.
     * @param itemIndex - Index of the item to be selected.
     */
    selectItem(itemIndex) {
        if (itemIndex === this.activeIndex)
            return;
        const oldIndex = this.activeIndex;
        if (oldIndex >= 0) {
            this.items[oldIndex].removeAttribute('selected');
        }
        this.activeIndex = itemIndex;
        this.items[itemIndex].setAttribute('selected', 'true');
        this.ifxChange.emit({ oldValue: this.getValueOfItem(oldIndex), newValue: this.getValueOfItem(itemIndex) });
        this.updateDividersOfItem(oldIndex);
        this.updateDividersOfItem(itemIndex);
    }
    /**
     * Get the value property of the item at a specific index.
     * Falls back to the index if no value is set.
     *
     * @param index - Index of the item.
     * @returns The value of the item.
     */
    getValueOfItem(index) {
        if (this.items[index] == null)
            return index.toLocaleString();
        return this.items[index].getAttribute('value') || index.toLocaleString();
    }
    render() {
        return (h(Host, { key: '6a0e5172af0ececbfbe29ba2c45c464bd228f6b4' }, h("div", { key: 'f17700d042f7b8eef9c07acf1c9fe81ee7283c5f', class: "ifx-content-switcher", role: "group" }, h("slot", { key: 'd1192fc9ca4a4ad57cf9fdc93d98d010d9956484' }))));
    }
    static get is() { return "ifx-content-switcher"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["./content-switcher.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["content-switcher.css"]
        };
    }
    static get states() {
        return {
            "items": {},
            "activeIndex": {},
            "hoverIndex": {},
            "focusIndex": {},
            "dividers": {}
        };
    }
    static get events() {
        return [{
                "method": "ifxChange",
                "name": "ifxChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "ChangeEvent",
                    "resolved": "{ oldValue: string; newValue: string; }",
                    "references": {
                        "ChangeEvent": {
                            "location": "local",
                            "path": "/home/runner/work/infineon-design-system-stencil/infineon-design-system-stencil/packages/components/src/components/content-switcher/content-switcher.tsx",
                            "id": "src/components/content-switcher/content-switcher.tsx::ChangeEvent"
                        }
                    }
                }
            }];
    }
    static get elementRef() { return "el"; }
}
//# sourceMappingURL=content-switcher.js.map
