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

export default {
    name: 'CompareItem',
    extends: BaseCompareItem,
    inheritAttrs: false,
    inject: ['$pcCompare'],
    methods: {
        getItemStyle() {
            const compare = this.$pcCompare;
            const percent = compare.getValuePercent(compare.d_value);
            const positionValue = compare.isHorizontal ? percent : 100 - percent;

            return {
                position: 'absolute',
                inset: 0,
                clipPath: compare.isHorizontal
                    ? this.position === 'before'
                        ? `inset(0 ${Math.max(0, 100 - positionValue)}% 0 0)`
                        : `inset(0 0 0 ${Math.max(0, positionValue)}%)`
                    : this.position === 'before'
                      ? `inset(0 0 ${Math.max(0, 100 - positionValue)}% 0)`
                      : `inset(${Math.max(0, positionValue)}% 0 0 0)`
            };
        }
    },
    computed: {
        attrs() {
            return mergeProps(this.a11yAttrs, this.$pcCompare?.ptm('item'), this.ptmi('root'));
        },
        a11yAttrs() {
            const compare = this.$pcCompare;

            if (!compare) return {};

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