import { forceUpdate, h, Host, } from "@stencil/core";
import { DEVICE_SIZES, getCssProperty, getCurrentDeviceSize, getBrandForegroundAppearance, getNavItemParentDetails, } from "../../utils/helpers";
import chevronIcon from "../../assets/chevron-icon.svg";
import OpenInNew from "../../assets/OpenInNew.svg";
/**
 * @part link - The `<a>` within ic-navigation-item
 * @slot badge - Badge component overlaying the top right of the icon.
 * @slot icon - Content will be displayed to the left of the label for expanded navigation items, and in replacement of the label for collapsed navigation items.
 */
export class NavigationItem {
    constructor() {
        this.isInitialRender = true;
        this.hostMutationObserver = null;
        this.ANIMATION_DURATION = parseInt(getCssProperty("--ic-transition-duration-slow")) || 0;
        this.ARIA_LABEL_STRING = "aria-label";
        this.deviceSize = DEVICE_SIZES.XL;
        this.focusStyle = getBrandForegroundAppearance();
        this.inTopNavSideMenu = false;
        this.isSideNavMobile = false;
        this.isTopNavChild = false;
        this.sideNavExpanded = false;
        this.ariaLabel = "";
        /**
         * @internal If `true`, the icon and label will be displayed when side navigation is collapsed.
         */
        this.collapsedIconLabel = false;
        /**
         * @internal If `true`, the navigation item will be displayed within a tooltip.
         */
        this.displayNavigationTooltip = false;
        /**
         * If `true`, the user can save the linked URL instead of navigating to it.
         */
        this.download = false;
        /**
         *  @internal If `true`, the navigation item will be expandable.
         */
        this.expandable = false;
        /**
         * The destination of the navigation item.
         */
        this.href = "";
        /**
         *  If `true`, the navigation item will be set in a selected state.
         */
        this.selected = false;
        /**
         * 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";
        this.displayDefaultNavigationItem = (href, hreflang, target, rel, referrerpolicy, download, label) => {
            const variant = this.isTopNavChild || this.inTopNavSideMenu ? "body" : "label";
            const ChevronIconComponent = this.expandable && (h("div", { class: { svg: true }, innerHTML: chevronIcon }));
            const slottedBadgeEl = this.el.querySelector('[slot="badge"]');
            const BadgeComponent = slottedBadgeEl && (h("div", { class: slottedBadgeEl.getAttribute("position") === "inline" ||
                    this.inTopNavSideMenu
                    ? "inline-badge"
                    : "badge" }, h("slot", { name: "badge" })));
            const IconComponent = this.el.querySelector('[slot="icon"]') && (h("div", { class: "icon" }, h("slot", { name: "icon" }), this.navigationType === "side" && BadgeComponent));
            if (href !== "") {
                return (h("a", { href: href, target: target, rel: rel, hreflang: hreflang, referrerPolicy: referrerpolicy, download: download !== false ? download : null, class: "link", ref: (el) => (this.itemEl = el), part: "link", "aria-label": this.ariaLabel ? this.ariaLabel : null }, IconComponent, h("ic-typography", { variant: variant }, label), target === "_blank" && (h("span", { class: "open-in-new-icon", innerHTML: OpenInNew })), BadgeComponent, h("div", { class: "chevron-container" }, ChevronIconComponent)));
            }
            return (h("div", { tabindex: "0", class: "link", ref: (el) => (this.itemEl = el) }, IconComponent, h("ic-typography", { variant: variant }, label), ChevronIconComponent, BadgeComponent));
        };
        this.topNavResizedHandler = ({ detail, }) => {
            var _a;
            const { size } = detail;
            if (size !== this.deviceSize) {
                this.deviceSize = size;
                this.inTopNavSideMenu =
                    size <=
                        (((_a = this.parentEl) === null || _a === void 0 ? void 0 : _a.customMobileBreakpoint) || DEVICE_SIZES.L);
            }
        };
        this.sideNavExpandHandler = ({ detail, }) => {
            const { sideNavExpanded, sideNavMobile } = detail;
            this.sideNavExpanded = sideNavExpanded;
            this.isSideNavMobile = sideNavMobile;
            this.sideNavToggleTooltip(!(sideNavExpanded || sideNavMobile));
        };
        this.handleBlur = ({ relatedTarget }) => {
            if (relatedTarget === null ||
                relatedTarget.tagName !== "IC-NAVIGATION-ITEM") {
                this.childBlur.emit();
            }
        };
        this.handleClick = () => {
            this.navItemClicked.emit();
        };
        // triggered when attributes of host element change
        this.hostMutationCallback = (mutationList) => {
            let forceComponentUpdate = false;
            mutationList.forEach(({ attributeName }) => {
                if (attributeName) {
                    const attribute = this.el.getAttribute(attributeName);
                    if (attribute && attributeName === this.ARIA_LABEL_STRING) {
                        this.ariaLabel = attribute;
                        forceComponentUpdate = true;
                    }
                }
            });
            if (forceComponentUpdate) {
                forceUpdate(this);
            }
        };
        this.generateTooltipLabel = () => {
            if (this.label) {
                return this.label;
            }
            if (this.navigationSlot) {
                return this.navigationSlot.textContent;
            }
            if (this.el.children[0]) {
                return this.el.children[0].textContent;
            }
            return "";
        };
        this.renderNavigationItemContent = () => {
            if (this.label) {
                return this.displayDefaultNavigationItem(this.href, this.hreflang, this.target, this.rel, this.referrerpolicy, this.download, this.label);
            }
            if (this.navigationSlot) {
                return h("slot", { name: "navigation-item" });
            }
            return h("slot", null);
        };
        // Displays tooltip only once the collapsing animation is finished
        this.sideNavToggleTooltip = (showTooltip) => {
            var _a;
            const tooltip = (_a = this.el.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector("ic-tooltip");
            const collapsedClass = "tooltip-navigation-item-side-nav-collapsed";
            let timer;
            if (tooltip) {
                if (showTooltip) {
                    tooltip.displayTooltip(false); // Hides tooltip for when mouse is hovering over icon
                    timer = setTimeout(() => {
                        tooltip.classList.add(collapsedClass);
                    }, this.ANIMATION_DURATION);
                }
                else {
                    clearTimeout(timer);
                    tooltip.classList.remove(collapsedClass);
                }
            }
        };
    }
    disconnectedCallback() {
        var _a, _b, _c;
        if (this.navigationType === "side") {
            (_a = this.parentEl) === null || _a === void 0 ? void 0 : _a.removeEventListener("icSideNavExpanded", this.sideNavExpandHandler);
        }
        else if (this.navigationType === "top") {
            (_b = this.parentEl) === null || _b === void 0 ? void 0 : _b.removeEventListener("icTopNavResized", this.topNavResizedHandler);
        }
        (_c = this.hostMutationObserver) === null || _c === void 0 ? void 0 : _c.disconnect();
    }
    componentWillLoad() {
        var _a, _b, _c, _d, _e, _f;
        const { navType, parent } = getNavItemParentDetails(this.el);
        this.navigationType = navType;
        this.parentEl = parent;
        this.deviceSize = getCurrentDeviceSize();
        this.sideNavExpanded =
            ((_a = this.parentEl) === null || _a === void 0 ? void 0 : _a.classList.contains("sm-expanded")) ||
                ((_b = this.parentEl) === null || _b === void 0 ? void 0 : _b.classList.contains("xs-menu-open")) ||
                false;
        if (this.navigationType === "side") {
            (_c = this.parentEl) === null || _c === void 0 ? void 0 : _c.addEventListener("icSideNavExpanded", this.sideNavExpandHandler);
        }
        else if (this.navigationType === "top") {
            (_d = this.parentEl) === null || _d === void 0 ? void 0 : _d.addEventListener("icTopNavResized", this.topNavResizedHandler);
            if (((_e = this.el.parentElement) === null || _e === void 0 ? void 0 : _e.tagName) === "IC-NAVIGATION-GROUP")
                this.isTopNavChild = true;
            if (this.deviceSize <=
                this.parentEl.customMobileBreakpoint)
                this.inTopNavSideMenu = true;
        }
        this.navigationSlot = this.el.querySelector('[slot="navigation-item"]');
        if (this.navigationSlot) {
            this.navigationSlot.ariaLabel =
                ((_f = this.navigationSlot.textContent) === null || _f === void 0 ? void 0 : _f.trim()) || null;
        }
        if (this.el.hasAttribute(this.ARIA_LABEL_STRING)) {
            this.ariaLabel = this.el.getAttribute(this.ARIA_LABEL_STRING) || "";
        }
    }
    componentDidLoad() {
        this.hostMutationObserver = new MutationObserver(this.hostMutationCallback);
        this.hostMutationObserver.observe(this.el, {
            attributes: true,
        });
    }
    componentDidUpdate() {
        this.isInitialRender = false;
    }
    brandChangeHandler({ detail }) {
        this.focusStyle = detail.mode;
    }
    /**
     * Sets focus on the nav item.
     */
    async setFocus() {
        var _a;
        this.itemEl ? this.itemEl.focus() : (_a = this.el.querySelector("a")) === null || _a === void 0 ? void 0 : _a.focus();
    }
    render() {
        const { inTopNavSideMenu, isTopNavChild, selected } = this;
        return (h(Host, { key: 'f20ee76495a75e8794e451e27b92f5545d06212c', class: {
                ["navigation-item"]: true,
                ["navigation-item-top-nav"]: !inTopNavSideMenu && this.navigationType === "top",
                ["navigation-item-top-nav-child-selected"]: isTopNavChild && !inTopNavSideMenu && !!selected,
                [this.focusStyle]: (!inTopNavSideMenu && !isTopNavChild) ||
                    (this.navigationType === "side" && isTopNavChild),
                ["navigation-item-selected"]: !isTopNavChild && !!selected,
                ["navigation-item-side-menu"]: inTopNavSideMenu,
                ["navigation-item-side-menu-selected"]: inTopNavSideMenu && !!selected,
                ["navigation-item-top-nav-child"]: isTopNavChild && !inTopNavSideMenu,
                ["navigation-item-page-header"]: this.navigationType === "page-header",
                ["with-transition"]: !this.isInitialRender,
                ["navigation-item-side-nav"]: this.navigationType === "side",
                ["navigation-item-side-nav-collapsed"]: (!this.sideNavExpanded || !!this.displayNavigationTooltip) &&
                    this.navigationType === "side",
                ["navigation-item-side-nav-collapsed-with-label"]: !this.sideNavExpanded &&
                    this.navigationType === "side" &&
                    !!this.collapsedIconLabel &&
                    !this.isSideNavMobile,
                ["expandable"]: !!this.expandable,
                [`ic-theme-${this.theme}`]: this.theme !== "inherit",
            }, onBlur: isTopNavChild && !inTopNavSideMenu ? this.handleBlur : null, onClick: this.handleClick, "aria-current": selected ? "page" : null, role: "listitem" }, h("ic-tooltip", { key: '6b1e5e2b20aa01cfea5dde82a27e93bf1c19cd3a', label: this.generateTooltipLabel() || "", target: "navigation-item", placement: "right", class: {
                ["tooltip-navigation-item"]: true,
                ["tooltip-navigation-item-side-nav-collapsed"]: !!this.displayNavigationTooltip && this.navigationType === "side",
                ["tooltip-long-label-navigation-item-side-nav-expanded"]: this.el.hasAttribute("[display-navigation-tooltip = 'true']"),
            } }, this.renderNavigationItemContent())));
    }
    static get is() { return "ic-navigation-item"; }
    static get encapsulation() { return "shadow"; }
    static get delegatesFocus() { return true; }
    static get originalStyleUrls() {
        return {
            "$": ["ic-navigation-item.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["ic-navigation-item.css"]
        };
    }
    static get properties() {
        return {
            "collapsedIconLabel": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean | undefined",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [{
                            "name": "internal",
                            "text": "If `true`, the icon and label will be displayed when side navigation is collapsed."
                        }],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "attribute": "collapsed-icon-label",
                "reflect": false,
                "defaultValue": "false"
            },
            "displayNavigationTooltip": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean | undefined",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [{
                            "name": "internal",
                            "text": "If `true`, the navigation item will be displayed within a tooltip."
                        }],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "attribute": "display-navigation-tooltip",
                "reflect": false,
                "defaultValue": "false"
            },
            "download": {
                "type": "any",
                "mutable": false,
                "complexType": {
                    "original": "string | boolean",
                    "resolved": "boolean | string | undefined",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "If `true`, the user can save the linked URL instead of navigating to it."
                },
                "getter": false,
                "setter": false,
                "attribute": "download",
                "reflect": false,
                "defaultValue": "false"
            },
            "expandable": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean | undefined",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [{
                            "name": "internal",
                            "text": "If `true`, the navigation item will be expandable."
                        }],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "attribute": "expandable",
                "reflect": false,
                "defaultValue": "false"
            },
            "href": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string | undefined",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "The destination of the navigation item."
                },
                "getter": false,
                "setter": false,
                "attribute": "href",
                "reflect": false,
                "defaultValue": "\"\""
            },
            "hreflang": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string | undefined",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "The human language of the linked URL."
                },
                "getter": false,
                "setter": false,
                "attribute": "hreflang",
                "reflect": false
            },
            "label": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string | undefined",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "The label of the navigation item."
                },
                "getter": false,
                "setter": false,
                "attribute": "label",
                "reflect": false
            },
            "rel": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string | undefined",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "The relationship of the linked URL as space-separated link types."
                },
                "getter": false,
                "setter": false,
                "attribute": "rel",
                "reflect": false
            },
            "referrerpolicy": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "ReferrerPolicy",
                    "resolved": "\"\" | \"no-referrer\" | \"no-referrer-when-downgrade\" | \"origin\" | \"origin-when-cross-origin\" | \"same-origin\" | \"strict-origin\" | \"strict-origin-when-cross-origin\" | \"unsafe-url\" | undefined",
                    "references": {
                        "ReferrerPolicy": {
                            "location": "global",
                            "id": "global::ReferrerPolicy"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "How much of the referrer to send when following the link."
                },
                "getter": false,
                "setter": false,
                "attribute": "referrerpolicy",
                "reflect": false
            },
            "selected": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean | undefined",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "If `true`, the navigation item will be set in a selected state."
                },
                "getter": false,
                "setter": false,
                "attribute": "selected",
                "reflect": false,
                "defaultValue": "false"
            },
            "target": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string | undefined",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "The place to display the linked URL, as the name for a browsing context (a tab, window, or iframe)."
                },
                "getter": false,
                "setter": false,
                "attribute": "target",
                "reflect": false
            },
            "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\""
            }
        };
    }
    static get states() {
        return {
            "deviceSize": {},
            "focusStyle": {},
            "inTopNavSideMenu": {},
            "isSideNavMobile": {},
            "isTopNavChild": {},
            "navigationType": {},
            "parentEl": {},
            "sideNavExpanded": {},
            "ariaLabel": {}
        };
    }
    static get events() {
        return [{
                "method": "childBlur",
                "name": "childBlur",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [{
                            "name": "internal",
                            "text": "- Emitted when item loses focus."
                        }],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }, {
                "method": "navItemClicked",
                "name": "navItemClicked",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [{
                            "name": "internal",
                            "text": "- Emitted when navigation item clicked."
                        }],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "setFocus": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "Sets focus on the nav item.",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "el"; }
    static get listeners() {
        return [{
                "name": "brandChange",
                "method": "brandChangeHandler",
                "target": "document",
                "capture": false,
                "passive": false
            }];
    }
}
//# sourceMappingURL=ic-navigation-item.js.map
