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

<script>
import { isElement } from '@primeuix/utils/dom';
import { mergeProps } from 'vue';
import BaseScrollAreaViewport from './BaseScrollAreaViewport.vue';

export default {
    name: 'ScrollAreaViewport',
    extends: BaseScrollAreaViewport,
    inheritAttrs: false,
    inject: ['$pcScrollArea'],
    beforeUnmount() {
        this.$pcScrollArea?.setViewportEl(null);
    },
    methods: {
        setRef(el) {
            const dom = isElement(el) ? el : (el?.$el ?? null);

            this.$pcScrollArea?.setViewportEl(dom);
        },
        onScroll(event) {
            this.$pcScrollArea?.onScroll(event);
        }
    },
    computed: {
        scrollMeta() {
            return this.$pcScrollArea?.scrollMeta ?? {};
        },
        attrs() {
            return mergeProps(this.a11yAttrs, this.ptmi('root'));
        },
        a11yAttrs() {
            return {
                ref: this.setRef,
                tabindex: this.$pcScrollArea?.hasOverflowX || this.$pcScrollArea?.hasOverflowY ? (this.$pcScrollArea?.tabIndex ?? 0) : undefined,
                'data-scroll-x-before': this.scrollMeta.xBefore ? '' : undefined,
                'data-scroll-x-after': this.scrollMeta.xAfter ? '' : undefined,
                'data-scroll-y-before': this.scrollMeta.yBefore ? '' : undefined,
                'data-scroll-y-after': this.scrollMeta.yAfter ? '' : undefined,
                onScroll: this.onScroll
            };
        }
    }
};
</script>
