<template>
    <component v-if="!asChild" :is="as" :class="cx('root')" v-bind="ptmi('root')">
        <slot />
    </component>
    <slot v-else :class="cx('root')" />
</template>

<script>
import BaseSidebarLayout from './BaseSidebarLayout.vue';

export default {
    name: 'SidebarLayout',
    extends: BaseSidebarLayout,
    inheritAttrs: false,
    triggerEvent: null,
    data() {
        return {
            registryMap: new Map()
        };
    },
    methods: {
        registerSidebar(id, entry) {
            this.registryMap.set(id, entry);
        },
        unregisterSidebar(id) {
            this.registryMap.delete(id);
        },
        getSidebarEntry(id) {
            return this.registryMap.get(id);
        },
        getSidebarEntries() {
            return this.registryMap;
        },
        toggleSidebar(target, event) {
            if (target) {
                this.registryMap.get(target)?.toggle(event);

                return;
            }

            if (this.registryMap.size >= 1) {
                this.registryMap.values().next().value?.toggle(event);
            }
        },
        collapseSidebar(target, event) {
            if (typeof target === 'string') {
                const entry = this.registryMap.get(target);

                if (entry?.open) entry.toggle(event);

                return;
            }

            const originalEvent = event ?? target;

            this.registryMap.forEach((entry) => {
                if (entry.open && entry.dismissable) entry.toggle(originalEvent);
            });
        },
        notifyTriggerClick(event) {
            // Remember the click dispatched by a SidebarTrigger so the same event, once it bubbles
            // to SidebarMain, is not treated as an outside click that would undo the trigger action.
            this.triggerEvent = event;
        },
        onMainClick(event) {
            if (event && this.triggerEvent === event) {
                this.triggerEvent = null;

                return;
            }

            this.registryMap.forEach((entry) => {
                if (entry.open && entry.overlay && entry.hideOnOutsideClick) entry.toggle(event);
            });
        },
        isAnySidebarOpen() {
            let open = false;

            this.registryMap.forEach((entry) => {
                if (entry.open) open = true;
            });

            return open;
        }
    }
};
</script>
