'use client';
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var tslib = require('tslib');
var sgdsElement = require('../../base/sgds-element.cjs.js');
var lit = require('lit');
var decorators_js = require('lit/decorators.js');
var classMap_js = require('lit/directives/class-map.js');
var watch = require('../../utils/watch.cjs.js');
var event = require('../../utils/event.cjs.js');
var animate = require('../../utils/animate.cjs.js');
var animationRegistry = require('../../utils/animation-registry.cjs.js');
var breakpoints = require('../../utils/breakpoints.cjs.js');
var sgdsIcon = require('../Icon/sgds-icon.cjs.js');
var subnav = require('./subnav.cjs.js');
var grid = require('../../css/grid.cjs.js');
var slot = require('../../utils/slot.cjs.js');

const VALID_KEYS = ["Enter", " "];
/**
 * @summary This component provides secondary navigation within a specific section or page. It typically appears below the main navigation and offers context-specific links or actions to help users explore related content.
 *
 * @event sgds-show - Emitted on show. Only for collapsed menu.
 * @event sgds-after-show - Emitted on show after animation has completed. Only for collapsed menu.
 * @event sgds-hide - Emitted on hide. Only for collapsed menu.
 * @event sgds-after-hide - Emitted on hide after animation has completed. Only for collapsed menu.
 *
 * @slot default - Default slot of SgdsSubnav. Pass in SgdsSubnavItem elements here.
 * @slot header - Slot for rendering the sub-navigation header or section title.
 * @slot actions - Slot for inserting contextual action elements such as buttons, filters, or other controls aligned with the sub-navigation.
 *
 */
class SgdsSubnav extends sgdsElement["default"] {
    constructor() {
        super(...arguments);
        /** Used only for SSR to indicate the presence of the `actions` slot. */
        this.hasActionsSlot = false;
        this.isCollapsed = false;
        this.isMenuOpen = false;
        this.hasSlotController = new slot.HasSlotController(this, "actions");
        this._handleResize = async () => {
            this.isCollapsed = window.innerWidth < breakpoints.LG_BREAKPOINT;
            await this.updateComplete;
            if (!this.isCollapsed) {
                this.isMenuOpen = false;
            }
            this._updateMobileLayout();
        };
        this._updateMobileLayout = () => {
            if (!this.nav || !this.headerContainer || !this.mobileActions || !this.mobileNav)
                return;
            if (this.isCollapsed) {
                const { top: subnavTop } = this.nav.getBoundingClientRect();
                const headerHeight = this.headerContainer.clientHeight;
                const actionsButtonHeight = this.mobileActions.clientHeight;
                const offset = window.innerWidth >= breakpoints.MD_BREAKPOINT && window.innerWidth < breakpoints.LG_BREAKPOINT
                    ? subnavTop + headerHeight
                    : subnavTop + headerHeight + actionsButtonHeight;
                this.mobileNav.style.maxHeight = `calc(100dvh - ${offset}px)`;
                this.style.minHeight = `${this.nav.clientHeight}px`;
                this.nav.style.position = "absolute";
            }
            else {
                this.mobileNav.style.maxHeight = "none";
                this.style.minHeight = "auto";
                this.nav.style.position = "relative";
            }
        };
        this._toggleMenu = () => {
            var _a;
            if (this.isMenuOpen) {
                this.hide();
            }
            else {
                document.querySelector("body").style.overflow = "hidden";
                this.show();
            }
            (_a = this.toggler) === null || _a === void 0 ? void 0 : _a.focus();
        };
    }
    connectedCallback() {
        super.connectedCallback();
        // this._handleResize();
        window.addEventListener("resize", this._handleResize);
        window.addEventListener("click", (event) => this._handleClickOutOfElement(event, this.navGroup));
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        window.removeEventListener("resize", this._handleResize);
        window.removeEventListener("click", (event) => this._handleClickOutOfElement(event, this.navGroup));
    }
    firstUpdated(changedProperties) {
        super.firstUpdated(changedProperties);
        this._handleResize();
    }
    updated() {
        if (!this.hasActionsSlot)
            this.hasActionsSlot = this.hasSlotController.test("actions");
    }
    _handleClickOutOfElement(e, self) {
        if (!e.composedPath().includes(self) && !e.composedPath().includes(this.toggler)) {
            this.hide();
        }
    }
    async _onKeyboardToggle(event) {
        if (!VALID_KEYS.includes(event.key))
            return;
        event.preventDefault();
        this._toggleMenu();
    }
    /** Shows the menu. For when subnav is in the collapsed form */
    async show() {
        if (this.isMenuOpen) {
            return;
        }
        this.isMenuOpen = true;
        return event.waitForEvent(this, "sgds-after-show");
    }
    /** Hide the menu. For when subnav is in the collapsed form */
    async hide() {
        if (!this.isMenuOpen) {
            return;
        }
        this.isMenuOpen = false;
        document.querySelector("body").style.removeProperty("overflow");
        return event.waitForEvent(this, "sgds-after-hide");
    }
    async _animateToShow() {
        const sgdsShow = this.emit("sgds-show", { cancelable: true });
        if (sgdsShow.defaultPrevented) {
            this.isMenuOpen = false;
            return;
        }
        await animate.stopAnimations(this.mobileNav);
        if (this.isCollapsed) {
            this.mobileNav.style.display = "flex";
        }
        const { keyframes, options } = animationRegistry.getAnimation(this, "subnav.show");
        await animate.animateTo(this.mobileNav, animate.shimKeyframesHeightAuto(keyframes, this.mobileNav.scrollHeight), options);
        this.emit("sgds-after-show");
    }
    async _animateToHide() {
        const slHide = this.emit("sgds-hide", { cancelable: true });
        if (slHide.defaultPrevented) {
            this.isMenuOpen = true;
            return;
        }
        await animate.stopAnimations(this.mobileNav);
        const { keyframes, options } = animationRegistry.getAnimation(this, "subnav.hide");
        await animate.animateTo(this.mobileNav, animate.shimKeyframesHeightAuto(keyframes, this.mobileNav.scrollHeight), options);
        if (this.isCollapsed) {
            this.mobileNav.style.display = "none";
        }
        this.emit("sgds-after-hide");
    }
    async handleOpenChange() {
        if (this.isMenuOpen) {
            // Show
            this._animateToShow();
        }
        else {
            // Hide
            this._animateToHide();
        }
    }
    async handleCollapsedChange() {
        await this.updateComplete;
        this.mobileNav.style.display = this.isCollapsed ? "none" : "flex";
    }
    render() {
        return lit.html `
      <nav aria-label="Sub navigation">
        <div
          class=${classMap_js.classMap({
            "sgds-container": true,
            subnav: true,
            collapsed: !this.isMenuOpen
        })}
        >
          <div class="header-container">
            <slot name="header"></slot>
            <sgds-icon
              class="subnav-toggler"
              name="chevron-down"
              tabindex="0"
              @click=${this._toggleMenu}
              @keydown=${this._onKeyboardToggle}
              aria-label="Toggle sub navigation"
              aria-expanded=${this.isMenuOpen}
            ></sgds-icon>
          </div>
          <div class="subnav-nav-group">
            <div class="subnav-nav">
              <slot></slot>
            </div>
            <div
              class="${classMap_js.classMap({
            "subnav-actions": true,
            "no-actions": !this.hasActionsSlot
        })}"
            >
              <slot name="actions"></slot>
            </div>
          </div>
        </div>
      </nav>
    `;
    }
}
SgdsSubnav.styles = [...sgdsElement["default"].styles, subnav["default"], grid["default"]];
/** @internal */
SgdsSubnav.dependencies = {
    "sgds-icon": sgdsIcon.SgdsIcon
};
tslib.__decorate([
    decorators_js.property({ type: Boolean })
], SgdsSubnav.prototype, "hasActionsSlot", void 0);
tslib.__decorate([
    decorators_js.query("nav")
], SgdsSubnav.prototype, "nav", void 0);
tslib.__decorate([
    decorators_js.query(".subnav-nav")
], SgdsSubnav.prototype, "mobileNav", void 0);
tslib.__decorate([
    decorators_js.query(".header-container")
], SgdsSubnav.prototype, "headerContainer", void 0);
tslib.__decorate([
    decorators_js.query(".subnav-toggler")
], SgdsSubnav.prototype, "toggler", void 0);
tslib.__decorate([
    decorators_js.query(".subnav-nav-group")
], SgdsSubnav.prototype, "navGroup", void 0);
tslib.__decorate([
    decorators_js.query(".subnav-actions")
], SgdsSubnav.prototype, "mobileActions", void 0);
tslib.__decorate([
    decorators_js.state()
], SgdsSubnav.prototype, "isCollapsed", void 0);
tslib.__decorate([
    decorators_js.state()
], SgdsSubnav.prototype, "isMenuOpen", void 0);
tslib.__decorate([
    watch.watch("isMenuOpen", { waitUntilFirstUpdate: true })
], SgdsSubnav.prototype, "handleOpenChange", null);
tslib.__decorate([
    watch.watch("isCollapsed", { waitUntilFirstUpdate: true })
], SgdsSubnav.prototype, "handleCollapsedChange", null);
animationRegistry.setDefaultAnimation("subnav.show", {
    keyframes: [
        { height: "0", opacity: "0" },
        { height: "auto", opacity: "1" }
    ],
    options: { duration: 200, easing: "ease-in-out" }
});
animationRegistry.setDefaultAnimation("subnav.hide", {
    keyframes: [
        { height: "auto", opacity: "1" },
        { height: "0", opacity: "0" }
    ],
    options: { duration: 200, easing: "ease-in-out" }
});

exports.SgdsSubnav = SgdsSubnav;
exports["default"] = SgdsSubnav;
//# sourceMappingURL=sgds-subnav.cjs.js.map
