<template>
    <component v-if="!asChild" :is="as" :class="cx('root')" :type="as === 'BUTTON' || as === 'button' ? 'button' : undefined" v-bind="attrs" @click="onClick">
        <slot />
    </component>
    <slot v-else :a11yAttrs="a11yAttrs" :class="cx('root')" :onClick="onClick" />
</template>

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

export default {
    name: 'SidebarTrigger',
    extends: BaseSidebarTrigger,
    inheritAttrs: false,
    inject: {
        $pcSidebar: { default: null },
        $pcSidebarLayout: { default: null }
    },
    methods: {
        onClick(event) {
            // Let the layout know this click came from a trigger so its SidebarMain outside-click
            // handler does not immediately undo the toggle when the same event bubbles up.
            this.$pcSidebarLayout?.notifyTriggerClick?.(event);

            if (this.$pcSidebar) {
                this.$pcSidebar.toggle(event);

                return;
            }

            if (this.$pcSidebarLayout) {
                this.$pcSidebarLayout.toggleSidebar(this.target, event);
            }
        }
    },
    computed: {
        a11yAttrs() {
            const sidebarPart = this.$pcSidebar?.getSectionAttrs('trigger') ?? {};

            return {
                ...sidebarPart,
                'data-pc-name': 'sidebartrigger',
                'data-pc-section': 'root'
            };
        },
        attrs() {
            return mergeProps(this.$attrs, this.a11yAttrs, this.ptmi('root'));
        }
    }
};
</script>
