import { h } from "@stencil/core";
import { HeaderCenterContentWidth, UtilBreakpointObserverBreakpoints } from "../../../enums";
/**
 *
 *
 * @swedishName Sidhuvud-meny
 */
export class HeaderNavigation {
    constructor() {
        this._focusableElementsSelectors = 'a, input, select, textarea, button, button:not(hidden), iframe, object, [tabindex="0"]';
        this.focusableElements = [];
        this.isMobile = undefined;
        this.isVisible = undefined;
        this.afCloseButtonText = undefined;
        this.afNavAriaLabel = undefined;
        this.afCloseButtonAriaLabel = undefined;
        this.afFocusableElement = undefined;
        this.afCloseFocusableElement = undefined;
        this.afActive = false;
        this.afBackdrop = true;
        this.afCentered = HeaderCenterContentWidth.DEFAULT;
    }
    //private _observer: any;
    enablePageScroll() {
        document.body.style.height = '';
        document.body.style.overflowY = '';
        document.body.style.paddingRight = '';
    }
    disablePageScroll() {
        document.body.style.height = '100vh';
        document.body.style.overflowY = 'hidden';
    }
    toggleHandler(e) {
        const element = e.target;
        this._closeFocusableElement = element.querySelector('.digi-navigation-sidebar-button button');
        if (element.matches('digi-navigation-sidebar-button')) {
            this.afActive = true;
        }
    }
    get shouldUseFocusTrap() {
        return this.isMobile && this.focusableElements.length > 0;
    }
    closeHandler(e) {
        this.afActive = false;
        this.afOnClose.emit(e);
    }
    escHandler(e) {
        if (this.isMobile) {
            this.afActive = false;
            this.afOnClose.emit(e);
        }
    }
    tabHandler(e) {
        if (this.shouldUseFocusTrap) {
            if (document.activeElement === this.lastFocusableEl) {
                e.detail.preventDefault();
                this.firstFocusableEl.focus();
            }
        }
    }
    backdropClickHandler(e) {
        this.afActive = false;
        this.afOnClose.emit(e);
    }
    shiftHandler(e) {
        if (this.shouldUseFocusTrap) {
            if (document.activeElement === this.firstFocusableEl) {
                e.detail.preventDefault();
                this.lastFocusableEl.focus();
            }
        }
    }
    clickHandler(e) {
        // If clicking on toggle button, refresh the focusable items list
        // with the new sub level of items
        if (this.shouldUseFocusTrap) {
            const el = e.detail.target;
            if (el.tagName.toLowerCase() === 'button') {
                setTimeout(() => {
                    this.getFocusableItems();
                }, 100);
            }
        }
    }
    setMobileView(isMobile) {
        isMobile && this.afActive
            ? (this.disablePageScroll(), this.getFocusableItems())
            : this.enablePageScroll();
    }
    breakpointChange(e) {
        this.isVisible = false;
        const element = e.target;
        const type = element.nodeName;
        if (type.toLowerCase() === 'digi-util-breakpoint-observer') {
            this.isMobile =
                e.detail.value === UtilBreakpointObserverBreakpoints.SMALL;
        }
        if (this.isMobile) {
            setTimeout(() => {
                this.isVisible = true;
            }, 100);
        }
        else {
            this.isVisible = true;
        }
    }
    componentDidLoad() {
        const transition = this._wrapper;
        transition.addEventListener('transitionend', () => {
            this.getFocusableItems();
            this.setFocus();
        });
    }
    getFocusableItems() {
        const allElements = this._wrapper.querySelectorAll(this._focusableElementsSelectors);
        // Filters out visible items
        this.focusableElements = Array.prototype.slice
            .call(allElements)
            .filter(function (item) {
            return item.offsetParent !== null;
        });
        // Sets first and last focusable element
        if (this.focusableElements.length > 0) {
            this.firstFocusableEl = this.focusableElements[0];
            this.lastFocusableEl = this.focusableElements[this.focusableElements.length - 1];
        }
    }
    setFocus() {
        if (this.afActive) {
            let el;
            const firstNavLink = this.firstFocusableEl;
            if (this.afFocusableElement) {
                el = this.hostElement.querySelector(`${this.afFocusableElement}`);
            }
            else {
                el = firstNavLink;
            }
            if (el) {
                el.focus();
            }
        }
        else {
            if (this.afCloseFocusableElement) {
                const el = document.querySelector(`${this.afCloseFocusableElement}`);
                el.focus();
            }
            else if (this._closeFocusableElement) {
                const el = this._closeFocusableElement;
                el.focus();
            }
        }
    }
    get cssModifiers() {
        return {
            'digi-header-navigation--open': this.afActive,
            'digi-header-navigation--mobile': this.isMobile,
            'digi-header-navigation--visible': this.isVisible,
            'digi-header-navigation--centered': this.afCentered !== HeaderCenterContentWidth.DEFAULT
        };
    }
    render() {
        return (h("div", { key: '121c72d40552f28dba749b4396316766478f0b09', class: Object.assign({ 'digi-header-navigation': true }, this.cssModifiers) }, h("digi-util-breakpoint-observer", { key: 'f88dddc98531eaa9ee02d845f84ae87072291038', onAfOnChange: (e) => (this.isMobile =
                e.detail.value === UtilBreakpointObserverBreakpoints.SMALL) }, h("digi-util-keydown-handler", { key: '0cf7888905c1445d901b56453c6097bc65f1fa99', onAfOnEsc: (e) => this.escHandler(e), onAfOnTab: (e) => this.tabHandler(e), onAfOnShiftTab: (e) => this.shiftHandler(e) }, h("div", { key: 'ea6f5eb7d720d56b50b619379c341f0926c07876' }, this.isMobile && (h("div", { key: 'cdf39a5c739732a39bf05b4f29da58e0895de974', class: "digi-header-navigation__backdrop", onClick: (e) => this.backdropClickHandler(e) })), h("nav", { key: 'bc1d7c45ea0f6565f82f4ec8c9a22c76c10b1ed1', class: "digi-header-navigation__wrapper", "aria-label": this.afNavAriaLabel, "af-centered": this.afCentered, ref: (el) => {
                this._wrapper = el;
            } }, this.isMobile && (h("digi-button", { key: '838ad3369efd0f09fc42236ac361c8f71eddd22a', onClick: (e) => this.closeHandler(e), "af-variation": "function", "af-aria-label": this.afCloseButtonAriaLabel, class: "digi-header-navigation__close-button" }, this.afCloseButtonText, h("digi-icon-x", { key: '1053d972fbac618f9c0a5dac8362f982a331b132', slot: "icon-secondary" }))), this.afCentered !== HeaderCenterContentWidth.DEFAULT ? (h("digi-layout-container", { "af-max-width": this.afCentered }, h("div", { role: "list", class: "digi-header-navigation__inner" }, h("slot", null)))) : (h("div", { role: "list", class: "digi-header-navigation__inner" }, h("slot", null)))))))));
    }
    static get is() { return "digi-header-navigation"; }
    static get encapsulation() { return "scoped"; }
    static get originalStyleUrls() {
        return {
            "$": ["header-navigation.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["header-navigation.css"]
        };
    }
    static get properties() {
        return {
            "afCloseButtonText": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "The close buttons text"
                        }],
                    "text": "St\u00E4ng-knappens text"
                },
                "getter": false,
                "setter": false,
                "attribute": "af-close-button-text",
                "reflect": false
            },
            "afNavAriaLabel": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set `aria-label` attribute."
                        }],
                    "text": "S\u00E4tter attributet 'aria-label'."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-nav-aria-label",
                "reflect": false
            },
            "afCloseButtonAriaLabel": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set button `aria-label` attribute to the close button"
                        }],
                    "text": "S\u00E4tt attributet 'aria-label' p\u00E5 st\u00E4ng-knappen"
                },
                "getter": false,
                "setter": false,
                "attribute": "af-close-button-aria-label",
                "reflect": false
            },
            "afFocusableElement": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Element that is focused when menu is opened,\ndefaults to title or close button"
                        }],
                    "text": "Element som ska f\u00E5 fokus n\u00E4r menyn \u00F6ppnas. S\u00E4tts ingen\ns\u00E5 f\u00E5r rubriken eller st\u00E4ng-knappen fokus"
                },
                "getter": false,
                "setter": false,
                "attribute": "af-focusable-element",
                "reflect": false
            },
            "afCloseFocusableElement": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Element that is focused when menu is closed,\ndefaults to toggle button that opened the sidebar"
                        }],
                    "text": "Element som ska f\u00E5 fokus n\u00E4r menyn st\u00E4ngs.\nS\u00E4tts ingen s\u00E5 f\u00E5r knappen som \u00F6ppnade menyn fokus"
                },
                "getter": false,
                "setter": false,
                "attribute": "af-close-focusable-element",
                "reflect": false
            },
            "afActive": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Shows or hides the sidebar in mobile. If set to true it will be open by default."
                        }],
                    "text": "Visar eller d\u00F6ljer sidmenyn i mobill\u00E4ge. Om satt till true s\u00E5 \u00E4r den \u00F6ppen per standard."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-active",
                "reflect": false,
                "defaultValue": "false"
            },
            "afBackdrop": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Applies a unscrollable backdrop over the page content when the sidebar is active"
                        }],
                    "text": "L\u00E4gger en skugga bakom menyn som t\u00E4cker sidinneh\u00E5llet n\u00E4r menyn \u00E4r aktiv"
                },
                "getter": false,
                "setter": false,
                "attribute": "af-backdrop",
                "reflect": false,
                "defaultValue": "true"
            },
            "afCentered": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "HeaderCenterContentWidth",
                    "resolved": "HeaderCenterContentWidth.DEFAULT | HeaderCenterContentWidth.WIDTH_1200 | HeaderCenterContentWidth.WIDTH_1400",
                    "references": {
                        "HeaderCenterContentWidth": {
                            "location": "import",
                            "path": "../../../enums",
                            "id": "src/enums.ts::HeaderCenterContentWidth"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Applies a container around the menu's content, but allows the background to maintain full width. Width aligns with digi-layout-container."
                        }],
                    "text": "L\u00E4gger en container runt menyns inneh\u00E5ll, men l\u00E5ter bakgrunden beh\u00E5lla full bredd. Bredden linjerar med digi-layout-container."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-centered",
                "reflect": false,
                "defaultValue": "HeaderCenterContentWidth.DEFAULT"
            }
        };
    }
    static get states() {
        return {
            "isMobile": {},
            "isVisible": {}
        };
    }
    static get events() {
        return [{
                "method": "afOnClose",
                "name": "afOnClose",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Close button's 'onclick' event"
                        }],
                    "text": "St\u00E4ngknappens 'onclick'-event"
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "afOnEsc",
                "name": "afOnEsc",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "At close/open of sidebar using esc-key"
                        }],
                    "text": "St\u00E4ngning av sidof\u00E4lt med esc-tangenten"
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "afOnBackdropClick",
                "name": "afOnBackdropClick",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "At close of sidebar when clicking on backdrop"
                        }],
                    "text": "St\u00E4ngning av sidof\u00E4lt med klick p\u00E5 skuggan bakom menyn"
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "afOnToggle",
                "name": "afOnToggle",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "At close/open of sidebar"
                        }],
                    "text": "Vid \u00F6ppning/st\u00E4ngning av sidof\u00E4lt"
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
    static get elementRef() { return "hostElement"; }
    static get watchers() {
        return [{
                "propName": "isMobile",
                "methodName": "setMobileView"
            }];
    }
    static get listeners() {
        return [{
                "name": "afOnToggle",
                "method": "toggleHandler",
                "target": "window",
                "capture": false,
                "passive": false
            }, {
                "name": "afOnClick",
                "method": "clickHandler",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "afOnChange",
                "method": "breakpointChange",
                "target": undefined,
                "capture": false,
                "passive": false
            }];
    }
}
