/* eslint-disable no-inner-declarations */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { h } from "@stencil/core";
import { randomIdGenerator } from "../../../global/utils/randomIdGenerator";
import { logger } from "../../../global/utils/logger";
import { NavigationVerticalMenuVariation } from "./navigation-vertical-menu-variation.enum";
import { NavigationVerticalMenuActiveIndicatorSize } from "./navigation-vertical-menu-active-indicator-size.enum";
/**
 * @slot default - Måste innehålla en eller flera digi-navigation-vertical-menu-item
 *
 * @enums NavigationVerticalMenuVariation - navigation-vertical-menu-variation.enum.ts
 * @enums NavigationVerticalMenuActiveIndicatorSize = navigation-vertical-menu-active-indicator-size.enum.ts
 *@swedishName Vertikal meny
 */
export class NavigationVerticalMenu {
    constructor() {
        this.listItems = [];
        this.afId = randomIdGenerator('digi-navigation-vertical-menu');
        this.afVariation = NavigationVerticalMenuVariation.PRIMARY;
        this.afActiveIndicatorSize = NavigationVerticalMenuActiveIndicatorSize.PRIMARY;
        this.afAriaLabel = undefined;
    }
    linkClickHandler(e) {
        this.setCurrentActiveLevel(e.target);
        this.setClasses(e.target);
    }
    setClasses(el) {
        const activeDeepClass = 'digi-navigation-vertical-menu__item--deep-active';
        const activeClass = 'digi-navigation-vertical-menu__item--active';
        const navList = this.hostElement.querySelector('.digi-navigation-vertical-menu__list');
        const activeNavItems = Array.from(navList.children).filter((item) => item.classList.contains(activeClass));
        activeNavItems.forEach((listItem) => {
            listItem.classList.add(activeDeepClass);
            setClassRecursive(listItem);
        });
        function setClassRecursive(listItem) {
            const arr = Array.from(listItem.children).filter((item) => item.tagName === 'UL');
            const list = arr[0];
            const activeListItems = Array.from(list.children).filter((item) => item.classList.contains(activeClass));
            if (activeListItems.length == 0) {
                removeClassRecursive(list);
                return;
            }
            activeListItems.forEach((item) => {
                item.classList.add(activeDeepClass);
                setClassRecursive(item);
            });
        }
        function removeClassRecursive(item, deepElement = true) {
            const parentEl = item.closest('li');
            if (!parentEl) {
                return;
            }
            if (!deepElement) {
                parentEl.classList.remove(activeDeepClass);
            }
            const deepParent = parentEl.closest('ul');
            if (!deepParent) {
                return;
            }
            removeClassRecursive(deepParent, false);
        }
        const removeUnselected = this.hostElement.querySelectorAll(`.${activeDeepClass}:not(.${activeClass})`);
        removeUnselected.forEach((item) => {
            item.classList.remove(activeDeepClass);
        });
        if (!el.matches('.digi-navigation-vertical-menu-item--has-subnav')) {
            removeClassRecursive(el);
        }
    }
    componentWillLoad() {
        this.getListItems();
        this.initNav();
        this.setLevelClass();
    }
    componentDidLoad() {
        this.initCurrentActiveLevel();
        this.afOnReady.emit();
    }
    componentWillUpdate() {
        this.getListItems();
        this.initNav();
        this.setLevelClass();
    }
    initCurrentActiveLevel() {
        let elActiveSubnav = this.hostElement.querySelector('digi-navigation-vertical-menu-item[af-active-subnav="true"]');
        if (elActiveSubnav) {
            const getDeep = (elActiveSubnav) => {
                const deepEl = elActiveSubnav
                    .closest('li')
                    .querySelector('ul')
                    .querySelector('digi-navigation-vertical-menu-item[af-active-subnav="true"]');
                return deepEl ? deepEl : null;
            };
            const checkRecursive = (deepEl) => {
                const elToCheck = getDeep(deepEl);
                if (elToCheck) {
                    elActiveSubnav = elToCheck;
                    checkRecursive(elToCheck);
                }
                else {
                    elActiveSubnav = deepEl;
                }
            };
            checkRecursive(elActiveSubnav);
            this.setCurrentActiveLevel(elActiveSubnav);
        }
    }
    setCurrentActiveLevel(targetElement) {
        const currentLevelClass = 'digi-navigation-vertical-menu__item--current-level';
        const target = targetElement;
        const oldTarget = this.hostElement.querySelectorAll('.digi-navigation-vertical-menu__item--current-level');
        oldTarget.forEach((el) => {
            el.classList.remove(currentLevelClass);
        });
        let subnav = target.closest('li').querySelector('ul');
        if (target.matches('.digi-navigation-vertical-menu-item--has-subnav')) {
            subnav = target.closest('ul');
            subnav.classList.add(currentLevelClass);
            return;
        }
        if (subnav) {
            subnav.classList.add(currentLevelClass);
        }
        else {
            subnav = target.closest('ul');
            subnav.classList.add(currentLevelClass);
        }
    }
    setLevelClass() {
        this.hostElement
            .querySelector('ul')
            .classList.remove('primary', 'secondary');
        this.hostElement
            .querySelector('ul')
            .classList.add('digi-navigation-vertical-menu__list--root', this.afVariation);
    }
    initNav() {
        const $ul = this.hostElement.querySelectorAll('ul');
        const $li = this.hostElement.querySelectorAll('li');
        $ul.forEach((item) => item.classList.add('digi-navigation-vertical-menu__list'));
        $li.forEach((item) => item.classList.add('digi-navigation-vertical-menu__item'));
    }
    async afMSetCurrentActiveLevel(e) {
        this.setCurrentActiveLevel(e);
        this.initNav();
        this.setClasses(e);
    }
    getListItems() {
        const menuItems = this.hostElement.children;
        if (!menuItems || menuItems.length <= 0) {
            logger.warn(`The slot contains no children elements.`, this.hostElement);
            return;
        }
        this.listItems = [...Array.from(menuItems)].map((filter) => {
            return {
                outerHTML: filter.outerHTML
            };
        });
    }
    get cssModifiers() {
        return {
            'digi-navigation-vertical-menu': false,
            'digi-navigation-vertical-menu--primary': this.afVariation === NavigationVerticalMenuVariation.PRIMARY,
            'digi-navigation-vertical-menu--secondary': this.afVariation === NavigationVerticalMenuVariation.SECONDARY,
            'digi-navigation-vertical-menu--indicator--secondary': this.afActiveIndicatorSize ===
                NavigationVerticalMenuActiveIndicatorSize.SECONDARY
        };
    }
    render() {
        return (h("nav", { key: '6bfe043a155fec7ca12b329f26f9fe3d88a1ce90', class: Object.assign({ 'digi-navigation-vertical-menu': true }, this.cssModifiers), id: this.afId, "aria-label": this.afAriaLabel }, h("slot", { key: '280aa0dc9656afccd0890d278ed2ade21cd927a0' })));
    }
    static get is() { return "digi-navigation-vertical-menu"; }
    static get encapsulation() { return "scoped"; }
    static get originalStyleUrls() {
        return {
            "$": ["navigation-vertical-menu.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["navigation-vertical-menu.css"]
        };
    }
    static get properties() {
        return {
            "afId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set id attribute. Defaults to random string."
                        }],
                    "text": "S\u00E4tter attributet 'id'. Om inget v\u00E4ljs s\u00E5 skapas ett slumpm\u00E4ssigt id."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-id",
                "reflect": false,
                "defaultValue": "randomIdGenerator('digi-navigation-vertical-menu')"
            },
            "afVariation": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "NavigationVerticalMenuVariation",
                    "resolved": "NavigationVerticalMenuVariation.PRIMARY | NavigationVerticalMenuVariation.SECONDARY",
                    "references": {
                        "NavigationVerticalMenuVariation": {
                            "location": "import",
                            "path": "./navigation-vertical-menu-variation.enum",
                            "id": "src/components/_navigation/navigation-vertical-menu/navigation-vertical-menu-variation.enum.ts::NavigationVerticalMenuVariation"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set variation of vertical menu. Can be 'primary' or 'secondary'."
                        }, {
                            "name": "ignore",
                            "text": undefined
                        }],
                    "text": "S\u00E4tter variant. Kan vara 'primary' eller 'secondary'."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-variation",
                "reflect": false,
                "defaultValue": "NavigationVerticalMenuVariation.PRIMARY"
            },
            "afActiveIndicatorSize": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "NavigationVerticalMenuActiveIndicatorSize",
                    "resolved": "NavigationVerticalMenuActiveIndicatorSize.PRIMARY | NavigationVerticalMenuActiveIndicatorSize.SECONDARY",
                    "references": {
                        "NavigationVerticalMenuActiveIndicatorSize": {
                            "location": "import",
                            "path": "./navigation-vertical-menu-active-indicator-size.enum",
                            "id": "src/components/_navigation/navigation-vertical-menu/navigation-vertical-menu-active-indicator-size.enum.ts::NavigationVerticalMenuActiveIndicatorSize"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set variation of vertical menu. Can be 'primary' or 'secondary'."
                        }],
                    "text": "S\u00E4tter variant. Kan vara 'primary' eller 'secondary'."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-active-indicator-size",
                "reflect": false,
                "defaultValue": "NavigationVerticalMenuActiveIndicatorSize.PRIMARY"
            },
            "afAriaLabel": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set button `aria-label` attribute."
                        }],
                    "text": "S\u00E4tt attributet 'aria-label'."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-aria-label",
                "reflect": false
            }
        };
    }
    static get states() {
        return {
            "listItems": {}
        };
    }
    static get events() {
        return [{
                "method": "afOnReady",
                "name": "afOnReady",
                "bubbles": false,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "When the component and slots are loaded and initialized this event will trigger."
                        }],
                    "text": "N\u00E4r komponenten och slotsen \u00E4r laddade och initierade s\u00E5 skickas detta eventet."
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "afMSetCurrentActiveLevel": {
                "complexType": {
                    "signature": "(e: any) => Promise<void>",
                    "parameters": [{
                            "name": "e",
                            "type": "any",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "hostElement"; }
    static get listeners() {
        return [{
                "name": "afOnClick",
                "method": "linkClickHandler",
                "target": undefined,
                "capture": false,
                "passive": false
            }];
    }
}
