<template>
    <div :class="cx('root')" v-bind="ptmi('root')">
        <slot></slot>
    </div>
</template>

<script>
import { isRTL } from '@primeuix/utils/dom';
import BaseTabs from './BaseTabs.vue';

export default {
    name: 'Tabs',
    extends: BaseTabs,
    inheritAttrs: false,
    emits: ['update:value'],
    data() {
        return {
            d_value: this.value
        };
    },
    watch: {
        value(newValue) {
            this.d_value = newValue;
        }
    },
    methods: {
        updateValue(newValue) {
            if (this.d_value !== newValue) {
                this.d_value = newValue;
                this.$emit('update:value', newValue);
            }
        },
        scrollToActiveTab(content, tab) {
            if (!content || !tab || this.scrollStrategy === false) return;

            if (typeof this.scrollStrategy === 'function') {
                this.scrollStrategy(content, tab);

                return;
            }

            const contentWidth = content.clientWidth;
            const currentScrollLeft = Math.abs(content.scrollLeft);
            const tabLeft = tab.offsetLeft;
            const tabWidth = tab.offsetWidth;
            const tabRight = tabLeft + tabWidth;
            let targetScrollLeft;

            if (this.scrollStrategy === 'center') {
                targetScrollLeft = tabLeft - (contentWidth - tabWidth) / 2;
            } else {
                const padding = contentWidth * 0.1;

                if (tabLeft < currentScrollLeft + padding) {
                    targetScrollLeft = tabLeft - padding;
                } else if (tabRight > currentScrollLeft + contentWidth - padding) {
                    targetScrollLeft = tabRight - contentWidth + padding;
                } else {
                    return;
                }
            }

            const maxScrollLeft = content.scrollWidth - contentWidth;
            const clampedScrollLeft = Math.max(0, Math.min(targetScrollLeft, maxScrollLeft));

            content.scrollTo({ left: isRTL(content) ? -clampedScrollLeft : clampedScrollLeft, behavior: 'smooth' });
        }
    }
};
</script>
