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

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

export default {
    name: 'CompareHandle',
    extends: BaseCompareHandle,
    inheritAttrs: false,
    inject: ['$pcCompare'],
    methods: {
        getHandleStyle() {
            const compare = this.$pcCompare;
            const percent = compare.getValuePercent(compare.d_value);

            return compare.isHorizontal
                ? {
                      position: 'absolute',
                      insetInlineStart: `${percent}%`,
                      insetBlockStart: 0,
                      translate: '-50% 0'
                  }
                : {
                      position: 'absolute',
                      insetInlineStart: 0,
                      bottom: `${percent}%`,
                      translate: '0 50%'
                  };
        }
    },
    computed: {
        attrs() {
            return mergeProps(this.a11yAttrs, this.$pcCompare?.ptm('handle'), this.ptmi('root'));
        },
        a11yAttrs() {
            const compare = this.$pcCompare;

            if (!compare) return {};

            return {
                tabindex: -1,
                style: this.getHandleStyle(),
                'data-pc-section': 'root',
                'data-orientation': compare.orientation,
                'data-disabled': compare.disabled ? '' : undefined,
                'data-invalid': compare.invalid ? '' : undefined,
                'data-dragging': compare.isDragging ? '' : undefined,
                onPointerdown: compare.onHandlePointerDown
            };
        }
    }
};
</script>
