<template>
    <Portal :appendTo="appendTo" :disabled="!popup">
        <transition name="p-anchored-overlay" @enter="onEnter" @leave="onLeave" @after-leave="onAfterLeave" v-bind="ptm('transition')">
            <div v-if="popup ? overlayVisible : true" :ref="containerRef" :id="$id" :class="cx('root')" @click="onOverlayClick" :data-p="dataP" v-bind="ptmi('root')">
                <div v-if="$slots.start" :class="cx('start')" v-bind="ptm('start')">
                    <slot name="start"></slot>
                </div>
                <ul
                    :ref="listRef"
                    :id="$id + '_list'"
                    :class="cx('list')"
                    role="menu"
                    :tabindex="tabindex"
                    :aria-activedescendant="focused ? focusedOptionId : undefined"
                    :aria-label="ariaLabel"
                    :aria-labelledby="ariaLabelledby"
                    @focus="onListFocus"
                    @blur="onListBlur"
                    @keydown="onListKeyDown"
                    v-bind="ptm('list')"
                >
                    <MenuSub :items="model" :depth="0" :parentId="$id" :templates="$slots" :focusedOptionId="focusedOptionId" :unstyled="unstyled" @item-click="itemClick" @item-mousemove="itemMouseMove" :pt="pt" />
                </ul>
                <div v-if="$slots.end" :class="cx('end')" v-bind="ptm('end')">
                    <slot name="end"></slot>
                </div>
            </div>
        </transition>
    </Portal>
</template>

<script>
import { cn } from '@primeuix/utils';
import { absolutePosition, addStyle, find, findSingle, focus, getOuterWidth, isTouchDevice } from '@primeuix/utils/dom';
import { ZIndex } from '@primeuix/utils/zindex';
import { ConnectedOverlayScrollHandler } from '@primevue/core/utils';
import OverlayEventBus from 'primevue/overlayeventbus';
import Portal from 'primevue/portal';
import BaseMenu from './BaseMenu.vue';
import MenuSub from './MenuSub.vue';

const FOCUSABLE_SELECTOR = '[data-pc-section="item"][data-disabled="false"]';

export default {
    name: 'Menu',
    extends: BaseMenu,
    inheritAttrs: false,
    emits: ['show', 'hide', 'focus', 'blur', 'update:expandedKeys'],
    data() {
        return {
            overlayVisible: false,
            focused: false,
            focusedOptionId: null,
            d_expandedKeys: {}
        };
    },
    target: null,
    outsideClickListener: null,
    scrollHandler: null,
    resizeListener: null,
    container: null,
    list: null,
    mounted() {
        if (!this.popup) {
            this.bindResizeListener();
            this.bindOutsideClickListener();
        }
    },
    beforeUnmount() {
        this.unbindResizeListener();
        this.unbindOutsideClickListener();

        if (this.scrollHandler) {
            this.scrollHandler.destroy();
            this.scrollHandler = null;
        }

        this.target = null;

        if (this.container && this.autoZIndex) {
            ZIndex.clear(this.container);
        }

        this.container = null;
    },
    methods: {
        itemClick(event) {
            const item = event.item;

            if (this.disabled(item)) {
                return;
            }

            if (item.command) {
                item.command(event);
            }

            if (this.overlayVisible) this.hide();

            if (!this.popup && this.focusedOptionId !== event.id) {
                this.setFocusedOptionId(event.id);
            }
        },
        itemMouseMove(event) {
            if (this.focused) {
                this.setFocusedOptionId(event.id);
            }
        },
        setFocusedOptionId(id) {
            this.focusedOptionId = id;
        },
        focusMenuList() {
            this.list && focus(this.list);
        },
        onListFocus(event) {
            this.focused = true;

            if (!this.popup && !this.focusedOptionId) {
                this.changeFocusedOptionIndex(0);
            }

            this.$emit('focus', event);
        },
        onListBlur(event) {
            this.focused = false;
            this.setFocusedOptionId(null);
            this.$emit('blur', event);
        },
        onListKeyDown(event) {
            switch (event.code) {
                case 'ArrowDown':
                    this.onArrowDownKey(event);
                    break;

                case 'ArrowUp':
                    this.onArrowUpKey(event);
                    break;

                case 'Home':
                    this.onHomeKey(event);
                    break;

                case 'End':
                    this.onEndKey(event);
                    break;

                case 'Enter':
                case 'NumpadEnter':
                    this.onEnterKey(event);
                    break;

                case 'Space':
                    this.onSpaceKey(event);
                    break;

                case 'Escape':
                    if (this.popup) {
                        focus(this.target);
                        this.hide();
                    }

                    break;

                case 'Tab':
                    this.onTabKey();
                    break;

                default:
                    break;
            }
        },
        onArrowDownKey(event) {
            const optionIndex = this.findNextOptionIndex(this.focusedOptionId);

            this.changeFocusedOptionIndex(optionIndex);
            event.preventDefault();
        },
        onArrowUpKey(event) {
            if (event.altKey && this.popup) {
                focus(this.target);
                this.hide();
                event.preventDefault();
            } else {
                const optionIndex = this.findPrevOptionIndex(this.focusedOptionId);

                this.changeFocusedOptionIndex(optionIndex);
                event.preventDefault();
            }
        },
        onTabKey() {
            if (!this.overlayVisible) {
                return;
            }

            focus(this.target);
            this.hide();
        },
        onHomeKey(event) {
            this.changeFocusedOptionIndex(0);
            event.preventDefault();
        },
        onEndKey(event) {
            this.changeFocusedOptionIndex(find(this.container, FOCUSABLE_SELECTOR).length - 1);
            event.preventDefault();
        },
        onEnterKey(event) {
            event.preventDefault();

            const element = findSingle(this.list, `[id="${this.focusedOptionId}"]`);

            if (!element) return;

            if (element.getAttribute('data-toggleable') === 'true') {
                const content = findSingle(element, '[data-pc-section="itemcontent"]') || element;

                content.click();

                return;
            }

            const anchorElement = findSingle(element, 'a[data-pc-section="itemlink"]');

            this.popup && focus(this.target);
            (anchorElement || element).click();
        },
        onSpaceKey(event) {
            this.onEnterKey(event);
        },
        findNextOptionIndex(id) {
            const links = find(this.container, FOCUSABLE_SELECTOR);
            const matchedOptionIndex = [...links].findIndex((link) => link.id === id);

            return matchedOptionIndex > -1 ? matchedOptionIndex + 1 : 0;
        },
        findPrevOptionIndex(id) {
            const links = find(this.container, FOCUSABLE_SELECTOR);
            const matchedOptionIndex = [...links].findIndex((link) => link.id === id);

            return matchedOptionIndex > -1 ? matchedOptionIndex - 1 : 0;
        },
        changeFocusedOptionIndex(index) {
            const links = find(this.container, FOCUSABLE_SELECTOR);
            let order = index >= links.length ? links.length - 1 : index < 0 ? 0 : index;

            order > -1 && this.setFocusedOptionId(links[order].getAttribute('id'));
        },
        toggle(event, target) {
            if (this.overlayVisible) this.hide();
            else this.show(event, target);
        },
        show(event, target) {
            this.overlayVisible = true;
            this.target = target ?? event.currentTarget;
        },
        hide() {
            this.overlayVisible = false;
            this.target = null;
        },
        onEnter(el) {
            addStyle(el, { position: 'absolute', top: '0' });
            this.alignOverlay();
            this.bindOutsideClickListener();
            this.bindResizeListener();
            this.bindScrollListener();

            if (this.autoZIndex) {
                ZIndex.set('menu', el, this.baseZIndex || this.$primevue.config.zIndex.menu);
            }

            if (this.popup) {
                this.focusMenuList();
            }

            this.$emit('show');
        },
        onLeave() {
            this.unbindOutsideClickListener();
            this.unbindResizeListener();
            this.unbindScrollListener();
            this.$emit('hide');
        },
        onAfterLeave(el) {
            if (this.autoZIndex) {
                ZIndex.clear(el);
            }
        },
        alignOverlay() {
            absolutePosition(this.container, this.target);
            const targetWidth = getOuterWidth(this.target);

            if (targetWidth > getOuterWidth(this.container)) {
                this.container.style.minWidth = getOuterWidth(this.target) + 'px';
            }
        },
        bindOutsideClickListener() {
            if (!this.outsideClickListener) {
                this.outsideClickListener = (event) => {
                    const isOutsideContainer = this.container && !this.container.contains(event.target);
                    const isOutsideTarget = !(this.target && (this.target === event.target || this.target.contains(event.target)));

                    if (this.overlayVisible && isOutsideContainer && isOutsideTarget) {
                        this.hide();
                    } else if (!this.popup && isOutsideContainer && isOutsideTarget) {
                        this.setFocusedOptionId(null);
                    }
                };

                document.addEventListener('click', this.outsideClickListener, true);
            }
        },
        unbindOutsideClickListener() {
            if (this.outsideClickListener) {
                document.removeEventListener('click', this.outsideClickListener, true);
                this.outsideClickListener = null;
            }
        },
        bindScrollListener() {
            if (!this.scrollHandler) {
                this.scrollHandler = new ConnectedOverlayScrollHandler(this.target, () => {
                    if (this.overlayVisible) {
                        this.hide();
                    }
                });
            }

            this.scrollHandler.bindScrollListener();
        },
        unbindScrollListener() {
            if (this.scrollHandler) {
                this.scrollHandler.unbindScrollListener();
            }
        },
        bindResizeListener() {
            if (!this.resizeListener) {
                this.resizeListener = () => {
                    if (this.overlayVisible && !isTouchDevice()) {
                        this.hide();
                    }
                };

                window.addEventListener('resize', this.resizeListener);
            }
        },
        unbindResizeListener() {
            if (this.resizeListener) {
                window.removeEventListener('resize', this.resizeListener);
                this.resizeListener = null;
            }
        },
        visible(item) {
            return typeof item?.visible === 'function' ? item.visible() : item?.visible !== false;
        },
        disabled(item) {
            return typeof item?.disabled === 'function' ? item.disabled() : item?.disabled;
        },
        label(item) {
            return typeof item?.label === 'function' ? item.label() : item?.label;
        },
        isItemToggleable(item, depth) {
            return item?.toggleable !== undefined ? item.toggleable : depth > 0;
        },
        isSubmenuExpanded(id) {
            return !!this.currentExpandedKeys?.[id];
        },
        toggleSubmenu(id) {
            const next = { ...(this.currentExpandedKeys || {}), [id]: !this.isSubmenuExpanded(id) };

            if (this.expandedKeys !== undefined) this.$emit('update:expandedKeys', next);
            else this.d_expandedKeys = next;
        },
        onOverlayClick(event) {
            OverlayEventBus.emit('overlay-click', {
                originalEvent: event,
                target: this.target
            });
        },
        containerRef(el) {
            this.container = el;
        },
        listRef(el) {
            this.list = el;
        }
    },
    computed: {
        dataP() {
            return cn({
                popup: this.popup
            });
        },
        currentExpandedKeys() {
            return this.expandedKeys !== undefined ? this.expandedKeys : this.d_expandedKeys;
        },
        /**
         * Maps each visible menuitem to { level, posinset, setsize }.
         *
         * ARIA rules for Menu:
         *   - role="none" labels (non-toggleable group headers) are invisible to AT
         *     so their children are siblings of the group's peers.
         *   - role="menu" scopes are created only by toggleable submenu <ul>'s —
         *     those start a new aria-level.
         *
         * Implementation:
         *   1. collectSiblings(items, depth): returns the flat list of aria-siblings
         *      that live in the SAME role=menu scope — non-toggleable groups are
         *      inlined so their children bubble up.
         *   2. assign(items, level, depth): for each sibling in the current scope,
         *      stores its level/posinset/setsize; for siblings that are themselves
         *      toggleable submenu headers, recurses into their items with level + 1.
         */
        ariaMetaMap() {
            const map = new Map();

            const collectSiblings = (items, depth) => {
                const siblings = [];

                (items || []).forEach((item) => {
                    if (!this.visible(item) || item.separator) return;

                    if (item.items && !this.isItemToggleable(item, depth)) {
                        siblings.push(...collectSiblings(item.items, depth + 1));
                    } else {
                        siblings.push(item);
                    }
                });

                return siblings;
            };

            const assign = (items, level, depth) => {
                const siblings = collectSiblings(items, depth);

                siblings.forEach((item, idx) => {
                    map.set(item, { level, posinset: idx + 1, setsize: siblings.length });

                    if (item.items) {
                        assign(item.items, level + 1, depth + 1);
                    }
                });
            };

            assign(this.model || [], 1, 0);

            return map;
        }
    },
    components: {
        MenuSub,
        Portal
    }
};
</script>
