import { Host, h } from "@stencil/core";
export class SpwHeaderNavigationItem {
    constructor() {
        /** Définit si l'élément de menu est la page courante */
        this.isActive = false;
        /** Variante du menu (default ou megamenu) */
        this.variant = 'default';
        this.internalIsActive = false;
        this.hasSubnav = false;
        this.level = 1;
        this.isSubnavVisible = false;
        this.lastClickedLevel1Item = null;
        this.isMobile = window.innerWidth < 1024;
    }
    componentWillLoad() {
        this.internalIsActive = this.isActive;
        this.checkForSubnav();
        this.calculateLevel();
        this.updateLevelClass();
    }
    componentWillUpdate() {
        if (this.isActive !== this.internalIsActive) {
            this.internalIsActive = this.isActive;
        }
        this.updateLevelClass();
    }
    componentDidUpdate() {
        this.propagateMegamenuClass();
    }
    checkForSubnav() {
        const slot = this.el.shadowRoot.querySelector('slot');
        if (slot) {
            const assignedElements = slot.assignedElements({ flatten: true });
            const hasSubnav = assignedElements.some(el => el.tagName === 'SPW-HEADER-NAVIGATION-DROPDOWN');
            if (hasSubnav !== this.hasSubnav) {
                this.hasSubnav = hasSubnav;
            }
        }
    }
    calculateLevel() {
        let level = 1;
        let parent = this.el.parentElement;
        while (parent && parent.tagName !== 'SPW-HEADER-NAVIGATION') {
            if (parent.tagName === 'SPW-HEADER-NAVIGATION-DROPDOWN') {
                level++;
            }
            parent = parent.parentElement;
        }
        this.level = level;
    }
    updateLevelClass() {
        const htmlElement = document.documentElement;
        Array.from(htmlElement.classList).forEach(className => {
            if (className.startsWith('spw-ds-nav-level-')) {
                htmlElement.classList.remove(className);
            }
        });
        htmlElement.classList.add(`spw-ds-nav-level-${this.level}`);
        this.spwHeaderNavigationNavigate.emit({ level: this.level, element: this.el });
    }
    toggleSubnavVisibility(event) {
        if (!this.isMobile)
            return;
        event.stopPropagation();
        if (this.hasSubnav && !this.isSubnavVisible) {
            const isMobileScreen = window.matchMedia('(max-width: 1024px)').matches;
            if (isMobileScreen) {
                event.preventDefault();
            }
            if (this.level === 1) {
                this.lastClickedLevel1Item = this.el.innerText;
                document.documentElement.setAttribute('data-ds-nav-level1', this.lastClickedLevel1Item);
            }
            this.isSubnavVisible = !this.isSubnavVisible;
            if (this.isSubnavVisible) {
                this.level++;
                this.updateLevelClass();
            }
        }
    }
    getStoredLevel1Item() {
        return document.documentElement.getAttribute('data-ds-nav-level1') || '';
    }
    handleBackClick(event) {
        event.stopPropagation();
        this.isSubnavVisible = false;
        if (this.level > 1) {
            this.level--;
            this.updateLevelClass();
        }
        this.internalIsActive = false;
        if (this.level === 1 && !this.isSubnavVisible) {
            this.lastClickedLevel1Item = null;
            document.documentElement.removeAttribute('data-ds-nav-level1');
        }
    }
    getPageTitle() {
        const parent = this.el.shadowRoot.querySelector('slot');
        if (parent) {
            const assignedElements = parent.assignedElements({ flatten: true });
            if (assignedElements.length > 0) {
                const firstElement = assignedElements[0];
                const title = firstElement.innerText || '';
                const link = firstElement.href || null;
                const target = firstElement.target || null;
                return { title, link, target };
            }
        }
        return null;
    }
    propagateMegamenuClass() {
        if (this.variant === 'megamenu' && this.level === 1) {
            const slot = this.el.shadowRoot.querySelector('slot');
            if (slot) {
                const assignedElements = slot.assignedElements({ flatten: true });
                assignedElements.forEach(element => {
                    if (element.tagName === 'SPW-HEADER-NAVIGATION-DROPDOWN') {
                        const dropdown = element;
                        const dropdownShadowRoot = dropdown.shadowRoot;
                        if (dropdownShadowRoot) {
                            const dropdownDiv = dropdownShadowRoot.querySelector('.spw-header-navigation-dropdown');
                            if (dropdownDiv) {
                                dropdownDiv.classList.add('spw-header-navigation-dropdown--is-megamenu');
                            }
                        }
                        const childItems = element.querySelectorAll('spw-header-navigation-item');
                        childItems.forEach((childItem) => {
                            const childShadowRoot = childItem.shadowRoot;
                            if (childShadowRoot) {
                                const childDiv = childShadowRoot.querySelector('.spw-header-navigation-item');
                                if (childDiv) {
                                    childDiv.classList.add('spw-header-navigation-item--is-megamenu');
                                }
                            }
                        });
                    }
                });
            }
        }
    }
    async componentDidLoad() {
        setTimeout(() => {
            this.checkForSubnav();
            this.propagateMegamenuClass();
        }, 0);
        const slot = this.el.shadowRoot.querySelector('slot');
        if (slot) {
            const mutationObserver = new MutationObserver(() => {
                this.checkForSubnav();
                this.propagateMegamenuClass();
            });
            mutationObserver.observe(slot, { childList: true, subtree: true });
        }
    }
    render() {
        const pageTitle = this.getPageTitle();
        const storedTitle = this.getStoredLevel1Item();
        const elementClass = {
            'spw-header-navigation-item': true,
            'spw-header-navigation-item--has-subnav': this.hasSubnav,
            'spw-header-navigation-item--is-active': this.internalIsActive,
            'spw-header-navigation-item--is-subnav-visible': this.isSubnavVisible,
            'spw-header-navigation-item--is-megamenu': this.variant === 'megamenu',
        };
        return (h(Host, { key: 'e952c4870e1aa4939b14a210565fa3509460256a', "data-level": this.level }, h("div", { key: '7c038d9fd7c6c055b76bd59b05d4b3994a7be2e0', class: elementClass }, h("div", { key: '3e94692f9383cefaaf46aaf74f9106265524ef3b', class: "spw-header-navigation-item__content", onClick: event => this.toggleSubnavVisibility(event) }, this.isSubnavVisible && (h("div", { key: 'ddce685e6067f559f94dfd2b325d2a795ebe94a3', class: `spw-header-navigation-item__top spw-header-navigation-item__top--${this.level}` }, h("div", { key: '387d26e8a57da5d4369d800b763cc8e0062d084f', class: "spw-header-navigation-item__top-back", onClick: event => this.handleBackClick(event) }, h("spw-icon", { key: '5beca235171ae596b17bb79776db39af855f4fd0', icon: "fa-chevron-left" }), " ", h("span", { key: 'b9006b33470692e209ba3c6139181616f9488ab3' }, this.level === 1 ? '' : this.level === 2 ? 'Menu principal' : storedTitle)), h("div", { key: '4b682e1f1a1ef92b695f5b50cb9b7cd4b411fde6', class: "spw-header-navigation-item__top-title" }, h("a", { key: '7bd2492d5b62b58be3f074a11651e3287ece5f91', href: (pageTitle === null || pageTitle === void 0 ? void 0 : pageTitle.link) || '#', target: (pageTitle === null || pageTitle === void 0 ? void 0 : pageTitle.target) || '_self' }, (pageTitle === null || pageTitle === void 0 ? void 0 : pageTitle.title) || '')))), h("slot", { key: 'c57027af3472e46897c0fc0a05e097b4b2f1b1ca' })))));
    }
    static get is() { return "spw-header-navigation-item"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["spw-header-navigation-item.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["spw-header-navigation-item.css"]
        };
    }
    static get properties() {
        return {
            "isActive": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "D\u00E9finit si l'\u00E9l\u00E9ment de menu est la page courante"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "is-active",
                "defaultValue": "false"
            },
            "variant": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "'default' | 'megamenu'",
                    "resolved": "\"default\" | \"megamenu\"",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Variante du menu (default ou megamenu)"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "variant",
                "defaultValue": "'default'"
            }
        };
    }
    static get states() {
        return {
            "internalIsActive": {},
            "hasSubnav": {},
            "level": {},
            "isSubnavVisible": {},
            "lastClickedLevel1Item": {},
            "isMobile": {}
        };
    }
    static get events() {
        return [{
                "method": "spwHeaderNavigationNavigate",
                "name": "spwHeaderNavigationNavigate",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "{ level: number; element: HTMLSpwHeaderNavigationItemElement }",
                    "resolved": "{ level: number; element: HTMLSpwHeaderNavigationItemElement; }",
                    "references": {
                        "HTMLSpwHeaderNavigationItemElement": {
                            "location": "global",
                            "id": "global::HTMLSpwHeaderNavigationItemElement"
                        }
                    }
                }
            }];
    }
    static get elementRef() { return "el"; }
}
