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

<script>
import { mergeProps } from 'vue';
import BaseSidebarMenuItem from './BaseSidebarMenuItem.vue';

export default {
    name: 'SidebarMenuItem',
    extends: BaseSidebarMenuItem,
    inheritAttrs: false,
    inject: {
        $pcSidebar: { default: null }
    },
    emits: ['update:open'],
    data() {
        return {
            d_open: this.open !== undefined ? this.open : (this.defaultOpen ?? true)
        };
    },
    watch: {
        open(newValue) {
            if (newValue === undefined) return;
            this.d_open = newValue;
        }
    },
    methods: {
        toggle(event) {
            if (!this.collapsible || this.disabled) return;

            const next = !this.d_open;

            if (this.open === undefined) {
                this.d_open = next;
            }

            this.$emit('update:open', next);
        }
    },
    computed: {
        a11yAttrs() {
            const sidebarPart = this.$pcSidebar?.getSectionAttrs('menuitem') ?? {};

            return {
                ...sidebarPart,
                'data-pc-section': 'menuitem',
                'data-collapsible': this.collapsible ? '' : undefined,
                'data-state': this.collapsible ? (this.d_open ? 'expanded' : 'collapsed') : undefined,
                'data-open': this.collapsible && this.d_open ? '' : undefined
            };
        },
        attrs() {
            return mergeProps(this.a11yAttrs, this.ptmi('root'));
        }
    }
};
</script>
