'use client';
import { __decorate } from 'tslib';
import { html } from 'lit';
import { consume } from '@lit/context';
import { state, query, property, queryAssignedElements } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import { offset } from '@floating-ui/dom';
import genId from '../../utils/generateId.js';
import css_248z from '../Dropdown/dropdown.js';
import css_248z$1 from '../Dropdown/dropdown-menu.js';
import css_248z$2 from './mainnav-dropdown.js';
import { SgdsDropdown } from '../Dropdown/sgds-dropdown.js';
import { SgdsDropdownItem } from '../Dropdown/sgds-dropdown-item.js';
import { SgdsIcon } from '../Icon/sgds-icon.js';
import { MainnavBreakpointContext, MainnavExpandedContext } from './mainnav-context.js';
import SgdsElement from '../../base/sgds-element.js';

const TAB = "Tab";
const ENTER = "Enter";
const SPACE = " ";
/**
 * @slot default - The menu items. Pass in sgds-dropdown-item as the menu items
 * @slot toggler - The content of the toggler to pass in html content.
 */
class SgdsMainnavDropdown extends SgdsElement {
    constructor() {
        super(...arguments);
        this._breakpointReached = true;
        /** @internal Forwards value to id attribute of toggle button of Dropdown. An unique id generated by default */
        this.togglerId = genId("dropdown", "button");
        /** When true,  applies active styles on the dropdown button */
        this.active = false;
        /** When true,  applies active styles on the dropdown button */
        this.disabled = false;
    }
    /** @internal */
    get defaultSlotItems() {
        return [...(this.defaultNodes || [])].filter((node) => typeof node.tagName !== "undefined");
    }
    updated() {
        if (this._breakpointReached) {
            this._copyTextToMenu();
            this._resetDropdownMenu();
            this._hideDropdownMenuItems();
        }
    }
    _handleSlotChange(e) {
        const items = e.target.assignedElements({ flatten: true });
        items.forEach(item => {
            var _a;
            item.addEventListener("keydown", this._handleKeyboardMenuItemsEvent.bind(this));
            const dropdownItem = item.shadowRoot.querySelector(".dropdown-item");
            dropdownItem.classList.add("nav-link");
            const link = ((_a = item.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector("a")) || item.querySelector("a");
            link.tabIndex = -1;
            if (dropdownItem.classList.contains("disabled")) {
                link.setAttribute("href", "javascript:void(0)");
                link.setAttribute("tabindex", "-1");
            }
            else {
                link.addEventListener("click", (e) => {
                    const target = e.target;
                    const mainnav = target.closest("sgds-mainnav");
                    mainnav.hide();
                });
            }
        });
    }
    _handleDesktopSlotChange(e) {
        const items = e.target.assignedElements({ flatten: true });
        items.forEach(item => {
            const dropdownItem = item.shadowRoot.querySelector(".dropdown-item");
            dropdownItem.classList.remove("nav-link");
            const slottedItem = item.shadowRoot.querySelector(".dropdown-item slot").assignedElements({
                flatten: true
            });
            slottedItem.forEach(item => {
                if (dropdownItem.classList.contains("disabled")) {
                    item.setAttribute("href", "javascript:void(0)");
                    item.setAttribute("tabindex", "-1");
                }
            });
        });
    }
    _handleKeyboardMenuItemsEvent(e) {
        if (!this._breakpointReached) {
            return;
        }
        const slottedItems = this.defaultSlotItems.filter(item => !item.hasAttribute("disabled"));
        const items = [this.menuHeaderButton, ...slottedItems];
        const itemLength = items.length;
        if (itemLength === 0) {
            return;
        }
        const firstItem = items[0];
        const lastItem = items[itemLength - 1].shadowRoot.querySelector(".dropdown-item");
        let activeElement = document.activeElement;
        if (activeElement === this) {
            activeElement = this.shadowRoot.activeElement;
        }
        switch (e.key) {
            case "Tab": {
                if (e.shiftKey) {
                    if (activeElement === firstItem) {
                        e.preventDefault();
                        setTimeout(() => {
                            lastItem.focus();
                        }, 0);
                    }
                }
                else {
                    const activeShadowElement = activeElement.shadowRoot
                        ? activeElement.shadowRoot.querySelector(".dropdown-item")
                        : null;
                    if (activeShadowElement && activeShadowElement === lastItem) {
                        e.preventDefault();
                        firstItem.focus();
                    }
                }
                break;
            }
        }
    }
    _copyTextToMenu() {
        this.menuHeaderText.innerHTML = this.togglerNodes[0].innerHTML;
    }
    _hideDropdownMenuItems() {
        this.dropdownItems.style.display = "none";
        this.dropdownItems.setAttribute("aria-hidden", "true");
    }
    _resetDropdownMenu() {
        const navbarBody = this._getNavbarBody();
        if (!navbarBody)
            return Promise.resolve();
        return new Promise(resolve => {
            const onEnd = (event) => {
                if (event.propertyName === "transform") {
                    navbarBody.removeEventListener("transitionend", onEnd);
                    resolve();
                }
            };
            const hasTransition = getComputedStyle(navbarBody).transitionProperty.includes("transform");
            if (hasTransition) {
                navbarBody.addEventListener("transitionend", onEnd);
                navbarBody.style.removeProperty("transform");
            }
            else {
                navbarBody.style.removeProperty("transform");
                resolve();
            }
        });
    }
    _handleKeyboardOpen(event) {
        if (this.disabled) {
            return;
        }
        if (event.key === ENTER || event.key === SPACE) {
            event.preventDefault();
            this._openMenu();
        }
    }
    _getNavbarBody() {
        const mainNav = document.querySelector("sgds-mainnav");
        if (!(mainNav === null || mainNav === void 0 ? void 0 : mainNav.shadowRoot)) {
            console.warn("sgds-mainnav or its shadowRoot not found");
            return;
        }
        const navbarBody = mainNav.shadowRoot.querySelector(".navbar-body");
        if (!navbarBody) {
            console.warn(".navbar-body not found in sgds-mainnav");
            return;
        }
        return navbarBody;
    }
    _openMenu() {
        const navbarBody = this._getNavbarBody();
        navbarBody.style.transform = "translateX(-100%)";
        this.dropdownItems.style.removeProperty("display");
        this.dropdownItems.setAttribute("aria-hidden", "false");
        setTimeout(() => {
            this.menuHeaderButton.focus();
        }, 50);
    }
    _handleHeaderKeyboardEvent(event) {
        switch (event.key) {
            case TAB: {
                this._handleKeyboardMenuItemsEvent(event);
                break;
            }
            case ENTER:
            case SPACE: {
                event.preventDefault();
                this._closeMenu();
                break;
            }
        }
    }
    async _closeMenu() {
        await this._resetDropdownMenu();
        this._hideDropdownMenuItems();
        this.navLink.focus();
    }
    render() {
        const mobileView = html `
      <a
        class="${classMap({
            "nav-link": true,
            active: this.active,
            disabled: this.disabled
        })}"
        aria-disabled=${this.disabled ? "true" : "false"}
        tabindex=${this.disabled ? "-1" : "0"}
        role="button"
        @click=${this._openMenu}
        @keydown=${this._handleKeyboardOpen}
      >
        <slot name="toggler"></slot>
        <sgds-icon name="chevron-right"></sgds-icon>
      </a>
      <div class="dropdown-items">
        <a tabindex="0" role="button" @click=${this._closeMenu} @keydown=${this._handleHeaderKeyboardEvent}>
          <sgds-icon name="chevron-left"></sgds-icon>
          <span></span>
        </a>
        <slot @slotchange=${this._handleSlotChange}></slot>
      </div>
    `;
        const desktopView = html `<sgds-dropdown
      .floatingOpts=${{
            middleware: [offset(0)]
        }}
      ?disabled=${this.disabled}
    >
      <a
        class="${classMap({
            "nav-link": true,
            active: this.active,
            disabled: this.disabled
        })}"
        aria-disabled=${this.disabled ? "true" : "false"}
        id=${this.togglerId}
        tabindex=${this.disabled ? "-1" : "0"}
        role="button"
        slot="toggler"
      >
        <slot name="toggler"></slot>
        <sgds-icon name="chevron-down"></sgds-icon>
      </a>
      <slot @slotchange=${this._handleDesktopSlotChange}></slot>
    </sgds-dropdown>`;
        return this._breakpointReached ? mobileView : desktopView;
    }
}
SgdsMainnavDropdown.styles = [...SgdsElement.styles, css_248z, css_248z$1, css_248z$2];
/** @internal */
SgdsMainnavDropdown.dependencies = {
    "sgds-dropdown": SgdsDropdown,
    "sgds-dropdown-item": SgdsDropdownItem,
    "sgds-icon": SgdsIcon
};
__decorate([
    consume({ context: MainnavBreakpointContext, subscribe: true }),
    state()
], SgdsMainnavDropdown.prototype, "_breakpointReached", void 0);
__decorate([
    consume({ context: MainnavExpandedContext, subscribe: true }),
    state()
], SgdsMainnavDropdown.prototype, "expanded", void 0);
__decorate([
    query(".nav-link")
], SgdsMainnavDropdown.prototype, "navLink", void 0);
__decorate([
    query(".dropdown-items")
], SgdsMainnavDropdown.prototype, "dropdownItems", void 0);
__decorate([
    query(".dropdown-items a")
], SgdsMainnavDropdown.prototype, "menuHeaderButton", void 0);
__decorate([
    query(".dropdown-items span")
], SgdsMainnavDropdown.prototype, "menuHeaderText", void 0);
__decorate([
    property({ type: Boolean })
], SgdsMainnavDropdown.prototype, "active", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], SgdsMainnavDropdown.prototype, "disabled", void 0);
__decorate([
    queryAssignedElements({ slot: "toggler" })
], SgdsMainnavDropdown.prototype, "togglerNodes", void 0);
__decorate([
    queryAssignedElements()
], SgdsMainnavDropdown.prototype, "defaultNodes", void 0);

export { SgdsMainnavDropdown, SgdsMainnavDropdown as default };
//# sourceMappingURL=sgds-mainnav-dropdown.js.map
