<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 BaseScrollAreaScrollbar from './BaseScrollAreaScrollbar.vue';

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

            this.$pcScrollArea?.setScrollbarEl(dom, this.orientation);
        },
        onPointerdown(event) {
            this.$pcScrollArea?.onScrollbarPointerDown(event, this.orientation);
        },
        onPointermove(event) {
            this.$pcScrollArea?.onScrollbarPointerMove(event);
        },
        onPointerup(event) {
            this.$pcScrollArea?.onScrollbarPointerUp(event);
        },
        onWheel(event) {
            this.$pcScrollArea?.onScrollbarWheel(event, this.orientation);
        }
    },
    computed: {
        isVertical() {
            return this.orientation === 'vertical';
        },
        hovering() {
            return !!this.$pcScrollArea?.hovering;
        },
        scrolling() {
            return this.isVertical ? !!this.$pcScrollArea?.scrollingY : !!this.$pcScrollArea?.scrollingX;
        },
        hidden() {
            const scrollMeta = this.$pcScrollArea?.scrollMeta;

            return this.isVertical ? !!scrollMeta?.hiddenY : !!scrollMeta?.hiddenX;
        },
        scrollbarStyle() {
            const base = {
                display: this.hidden ? 'none' : undefined
            };

            if (this.isVertical) {
                return { ...base, bottom: 'var(--px-corner-height)' };
            }

            return { ...base, insetInlineEnd: 'var(--px-corner-width)' };
        },
        attrs() {
            return mergeProps(this.a11yAttrs, this.ptmi('root'));
        },
        a11yAttrs() {
            return {
                ref: this.setRef,
                'data-orientation': this.orientation,
                'data-hovering': this.hovering ? '' : undefined,
                'data-scrolling': this.scrolling ? '' : undefined,
                'data-hidden': this.hidden ? '' : undefined,
                style: this.scrollbarStyle,
                onPointerdown: this.onPointerdown,
                onPointermove: this.onPointermove,
                onPointerup: this.onPointerup,
                onWheel: this.onWheel
            };
        }
    }
};
</script>
