import { h, } from "@stencil/core";
export class SidebarItem {
    el;
    /** Icon name or URL for the item */
    icon = "";
    /** Navigation link href for the item */
    href = "";
    internalHref = "";
    /** Link target (e.g., "_self", "_blank") */
    target = "_self";
    isExpandable = false;
    isNested = true;
    isSubMenuItem = false;
    /** Numeric badge indicator value */
    numberIndicator;
    /** Marks the item as active */
    active = false; // set to true manually or by clicking on a navigation item
    /** Marks as an action item */
    isActionItem = false; // if an item is an action item, it can not become active
    /** Click handler callback; receives the item HTMLElement */
    handleItemClick;
    showIcon = true;
    showIconWrapper = false;
    indicatorVariant = "number";
    internalActiveState = false;
    /** Event fired for menu item interactions */
    ifxSidebarMenu;
    /** Event fired when a navigation item is clicked */
    ifxSidebarNavigationItem;
    /** Event fired when an action item is clicked */
    ifxSidebarActionItem;
    titleText = "";
    handleActiveChange(newValue, oldValue) {
        // If the item is an action item, ignore the active prop
        if (this.isActionItem) {
            this.internalActiveState = false;
            return;
        }
        this.internalActiveState = newValue;
        if (newValue !== oldValue) {
            const labelElement = this.getNavItem(this.el.shadowRoot);
            if (!this.isExpandable && !newValue) {
                this.handleClassList(labelElement, "remove", "active");
            }
            if (!this.isExpandable && newValue) {
                this.handleClassList(labelElement, "add", "active");
            }
        }
    }
    handleNumberIndicatorChange() {
        this.updateIndicatorVariant();
    }
    handleConsoleError(event) {
        if (event.detail) {
            this.showIcon = false;
        }
        else {
            this.showIcon = true;
        }
    }
    handleEventEmission() {
        // Get the active item section
        this.ifxSidebarMenu.emit(this.el);
    }
    handleClassList(el, type, className) {
        el.classList[type](className);
        if (type === "contains") {
            return el.classList.contains(className);
        }
    }
    getExpandableMenu() {
        const expandableSubmenu = this.el.shadowRoot.querySelector(".expandable__submenu");
        return expandableSubmenu;
    }
    getNavItem(el) {
        return el?.querySelector(".sidebar__nav-item");
    }
    getSidebarMenuItems(el = this.el) {
        const sidebarItems = el.querySelectorAll("ifx-sidebar-item");
        if (sidebarItems.length === 0) {
            return el.shadowRoot.querySelectorAll("ifx-sidebar-item");
        }
        return sidebarItems;
    }
    getSidebarMenuItem() {
        const sidebarItem = this.el.shadowRoot.querySelector(".sidebar__nav-item");
        return sidebarItem;
    }
    toggleSubmenu() {
        if (this.isExpandable) {
            const menuItem = this.getSidebarMenuItem();
            const expandableMenu = this.getExpandableMenu();
            this.handleClassList(expandableMenu, "toggle", "open");
            this.handleClassList(menuItem, "toggle", "open");
            // Emit an event with the current component
            this.handleEventEmission();
        }
        else {
            // If the sidebar item is not expandable, it's a leaf item without a submenu.
            // Emit an event to the parent `ifx-sidebar` component to notify it that a leaf item has been clicked.
            if (this.isActionItem) {
                //its an action item that eg opens an overlay etc and should not influence the active state of the item
                this.ifxSidebarActionItem.emit(this.el); // emit new event if isActionItem is true
                return;
            }
            else {
                //its a navigation item which becomes active after clicking it
                this.handleActiveChange(true, this.internalActiveState);
                this.ifxSidebarNavigationItem.emit(this.el);
            }
            // If the sidebar item is selectable (not expandable), then call the handler function with the current element.
            if (this.handleItemClick) {
                this.handleItemClick(this.el);
            }
        }
        // // Emit an event with the current component
        // this.handleEventEmission();
    }
    handleExpandableMenu(sidebarItems) {
        const sidebarExpandableMenu = this.getExpandableMenu();
        sidebarItems.forEach((el) => {
            const li = document.createElement("li");
            li.appendChild(el);
            sidebarExpandableMenu.appendChild(li);
        });
    }
    parentElementIsSidebar() {
        const parentElement = this.el.parentElement;
        if (parentElement.tagName.toUpperCase() === "IFX-SIDEBAR") {
            return true;
        }
        else
            return false;
    }
    checkIfMenuItemIsNested() {
        const parentIsSidebar = this.parentElementIsSidebar();
        if (parentIsSidebar) {
            this.isNested = false;
        }
    }
    checkIfMenuItemIsSubMenu() {
        const parentElement = this.el.parentElement;
        const navItem = this.getNavItem(parentElement.shadowRoot);
        if (parentElement.tagName.toUpperCase() === "IFX-SIDEBAR-ITEM" &&
            !this.handleClassList(navItem, "contains", "header__section")) {
            this.isSubMenuItem = true;
        }
        else {
            this.isSubMenuItem = false;
        }
    }
    setHref() {
        if (this.href.toLowerCase().trim() === "") {
            this.internalHref = undefined;
        }
        else
            this.internalHref = this.href;
    }
    /** Add 'active' class to the current navigation item */
    async setActiveClasses() {
        const activeMenuItem = this.getNavItem(this.el.shadowRoot);
        this.handleClassList(activeMenuItem, "add", "active");
    }
    /** Expand submenu (adds 'open'); if ac=true, remove 'active-section' */
    async expandMenu(ac) {
        const menuItem = this.getSidebarMenuItem();
        const expandableMenu = this.getExpandableMenu();
        this.handleClassList(expandableMenu, "add", "open");
        this.handleClassList(menuItem, "add", "open");
        if (ac) {
            this.handleClassList(expandableMenu, "remove", "active-section");
            this.handleClassList(menuItem, "remove", "active-section");
        }
    }
    /** Return whether the item is expandable */
    async isItemExpandable() {
        return this.isExpandable;
    }
    handleActiveState() {
        if (this.internalActiveState) {
            this.setActiveClasses();
        }
    }
    handleKeyDown(event) {
        if (event.key === "Enter") {
            this.toggleSubmenu();
        }
    }
    componentDidLoad() {
        this.handleActiveState();
        if (this.isExpandable) {
            const sidebarItems = this.getSidebarMenuItems();
            this.handleExpandableMenu(sidebarItems);
        }
        // Listen for collapsed state changes
        this.updateIndicatorVariant();
        // Set up MutationObserver to watch for CSS custom property changes
        this.observeCollapsedState();
        // Extract text content for title attribute
        this.extractTitleText();
    }
    extractTitleText() {
        // Get the text content from the slot
        const slotElement = this.el.shadowRoot.querySelector("slot");
        if (slotElement) {
            const assignedNodes = slotElement.assignedNodes();
            this.titleText = assignedNodes
                .filter((node) => node.nodeType === Node.TEXT_NODE ||
                node.nodeType === Node.ELEMENT_NODE)
                .map((node) => node.textContent?.trim() || "")
                .join(" ")
                .trim();
        }
    }
    updateIndicatorVariant() {
        // Check the data attribute on this element
        const isCollapsed = this.el.hasAttribute("data-sidebar-collapsed");
        //this.indicatorVariant = isCollapsed ? 'dot' : 'number';
        if (this.numberIndicator > 0) {
            this.indicatorVariant = isCollapsed ? "dot" : "number";
        }
    }
    observeCollapsedState() {
        // Create a MutationObserver to watch for data-sidebar-collapsed attribute changes
        const observer = new MutationObserver(() => {
            this.updateIndicatorVariant();
        });
        observer.observe(this.el, {
            attributes: true,
            attributeFilter: ["data-sidebar-collapsed"],
        });
    }
    componentWillLoad() {
        this.internalActiveState = this.active;
        this.checkIfMenuItemIsNested();
        this.checkIfMenuItemIsSubMenu();
        this.setHref();
        // Set attribute to track if item has icon
        this.el.setAttribute("data-has-icon", this.icon ? "true" : "false");
        const sidebarItems = this.getSidebarMenuItems();
        if (sidebarItems.length !== 0) {
            this.isExpandable = true;
        }
        else {
            this.isExpandable = false;
        }
    }
    componentWillUpdate() {
        // If the active prop has been set to true and the internalActiveState has not been set to true yet
        if (this.active && !this.internalActiveState) {
            // Set the internal active state to true
            this.internalActiveState = this.active;
            // Emit the event to notify the parent Sidebar
            this.ifxSidebarNavigationItem.emit(this.el);
        }
    }
    render() {
        const isCollapsed = this.el.hasAttribute("data-sidebar-collapsed");
        const shouldHide = this.el.hasAttribute("data-hide-in-collapsed");
        return (h("div", { key: '9cd032209aa9c39b6c513f837f45866e5b1e1163', style: { display: shouldHide ? "none" : "block" } }, h("a", { key: '8a63de5c131731cf4d8a0c833a290d67afc03913', tabIndex: 1, onKeyDown: (event) => this.handleKeyDown(event), href: this.internalHref, onClick: () => this.toggleSubmenu(), target: this.target, class: `sidebar__nav-item ${!this.isNested && this.isExpandable ? "header__section" : ""} ${this.isSubMenuItem ? "submenu__item" : ""}`, title: this.titleText }, this.icon && (h("div", { key: '9f2f637c8f0d8e048f1c398fb649cfd2cc5454ca', class: `sidebar__nav-item-icon-wrapper ${!this.showIcon && !isCollapsed ? "noIcon" : ""}` }, h("ifx-icon", { key: 'ce4727e84b41d5e9e3ad12c91154fd2def54ca20', icon: this.icon }))), h("div", { key: 'ad1475cc4c620f738c251b41971ddecf48debd46', class: "sidebar__nav-item-label" }, h("slot", { key: 'd8095a3907dc47456abd49bd0ed66497d75d49a3' })), (this.isExpandable || !isNaN(this.numberIndicator)) && (h("div", { key: 'df08c1cc975b45d8f8162ac09b5a5818c993e608', class: "sidebar__nav-item-indicator", style: {
                display: !isCollapsed || this.icon ? "flex" : "none",
            } }, this.isExpandable && (h("span", { key: 'ee256687f309e1b21129a623471447394d71942b', class: "item__arrow-wrapper" }, h("ifx-icon", { key: 'c9369884d05c03d6328bf96a063ed4809b1b6eca', icon: "chevron-down-16" }))), this.numberIndicator > 0 &&
            !this.isExpandable &&
            !this.isNested && (h("span", { key: '1d1ba8c67fd16525137a70be2345fc3c54ce7d2d', class: "item__number-indicator" }, h("ifx-indicator", { key: '27191853f8825ea4fae8b7d517a714e5c189b2c4', variant: this.indicatorVariant, number: this.numberIndicator })))))), this.isExpandable && h("ul", { key: '28e939284d79af56270ec28b2269f190c0c2f05d', class: "expandable__submenu" })));
    }
    static get is() { return "ifx-sidebar-item"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["sidebar-item.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["sidebar-item.css"]
        };
    }
    static get properties() {
        return {
            "icon": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Icon name or URL for the item"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "icon",
                "defaultValue": "\"\""
            },
            "href": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Navigation link href for the item"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "href",
                "defaultValue": "\"\""
            },
            "target": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Link target (e.g., \"_self\", \"_blank\")"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "target",
                "defaultValue": "\"_self\""
            },
            "numberIndicator": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Numeric badge indicator value"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "number-indicator"
            },
            "active": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Marks the item as active"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "active",
                "defaultValue": "false"
            },
            "isActionItem": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Marks as an action item"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "is-action-item",
                "defaultValue": "false"
            },
            "handleItemClick": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "(item: HTMLElement) => void",
                    "resolved": "(item: HTMLElement) => void",
                    "references": {
                        "HTMLElement": {
                            "location": "global",
                            "id": "global::HTMLElement"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Click handler callback; receives the item HTMLElement"
                },
                "getter": false,
                "setter": false
            }
        };
    }
    static get states() {
        return {
            "internalHref": {},
            "isExpandable": {},
            "isNested": {},
            "isSubMenuItem": {},
            "showIcon": {},
            "showIconWrapper": {},
            "indicatorVariant": {},
            "internalActiveState": {}
        };
    }
    static get events() {
        return [{
                "method": "ifxSidebarMenu",
                "name": "ifxSidebarMenu",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired for menu item interactions"
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "ifxSidebarNavigationItem",
                "name": "ifxSidebarNavigationItem",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when a navigation item is clicked"
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "ifxSidebarActionItem",
                "name": "ifxSidebarActionItem",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when an action item is clicked"
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "setActiveClasses": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "Add 'active' class to the current navigation item",
                    "tags": []
                }
            },
            "expandMenu": {
                "complexType": {
                    "signature": "(ac: boolean) => Promise<void>",
                    "parameters": [{
                            "name": "ac",
                            "type": "boolean",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "Expand submenu (adds 'open'); if ac=true, remove 'active-section'",
                    "tags": []
                }
            },
            "isItemExpandable": {
                "complexType": {
                    "signature": "() => Promise<boolean>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<boolean>"
                },
                "docs": {
                    "text": "Return whether the item is expandable",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "active",
                "methodName": "handleActiveChange"
            }, {
                "propName": "numberIndicator",
                "methodName": "handleNumberIndicatorChange"
            }];
    }
    static get listeners() {
        return [{
                "name": "consoleError",
                "method": "handleConsoleError",
                "target": undefined,
                "capture": false,
                "passive": false
            }];
    }
}
