/**
 * Copyright Aquera Inc 2026
 *
 * This source code is licensed under the BSD-3-Clause license found in the
 * LICENSE file in the root directory of this source tree.
 */
var NileContextSubmenu_1;
import { __decorate } from "tslib";
import { html, css } from 'lit';
import { customElement, property, state } from 'lit/decorators.js';
import NileElement from '../internal/nile-element';
import '../nile-floating-panel';
const ITEM_TAG = 'nile-context-menu-item';
const SUBMENU_TAG = 'nile-context-submenu';
const HOVER_OPEN_DELAY = 100;
const HOVER_CLOSE_DELAY = 300;
let submenuIdSeq = 0;
/**
 * Nested submenu inside a `nile-context-menu-item`.
 * @tag nile-context-submenu
 */
let NileContextSubmenu = NileContextSubmenu_1 = class NileContextSubmenu extends NileElement {
    constructor() {
        super(...arguments);
        this.zIndex = 9999;
        this._open = false;
        this._parentItem = null;
        this._proxyId = `nile-context-submenu-anchor-${++submenuIdSeq}`;
        this._menuContainerRef = null;
        this._setupDone = false;
        this._onParentEnter = () => {
            if (this._parentItem?.disabled)
                return;
            this._clearTimers();
            if (this._open)
                return;
            this._openTimer = window.setTimeout(() => this.openSubmenu(), HOVER_OPEN_DELAY);
        };
        this._onParentLeave = () => {
            if (this._openTimer != null) {
                clearTimeout(this._openTimer);
                this._openTimer = undefined;
            }
            if (this._open) {
                this._closeTimer = window.setTimeout(() => this.closeSubmenu(), HOVER_CLOSE_DELAY);
            }
        };
        this._onParentClick = (e) => {
            e.stopPropagation();
            if (this._parentItem?.disabled)
                return;
            this._clearTimers();
            if (this._open)
                this.closeSubmenu();
            else
                this.openSubmenu();
        };
        this._onPanelEnter = () => {
            this._clearTimers();
        };
        this._onPanelLeave = () => {
            if (this._open) {
                this._closeTimer = window.setTimeout(() => {
                    const hasOpenDescendant = NileContextSubmenu_1.openStack.some(sub => sub !== this && this._menuContainerRef?.contains(sub));
                    if (hasOpenDescendant)
                        return;
                    this.closeSubmenu();
                }, HOVER_CLOSE_DELAY);
            }
        };
        this._onMenuMouseOver = (e) => {
            const item = e.composedPath().find(n => n instanceof HTMLElement && n.tagName.toLowerCase() === ITEM_TAG);
            if (!item || item.disabled)
                return;
            item.focus();
        };
        this._onNestedSelect = (e) => {
            if (e.target === this)
                return;
            if (e.detail?.type !== 'click')
                return;
            this.emit('nile-change', e.detail);
        };
        this._onMenuClick = (e) => {
            const item = e.composedPath().find(n => n instanceof HTMLElement && n.tagName.toLowerCase() === ITEM_TAG);
            if (!item || item.disabled)
                return;
            if (item.querySelector(`:scope > ${SUBMENU_TAG}`))
                return;
            const detail = {
                id: item.id,
                value: item.value,
                name: (item.textContent ?? '').trim(),
                target: null,
                originalEvent: e,
            };
            try {
                item.onSelect?.(detail);
            }
            catch (err) {
                console.error('[nile-context-submenu] onSelect callback threw:', err);
            }
            this.emit('nile-change', { type: 'click', ...detail });
        };
    }
    static get styles() {
        return [
            css `
        :host { display: contents; }
      `,
        ];
    }
    connectedCallback() {
        super.connectedCallback();
        let p = this.parentElement;
        while (p && p.tagName.toLowerCase() !== ITEM_TAG)
            p = p.parentElement;
        this._parentItem = p;
        this._ensureProxy();
        if (this._parentItem) {
            this._parentItem.setSubmenuExpanded?.(false);
            this._parentItem.addEventListener('mouseenter', this._onParentEnter);
            this._parentItem.addEventListener('mouseleave', this._onParentLeave);
            this._parentItem.addEventListener('click', this._onParentClick, true);
        }
        this._ensureBodyPanel();
    }
    _ensureProxy() {
        if (this._proxyEl)
            return;
        const el = document.createElement('div');
        el.id = this._proxyId;
        el.setAttribute('aria-hidden', 'true');
        el.style.cssText =
            'position: fixed; top: 0; left: 0; width: 0; height: 0; pointer-events: none;';
        document.body.appendChild(el);
        this._proxyEl = el;
    }
    _syncProxyToParent() {
        if (!this._proxyEl || !this._parentItem)
            return;
        const rect = this._parentItem.getBoundingClientRect();
        this._proxyEl.style.left = `${rect.left}px`;
        this._proxyEl.style.top = `${rect.top}px`;
        this._proxyEl.style.width = `${rect.width}px`;
        this._proxyEl.style.height = `${rect.height}px`;
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        if (this._parentItem) {
            this._parentItem.removeEventListener('mouseenter', this._onParentEnter);
            this._parentItem.removeEventListener('mouseleave', this._onParentLeave);
            this._parentItem.removeEventListener('click', this._onParentClick, true);
        }
        this._clearTimers();
        if (this._open)
            this.closeSubmenu();
        this._teardownBodyArtifacts();
        NileContextSubmenu_1.openStack = NileContextSubmenu_1.openStack.filter(s => s !== this);
    }
    _teardownBodyArtifacts() {
        const menu = this._menuContainerRef;
        if (menu) {
            menu.removeEventListener('click', this._onMenuClick);
            menu.removeEventListener('mouseover', this._onMenuMouseOver);
            menu.removeEventListener('mouseenter', this._onPanelEnter);
            menu.removeEventListener('mouseleave', this._onPanelLeave);
            menu.removeEventListener('nile-change', this._onNestedSelect);
            while (menu.firstChild)
                this.appendChild(menu.firstChild);
        }
        this._floatingPanelEl?.remove();
        this._floatingPanelEl = undefined;
        this._menuContainerRef = null;
        this._setupDone = false;
        this._proxyEl?.remove();
        this._proxyEl = undefined;
    }
    _ensureBodyPanel() {
        if (this._setupDone)
            return;
        const fp = document.createElement('nile-floating-panel');
        fp.setAttribute('for', this._proxyId);
        fp.setAttribute('trigger', 'manual');
        fp.setAttribute('placement', 'right-start');
        fp.panelClass = 'nile-context-menu-panel';
        fp.zIndex = this.zIndex;
        fp.interactive = true;
        fp.hideOnClick = false;
        fp.closeOnEscape = false;
        fp.arrow = 'none';
        fp.distance = 0;
        const menu = document.createElement('div');
        menu.className = 'nile-context-menu__menu';
        menu.setAttribute('role', 'menu');
        fp.appendChild(menu);
        document.body.appendChild(fp);
        this._floatingPanelEl = fp;
        this._menuContainerRef = menu;
        menu.addEventListener('click', this._onMenuClick);
        menu.addEventListener('mouseover', this._onMenuMouseOver);
        menu.addEventListener('mouseenter', this._onPanelEnter);
        menu.addEventListener('mouseleave', this._onPanelLeave);
        menu.addEventListener('nile-change', this._onNestedSelect);
        this._relocateLightChildren();
        this._setupDone = true;
    }
    firstUpdated() {
        this._relocateLightChildren();
    }
    _relocateLightChildren() {
        if (!this._menuContainerRef)
            return;
        for (const kid of Array.from(this.children)) {
            this._menuContainerRef.appendChild(kid);
        }
    }
    _clearTimers() {
        if (this._openTimer != null) {
            clearTimeout(this._openTimer);
            this._openTimer = undefined;
        }
        if (this._closeTimer != null) {
            clearTimeout(this._closeTimer);
            this._closeTimer = undefined;
        }
    }
    openSubmenu() {
        if (this._open)
            return;
        if (this._parentItem?.disabled)
            return;
        this._closeSiblingSubmenus();
        this._ensureProxy();
        this._ensureBodyPanel();
        this._syncProxyToParent();
        this._open = true;
        if (this._floatingPanelEl)
            this._floatingPanelEl.open = true;
        NileContextSubmenu_1.openStack.push(this);
        this._parentItem?.setSubmenuExpanded?.(true);
    }
    closeSubmenu() {
        if (!this._open)
            return;
        for (const sub of [...NileContextSubmenu_1.openStack]) {
            if (sub !== this && this._menuContainerRef?.contains(sub)) {
                sub.closeSubmenu();
            }
        }
        this._open = false;
        if (this._floatingPanelEl)
            this._floatingPanelEl.open = false;
        NileContextSubmenu_1.openStack = NileContextSubmenu_1.openStack.filter(s => s !== this);
        this._clearTimers();
        this._parentItem?.setSubmenuExpanded?.(false);
    }
    get isOpen() {
        return this._open;
    }
    static findByContainer(container) {
        for (const sub of NileContextSubmenu_1.openStack) {
            if (sub._menuContainerRef === container)
                return sub;
        }
        return null;
    }
    get parentItem() {
        return this._parentItem;
    }
    focusFirstItem() {
        if (!this._menuContainerRef)
            return;
        const items = Array.from(this._menuContainerRef.querySelectorAll(ITEM_TAG));
        for (const item of items) {
            let cur = item.parentElement;
            let inDeeperSub = false;
            while (cur && cur !== this._menuContainerRef) {
                if (cur.tagName.toLowerCase() === SUBMENU_TAG) {
                    inDeeperSub = true;
                    break;
                }
                cur = cur.parentElement;
            }
            if (inDeeperSub)
                continue;
            if (!item.disabled) {
                item.focus();
                return;
            }
        }
    }
    _closeSiblingSubmenus() {
        const myLevel = this._parentLevel();
        for (const sub of [...NileContextSubmenu_1.openStack]) {
            if (sub === this)
                continue;
            if (sub._parentLevel() === myLevel)
                sub.closeSubmenu();
        }
    }
    _parentLevel() {
        const item = this._parentItem;
        if (!item)
            return null;
        return item.parentElement?.closest('.nile-context-menu__menu') ?? null;
    }
    render() {
        return html ``;
    }
};
NileContextSubmenu.openStack = [];
__decorate([
    property({ attribute: true, type: Number, reflect: true })
], NileContextSubmenu.prototype, "zIndex", void 0);
__decorate([
    state()
], NileContextSubmenu.prototype, "_open", void 0);
NileContextSubmenu = NileContextSubmenu_1 = __decorate([
    customElement('nile-context-submenu')
], NileContextSubmenu);
export { NileContextSubmenu };
export default NileContextSubmenu;
//# sourceMappingURL=nile-context-submenu.js.map