<template>
    <component
        :is="as"
        :class="cx('root')"
        :style="sx('root')"
        :data-orientation="orientation"
        :data-align="align"
        :data-page="d_page"
        :data-swiping="swiping ? '' : undefined"
        :data-autosize="autoSize ? '' : undefined"
        role="region"
        v-bind="ptmi('root')"
    >
        <template v-if="hasCarouselValue">
            <div v-if="$slots.header" :class="cx('header')" v-bind="ptm('header')">
                <slot name="header"></slot>
            </div>
            <div v-if="!empty" :class="[cx('contentContainer'), containerClass]" v-bind="ptm('contentContainer')">
                <div :class="[cx('content'), contentClass]" :aria-live="isAutoplay() ? 'off' : 'polite'" v-bind="ptm('content')">
                    <Button
                        v-if="showNavigators"
                        :class="cx('pcPrevButton')"
                        :disabled="backwardIsDisabled"
                        :aria-label="ariaPrevButtonLabel"
                        :unstyled="unstyled"
                        @click="navBackward"
                        v-bind="prevButtonProps"
                        :pt="ptm('pcPrevButton')"
                        data-pc-group-section="navigator"
                    >
                        <slot name="previcon">
                            <component :is="isVertical() ? 'ChevronUp' : 'ChevronLeft'" v-bind="ptm('pcPrevButton')['icon']" />
                        </slot>
                    </Button>
                    <div :class="cx('viewport')" :style="[{ height: isVertical() ? verticalViewPortHeight : 'auto' }]" @touchend="onTouchEnd" @touchstart="onTouchStart" @touchmove="onTouchMove" v-bind="ptm('viewport')">
                        <div ref="itemsContainer" :class="cx('itemList')" @transitionend="onTransitionEnd" v-bind="ptm('itemList')">
                            <template v-if="isCircular()">
                                <div
                                    v-for="(item, index) of value.slice(-1 * d_numVisible)"
                                    :key="index + '_scloned'"
                                    :class="cx('itemClone', { index, value, totalShiftedItems, d_numVisible })"
                                    v-bind="ptm('itemClone')"
                                    :data-p-carousel-item-active="totalShiftedItems * -1 === value.length + d_numVisible"
                                    :data-p-carousel-item-start="index === 0"
                                    :data-p-carousel-item-end="value.slice(-1 * d_numVisible).length - 1 === index"
                                >
                                    <slot name="item" :data="item" :index="index"></slot>
                                </div>
                            </template>
                            <div
                                v-for="(item, index) of value"
                                :key="index"
                                :class="cx('item', { index })"
                                role="group"
                                :aria-hidden="firstIndex() > index || lastIndex() < index ? true : undefined"
                                :aria-label="ariaSlideNumber(index)"
                                :aria-roledescription="ariaSlideLabel"
                                v-bind="getItemPTOptions('item', index)"
                                :data-p-carousel-item-active="firstIndex() <= index && lastIndex() >= index"
                                :data-p-carousel-item-start="firstIndex() === index"
                                :data-p-carousel-item-end="lastIndex() === index"
                            >
                                <slot name="item" :data="item" :index="index"></slot>
                            </div>
                            <template v-if="isCircular()">
                                <div v-for="(item, index) of value.slice(0, d_numVisible)" :key="index + '_fcloned'" :class="cx('itemClone', { index, value, totalShiftedItems, d_numVisible })" v-bind="ptm('itemClone')">
                                    <slot name="item" :data="item" :index="index"></slot>
                                </div>
                            </template>
                        </div>
                    </div>
                    <Button
                        v-if="showNavigators"
                        :class="cx('pcNextButton')"
                        :disabled="forwardIsDisabled"
                        :aria-label="ariaNextButtonLabel"
                        :unstyled="unstyled"
                        @click="navForward"
                        v-bind="nextButtonProps"
                        :pt="ptm('pcNextButton')"
                        data-pc-group-section="navigator"
                    >
                        <slot name="nexticon">
                            <component :is="isVertical() ? 'ChevronDown' : 'ChevronRight'" v-bind="ptm('pcNextButton')['icon']" />
                        </slot>
                    </Button>
                </div>
                <ul v-if="totalIndicators >= 0 && showIndicators" ref="indicatorContent" :class="[cx('indicatorList'), indicatorsContentClass]" @keydown="onIndicatorKeydown" v-bind="ptm('indicatorList')">
                    <li v-for="(indicator, i) of totalIndicators" :key="'p-carousel-indicator-' + i.toString()" :class="cx('indicator', { index: i })" v-bind="getIndicatorPTOptions('indicator', i)" :data-p-active="d_page === i">
                        <button
                            :class="cx('indicatorButton')"
                            type="button"
                            :tabindex="d_page === i ? '0' : '-1'"
                            :aria-label="ariaPageLabel(i + 1)"
                            :aria-current="d_page === i ? 'page' : undefined"
                            @click="onIndicatorClick($event, i)"
                            v-bind="getIndicatorPTOptions('indicatorButton', i)"
                        />
                    </li>
                </ul>
            </div>
            <slot v-else name="empty">
                {{ emptyMessageText }}
            </slot>
            <div v-if="$slots.footer" :class="cx('footer')" v-bind="ptm('footer')">
                <slot name="footer"></slot>
            </div>
        </template>

        <slot v-else></slot>
    </component>
</template>

<script>
import ChevronDown from '@primeicons/vue/chevron-down';
import ChevronLeft from '@primeicons/vue/chevron-left';
import ChevronRight from '@primeicons/vue/chevron-right';
import ChevronUp from '@primeicons/vue/chevron-up';
import { addClass, find, findSingle, getAttribute, isElement, removeClass, setAttribute } from '@primeuix/utils/dom';
import { localeComparator, sort } from '@primeuix/utils/object';
import Button from 'primevue/button';
import Ripple from 'primevue/ripple';
import BaseCarousel from './BaseCarousel.vue';

const SWIPE_THRESHOLD = 20;
const POINTER_SWIPE_DISTANCE = 6;
const WHEEL_DEBOUNCE_MS = 80;
const SCROLL_DEBOUNCE_MS = 80;
const INTERSECTION_THRESHOLD = 0.6;
const TRANSITION_DURATION_MS = 500;

export default {
    name: 'Carousel',
    extends: BaseCarousel,
    inheritAttrs: false,
    emits: ['update:page', 'update:slide'],
    isRemainingItemsAdded: false,
    mutationObserver: null,
    intersectionObserver: null,
    resizeObserver: null,
    scrollTimeout: null,
    wheelTimeout: null,
    onScrollHandler: null,
    data() {
        return {
            remainingItems: 0,
            d_numVisible: this.numVisible,
            d_numScroll: this.numScroll,
            d_oldNumScroll: 0,
            d_oldNumVisible: 0,
            d_oldValue: [],
            d_page: this.page ?? 0,
            totalShiftedItems: (this.page ?? 0) * this.numScroll * -1,
            allowAutoplay: !!this.autoplayInterval,
            d_circular: this.circular || this.allowAutoplay,
            swiping: false,
            isNextDisabled: false,
            isPrevDisabled: false,
            snapPoints: new Set(),
            scrollSnaps: [],
            initialPageApplied: false,
            initialControlledScroll: false,
            swipeStartPoint: { x: 0, y: 0 },
            startPos: null,
            isRealSwipe: false,
            contentEl: null
        };
    },
    watch: {
        page(newValue) {
            if (newValue == null) return;

            if (this.snapPoints.size > 0) {
                if (this.slide != null) return;

                const instant = !this.initialControlledScroll;

                this.initialControlledScroll = true;
                this.scrollToPage(newValue, instant);
            } else {
                if (newValue > this.d_page) {
                    this.navForward({}, newValue);
                } else if (newValue < this.d_page) {
                    this.navBackward({}, newValue);
                }

                this.d_page = newValue;
            }
        },
        circular(newValue) {
            this.d_circular = newValue || !!this.autoplayInterval;
        },
        autoplayInterval(newValue) {
            this.allowAutoplay = !!newValue;
            this.d_circular = this.circular || !!newValue;

            if (!newValue) {
                this.stopAutoplay();
            }
        },
        numVisible(newValue, oldValue) {
            this.d_numVisible = newValue;
            this.d_oldNumVisible = oldValue;
        },
        numScroll(newValue, oldValue) {
            this.d_oldNumScroll = oldValue;
            this.d_numScroll = newValue;
        },
        value(newValue, oldValue) {
            this.d_oldValue = oldValue || [];

            if (!newValue?.length) {
                this.remainingItems = 0;
            }
        },
        contentEl(newEl, oldEl) {
            if (oldEl && oldEl !== newEl) {
                this.unbindResizeObserver();
                this.unbindMutationObserver();
                this.unbindIntersectionObserver();
                this.unbindContentScrollListener();
            }

            if (newEl) {
                this.bindResizeObserver();
                this.bindMutationObserver();
                this.bindIntersectionObserver();
                this.bindContentScrollListener();
                this.computeSnapPoints();
                this.updateNavigationState();
            } else {
                this.unbindResizeObserver();
                this.unbindMutationObserver();
                this.unbindIntersectionObserver();
                this.unbindContentScrollListener();
            }
        },
        snapPoints(newSet, oldSet) {
            if (!newSet?.size) {
                this.updateNavigationState();

                return;
            }

            const page = Math.max(0, Math.min(this.d_page, newSet.size - 1));

            this.updateNavigationState(page);

            if (!this.initialPageApplied && (!oldSet || oldSet.size === 0)) {
                this.initialPageApplied = true;

                if (this.slide != null) {
                    this.initialControlledScroll = true;
                    this.scrollToSlide(this.slide, true);
                } else if (this.page != null) {
                    this.initialControlledScroll = true;
                    this.scrollToPage(this.page, true);
                } else {
                    this.d_page = page;
                }
            }
        },
        slide(newSlide) {
            if (newSlide == null) return;
            if (this.snapPoints.size === 0) return;

            const instant = !this.initialControlledScroll;

            this.initialControlledScroll = true;
            this.scrollToSlide(newSlide, instant);
        }
    },
    mounted() {
        if (!this.hasCarouselValue) return;
        if (this.empty) return;

        let stateChanged = false;

        this.initializeLegacyCarousel();

        if (this.isCircular()) {
            let totalShiftedItems = this.totalShiftedItems;

            if (this.d_page === 0) {
                totalShiftedItems = -1 * this.d_numVisible;
            } else if (totalShiftedItems === 0) {
                totalShiftedItems = -1 * this.value.length;

                if (this.remainingItems > 0) {
                    this.isRemainingItemsAdded = true;
                }
            }

            if (totalShiftedItems !== this.totalShiftedItems) {
                this.totalShiftedItems = totalShiftedItems;

                stateChanged = true;
            }
        }

        if (!stateChanged && this.isAutoplay()) {
            this.startAutoplay();
        }
    },
    updated() {
        if (!this.hasCarouselValue) return;

        if (this.$refs.itemsContainer && !this.carouselStyle) {
            this.initializeLegacyCarousel();
        }

        if (!this.empty) {
            const isCircular = this.isCircular();
            let stateChanged = false;
            let totalShiftedItems = this.totalShiftedItems;

            if (this.autoplayInterval) {
                this.stopAutoplay();
            }

            if (this.d_oldNumScroll !== this.d_numScroll || this.d_oldNumVisible !== this.d_numVisible || this.d_oldValue.length !== this.value.length) {
                this.remainingItems = (this.value.length - this.d_numVisible) % this.d_numScroll;

                let page = this.d_page;

                if (this.totalIndicators !== 0 && page >= this.totalIndicators) {
                    page = this.totalIndicators - 1;
                    this.$emit('update:page', page);
                    this.d_page = page;
                    stateChanged = true;
                }

                totalShiftedItems = page * this.d_numScroll * -1;

                if (isCircular) {
                    totalShiftedItems -= this.d_numVisible;
                }

                if (page === this.totalIndicators - 1 && this.remainingItems > 0) {
                    totalShiftedItems += -1 * this.remainingItems + this.d_numScroll;
                    this.isRemainingItemsAdded = true;
                } else {
                    this.isRemainingItemsAdded = false;
                }

                if (totalShiftedItems !== this.totalShiftedItems) {
                    this.totalShiftedItems = totalShiftedItems;
                    stateChanged = true;
                }

                this.d_oldNumScroll = this.d_numScroll;
                this.d_oldNumVisible = this.d_numVisible;
                this.d_oldValue = this.value;
                this.$refs.itemsContainer.style.transform = this.isVertical() ? `translate3d(0, ${totalShiftedItems * (100 / this.d_numVisible)}%, 0)` : `translate3d(${totalShiftedItems * (100 / this.d_numVisible)}%, 0, 0)`;
            }

            if (isCircular) {
                if (this.d_page === 0) {
                    totalShiftedItems = -1 * this.d_numVisible;
                } else if (totalShiftedItems === 0) {
                    totalShiftedItems = -1 * this.value.length;

                    if (this.remainingItems > 0) {
                        this.isRemainingItemsAdded = true;
                    }
                }

                if (totalShiftedItems !== this.totalShiftedItems) {
                    this.totalShiftedItems = totalShiftedItems;

                    stateChanged = true;
                }
            }

            if (!stateChanged && this.isAutoplay()) {
                this.startAutoplay();
            }
        }
    },
    beforeUnmount() {
        if (this.responsiveOptions) {
            this.unbindDocumentListeners();
        }

        if (this.autoplayInterval) {
            this.stopAutoplay();
        }

        this.unbindResizeObserver();
        this.unbindMutationObserver();
        this.unbindIntersectionObserver();
        this.unbindContentScrollListener();

        if (this.carouselStyle) {
            this.carouselStyle.remove();
            this.carouselStyle = null;
        }
    },
    methods: {
        initializeLegacyCarousel() {
            if (!this.carouselStyle) {
                this.createStyle();
            }

            this.calculatePosition();

            if (this.responsiveOptions && !this.documentResizeListener) {
                this.bindDocumentListeners();
            }
        },
        getIndicatorPTOptions(key, index) {
            return this.ptm(key, {
                context: {
                    highlighted: index === this.d_page
                }
            });
        },
        getItemPTOptions(key, index) {
            return this.ptm(key, {
                context: {
                    index,
                    active: this.firstIndex() <= index && this.lastIndex() >= index,
                    start: this.firstIndex() === index,
                    end: this.lastIndex() === index
                }
            });
        },
        updateNavigationState(page = this.d_page) {
            const pageCount = this.snapPoints.size;

            if (!pageCount) {
                this.isPrevDisabled = true;
                this.isNextDisabled = true;

                return;
            }

            if (this.loop) {
                this.isPrevDisabled = false;
                this.isNextDisabled = false;

                return;
            }

            this.isPrevDisabled = page <= 0;
            this.isNextDisabled = page >= pageCount - 1;
        },
        step(dir, page) {
            let totalShiftedItems = this.totalShiftedItems;
            const isCircular = this.isCircular();

            if (page != null) {
                totalShiftedItems = this.d_numScroll * page * -1;

                if (isCircular) {
                    totalShiftedItems -= this.d_numVisible;
                }

                this.isRemainingItemsAdded = false;
            } else {
                totalShiftedItems += this.d_numScroll * dir;

                if (this.isRemainingItemsAdded) {
                    totalShiftedItems += this.remainingItems - this.d_numScroll * dir;
                    this.isRemainingItemsAdded = false;
                }

                let originalShiftedItems = isCircular ? totalShiftedItems + this.d_numVisible : totalShiftedItems;

                page = Math.abs(Math.floor(originalShiftedItems / this.d_numScroll));
            }

            if (isCircular && this.d_page === this.totalIndicators - 1 && dir === -1) {
                totalShiftedItems = -1 * (this.value.length + this.d_numVisible);
                page = 0;
            } else if (isCircular && this.d_page === 0 && dir === 1) {
                totalShiftedItems = 0;
                page = this.totalIndicators - 1;
            } else if (page === this.totalIndicators - 1 && this.remainingItems > 0) {
                totalShiftedItems += this.remainingItems * -1 - this.d_numScroll * dir;
                this.isRemainingItemsAdded = true;
            }

            if (this.$refs.itemsContainer) {
                !this.isUnstyled && removeClass(this.$refs.itemsContainer, 'p-items-hidden');
                this.$refs.itemsContainer.style.transform = this.isVertical() ? `translate3d(0, ${totalShiftedItems * (100 / this.d_numVisible)}%, 0)` : `translate3d(${totalShiftedItems * (100 / this.d_numVisible)}%, 0, 0)`;
                this.$refs.itemsContainer.style.transition = `transform ${TRANSITION_DURATION_MS}ms ease 0s`;
            }

            this.totalShiftedItems = totalShiftedItems;

            this.$emit('update:page', page);
            this.d_page = page;
        },
        calculatePosition() {
            if (this.$refs.itemsContainer && this.responsiveOptions) {
                let windowWidth = window.innerWidth;
                let matchedResponsiveOptionsData = {
                    numVisible: this.numVisible,
                    numScroll: this.numScroll
                };

                for (let i = 0; i < this.responsiveOptions.length; i++) {
                    let res = this.responsiveOptions[i];

                    if (parseInt(res.breakpoint, 10) >= windowWidth) {
                        matchedResponsiveOptionsData = res;
                    }
                }

                if (this.d_numScroll !== matchedResponsiveOptionsData.numScroll) {
                    let page = this.d_page;

                    page = parseInt((page * this.d_numScroll) / matchedResponsiveOptionsData.numScroll);

                    this.totalShiftedItems = matchedResponsiveOptionsData.numScroll * page * -1;

                    if (this.isCircular()) {
                        this.totalShiftedItems -= matchedResponsiveOptionsData.numVisible;
                    }

                    this.d_numScroll = matchedResponsiveOptionsData.numScroll;

                    this.$emit('update:page', page);
                    this.d_page = page;
                }

                if (this.d_numVisible !== matchedResponsiveOptionsData.numVisible) {
                    this.d_numVisible = matchedResponsiveOptionsData.numVisible;
                }
            }
        },
        navBackward(e, index) {
            if (this.d_circular || this.d_page !== 0) {
                this.step(1, index);
            }

            this.allowAutoplay = false;

            if (e.cancelable) {
                e.preventDefault();
            }
        },
        navForward(e, index) {
            if (this.d_circular || this.d_page < this.totalIndicators - 1) {
                this.step(-1, index);
            }

            this.allowAutoplay = false;

            if (e.cancelable) {
                e.preventDefault();
            }
        },
        onIndicatorClick(e, index) {
            let page = this.d_page;

            if (index > page) {
                this.navForward(e, index);
            } else if (index < page) {
                this.navBackward(e, index);
            }
        },
        onTransitionEnd() {
            if (this.$refs.itemsContainer) {
                !this.isUnstyled && addClass(this.$refs.itemsContainer, 'p-items-hidden');
                this.$refs.itemsContainer.style.transition = '';

                if ((this.d_page === 0 || this.d_page === this.totalIndicators - 1) && this.isCircular()) {
                    this.$refs.itemsContainer.style.transform = this.isVertical() ? `translate3d(0, ${this.totalShiftedItems * (100 / this.d_numVisible)}%, 0)` : `translate3d(${this.totalShiftedItems * (100 / this.d_numVisible)}%, 0, 0)`;
                }
            }
        },
        onTouchStart(e) {
            let touchobj = e.changedTouches[0];

            this.startPos = {
                x: touchobj.pageX,
                y: touchobj.pageY
            };
        },
        onTouchMove(e) {
            const touchobj = e.changedTouches[0];
            const diff = this.isVertical() ? touchobj.pageY - this.startPos.y : touchobj.pageX - this.startPos.x;

            if (Math.abs(diff) > SWIPE_THRESHOLD && e.cancelable) {
                e.preventDefault();
            }
        },
        onTouchEnd(e) {
            let touchobj = e.changedTouches[0];

            if (this.isVertical()) {
                this.changePageOnTouch(e, touchobj.pageY - this.startPos.y);
            } else {
                this.changePageOnTouch(e, touchobj.pageX - this.startPos.x);
            }
        },
        changePageOnTouch(e, diff) {
            if (Math.abs(diff) > SWIPE_THRESHOLD) {
                if (diff < 0) {
                    // left
                    this.navForward(e);
                } else {
                    // right
                    this.navBackward(e);
                }
            }
        },
        onIndicatorKeydown(event) {
            switch (event.code) {
                case 'ArrowRight':
                    this.onRightKey();
                    break;

                case 'ArrowLeft':
                    this.onLeftKey();
                    break;

                case 'Home':
                    this.onHomeKey();
                    event.preventDefault();
                    break;

                case 'End':
                    this.onEndKey();
                    event.preventDefault();
                    break;

                case 'ArrowUp':
                case 'ArrowDown':
                case 'PageUp':
                case 'PageDown':
                    event.preventDefault();
                    break;

                case 'Tab':
                    this.onTabKey();
                    break;

                default:
                    break;
            }
        },
        onRightKey() {
            const indicators = [...find(this.$refs.indicatorContent, '[data-pc-section="indicator"]')];
            const activeIndex = this.findFocusedIndicatorIndex();

            this.changedFocusedIndicator(activeIndex, activeIndex + 1 === indicators.length ? indicators.length - 1 : activeIndex + 1);
        },
        onLeftKey() {
            const activeIndex = this.findFocusedIndicatorIndex();

            this.changedFocusedIndicator(activeIndex, activeIndex - 1 <= 0 ? 0 : activeIndex - 1);
        },
        onHomeKey() {
            const activeIndex = this.findFocusedIndicatorIndex();

            this.changedFocusedIndicator(activeIndex, 0);
        },
        onEndKey() {
            const indicators = [...find(this.$refs.indicatorContent, '[data-pc-section="indicator"]')];
            const activeIndex = this.findFocusedIndicatorIndex();

            this.changedFocusedIndicator(activeIndex, indicators.length - 1);
        },
        onTabKey() {
            const indicators = [...find(this.$refs.indicatorContent, '[data-pc-section="indicator"]')];
            const highlightedIndex = indicators.findIndex((ind) => getAttribute(ind, 'data-p-active') === true);

            const activeIndicator = findSingle(this.$refs.indicatorContent, '[data-pc-section="indicator"] > button[tabindex="0"]');
            const activeIndex = indicators.findIndex((ind) => ind === activeIndicator.parentElement);

            indicators[activeIndex].children[0].tabIndex = '-1';
            indicators[highlightedIndex].children[0].tabIndex = '0';
        },
        findFocusedIndicatorIndex() {
            const indicators = [...find(this.$refs.indicatorContent, '[data-pc-section="indicator"]')];
            const activeIndicator = findSingle(this.$refs.indicatorContent, '[data-pc-section="indicator"] > button[tabindex="0"]');

            return indicators.findIndex((ind) => ind === activeIndicator.parentElement);
        },
        changedFocusedIndicator(prevInd, nextInd) {
            const indicators = [...find(this.$refs.indicatorContent, '[data-pc-section="indicator"]')];

            indicators[prevInd].children[0].tabIndex = '-1';
            indicators[nextInd].children[0].tabIndex = '0';
            indicators[nextInd].children[0].focus();
        },
        bindDocumentListeners() {
            if (!this.documentResizeListener) {
                this.documentResizeListener = (e) => {
                    this.calculatePosition(e);
                };

                window.addEventListener('resize', this.documentResizeListener);
            }
        },
        unbindDocumentListeners() {
            if (this.documentResizeListener) {
                window.removeEventListener('resize', this.documentResizeListener);
                this.documentResizeListener = null;
            }
        },
        startAutoplay() {
            this.interval = setInterval(() => {
                if (this.d_page === this.totalIndicators - 1) {
                    this.step(-1, 0);
                } else {
                    this.step(-1, this.d_page + 1);
                }
            }, this.autoplayInterval);
        },
        stopAutoplay() {
            if (this.interval) {
                clearInterval(this.interval);
                this.interval = null;
            }
        },
        createStyle() {
            if (!this.carouselStyle) {
                this.carouselStyle = document.createElement('style');
                this.carouselStyle.type = 'text/css';
                setAttribute(this.carouselStyle, 'nonce', this.$primevue?.config?.csp?.nonce);
                document.body.appendChild(this.carouselStyle);
            }

            let innerHTML = `
                .p-carousel[${this.$attrSelector}] .p-carousel-item {
                    flex: 1 0 ${100 / this.d_numVisible}%
                }
            `;

            if (this.responsiveOptions && !this.isUnstyled) {
                let _responsiveOptions = [...this.responsiveOptions];
                const comparer = localeComparator();

                _responsiveOptions.sort((data1, data2) => {
                    const value1 = data1.breakpoint;
                    const value2 = data2.breakpoint;

                    return sort(value1, value2, -1, comparer);
                });

                for (let i = 0; i < _responsiveOptions.length; i++) {
                    let res = _responsiveOptions[i];

                    innerHTML += `
                        @media screen and (max-width: ${res.breakpoint}) {
                            .p-carousel[${this.$attrSelector}] .p-carousel-item {
                                flex: 1 0 ${100 / res.numVisible}%
                            }
                        }
                    `;
                }
            }

            this.carouselStyle.innerHTML = innerHTML;
        },
        isVertical() {
            return this.orientation === 'vertical';
        },
        hasValidItemCount() {
            return this.value && this.value.length > this.d_numVisible;
        },
        isCircular() {
            return this.hasValidItemCount() && this.d_circular;
        },
        isAutoplay() {
            return this.hasValidItemCount() && this.autoplayInterval && this.allowAutoplay;
        },
        firstIndex() {
            return this.isCircular() ? -1 * (this.totalShiftedItems + this.d_numVisible) : this.totalShiftedItems * -1;
        },
        lastIndex() {
            return this.firstIndex() + this.d_numVisible - 1;
        },
        ariaSlideNumber(value) {
            return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.slideNumber.replace(/{slideNumber}/g, value) : undefined;
        },
        ariaPageLabel(value) {
            return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.pageLabel.replace(/{page}/g, value) : undefined;
        },
        resolveSnapType() {
            const axis = this.orientation === 'vertical' ? 'y' : 'x';

            return `${axis} ${this.snapType ?? 'mandatory'}`;
        },
        areSetsEqual(a, b) {
            if (a.size !== b.size) return false;

            for (const value of a) {
                if (!b.has(value)) return false;
            }

            return true;
        },
        observeResizeItems() {
            if (!this.resizeObserver) return;
            this.contentEl.querySelectorAll('[data-pc-name="carouselitem"]').forEach((item) => this.resizeObserver.observe(item));
        },
        observeIntersectionItems() {
            if (!this.intersectionObserver) return;
            this.contentEl.querySelectorAll('[data-pc-name="carouselitem"]').forEach((item) => this.intersectionObserver.observe(item));
        },
        computeSnapPoints() {
            const content = this.contentEl;
            const isHorizontal = this.orientation !== 'vertical';
            const trackSize = isHorizontal ? content.clientWidth : content.clientHeight;
            const maxOffset = Math.max(0, isHorizontal ? content.scrollWidth - trackSize : content.scrollHeight - trackSize);
            const snaps = [];

            content.querySelectorAll('[data-pc-name="carouselitem"]').forEach((item) => {
                const offset = isHorizontal ? item.offsetLeft : item.offsetTop;
                const size = isHorizontal ? item.clientWidth : item.clientHeight;

                let snapPoint = offset;

                if (this.align === 'center') {
                    snapPoint = offset - (trackSize - size) / 2;
                } else if (this.align === 'end') {
                    snapPoint = offset - (trackSize - size);
                }

                const clamped = Math.max(0, Math.min(snapPoint, maxOffset));

                snaps.push(clamped);
            });

            const newSnapPoints = new Set(snaps.map(Number));

            if (this.areSetsEqual(this.snapPoints, newSnapPoints)) return;

            this.snapPoints = newSnapPoints;
            this.scrollSnaps = snaps;
        },
        setPage(page, slideOverride = null) {
            this.updateNavigationState(page);

            this.d_page = page;

            this.$emit('update:page', page);

            const snap = Array.from(this.snapPoints)[page];
            const slide = slideOverride ?? this.scrollSnaps.indexOf(snap);

            if (slide != null && slide !== -1) {
                this.$emit('update:slide', slide);
            }
        },
        setToClosest() {
            if (this.snapPoints.size === 0) return;

            const scrollPos = this.orientation === 'horizontal' ? this.contentEl.scrollLeft : this.contentEl.scrollTop;

            const closestSnapPoint = Array.from(this.snapPoints).reduce((closest, point) => {
                return Math.abs(point - scrollPos) < Math.abs(closest - scrollPos) ? point : closest;
            }, Infinity);

            const index = Array.from(this.snapPoints).indexOf(closestSnapPoint);

            this.setPage(index);

            return index;
        },
        scrollToPage(page, instant = false) {
            if (this.snapPoints.size === 0) return;

            const target = page ?? this.d_page;
            const clampedPage = this.loop ? (target + this.snapPoints.size) % this.snapPoints.size : Math.max(0, Math.min(target, this.snapPoints.size - 1));

            this.setPage(clampedPage);
            this.scrollToInternal(Array.from(this.snapPoints)[clampedPage], instant);
        },
        next() {
            this.scrollToPage(this.d_page + 1);
        },
        prev() {
            this.scrollToPage(this.d_page - 1);
        },
        scrollToInternal(snapPoint, instant = false) {
            this.contentEl.scrollTo({
                [this.orientation === 'horizontal' ? 'left' : 'top']: snapPoint,
                behavior: instant ? 'instant' : 'smooth'
            });
        },
        scrollToSlide(slide, instant = false) {
            if (this.snapPoints.size === 0 || this.scrollSnaps.length === 0) return;

            const clampedSlide = Math.max(0, Math.min(slide, this.scrollSnaps.length - 1));
            const snap = this.scrollSnaps[clampedSlide];

            this.scrollToInternal(snap, instant);

            const page = Array.from(this.snapPoints).indexOf(snap);

            this.setPage(page, clampedSlide);
        },
        onContentPointerDown(e) {
            if (e.button !== 0) return;
            if (e.pointerType === 'touch') return;

            this.swiping = true;
            this.swipeStartPoint = { x: e.clientX, y: e.clientY };
            this.isRealSwipe = false;
        },
        onContentPointerMove(e) {
            if (!this.swiping || e.pointerType === 'touch') return;

            const deltaX = e.clientX - this.swipeStartPoint.x;
            const deltaY = e.clientY - this.swipeStartPoint.y;
            const distance = Math.abs(deltaX) + Math.abs(deltaY);

            if (distance < POINTER_SWIPE_DISTANCE) return;
            if ((window.getSelection()?.toString().length ?? 0) > 0) return;

            e.currentTarget.setPointerCapture(e.pointerId);

            this.contentEl.style.userSelect = 'none';
            this.isRealSwipe = true;
            this.contentEl.style.scrollSnapType = 'none';
            this.contentEl.scrollBy({
                left: -e.movementX,
                top: -e.movementY,
                behavior: 'instant'
            });

            e.preventDefault();
        },
        onContentPointerUp(e) {
            this.swiping = false;

            if (e.currentTarget.hasPointerCapture?.(e.pointerId)) {
                e.currentTarget.releasePointerCapture(e.pointerId);
            }

            if (!this.isRealSwipe) return;

            this.contentEl.style.userSelect = '';

            const scrollPos = this.orientation === 'horizontal' ? this.contentEl.scrollLeft : this.contentEl.scrollTop;
            const points = this.snapPoints;

            if (points.size === 0) return;

            const closestSnapPoint = Array.from(points).reduce((closest, point) => {
                return Math.abs(point - scrollPos) < Math.abs(closest - scrollPos) ? point : closest;
            }, Infinity);

            const index = Array.from(points).indexOf(closestSnapPoint);

            requestAnimationFrame(() => {
                if (closestSnapPoint !== undefined) this.scrollToPage(index);

                requestAnimationFrame(() => {
                    this.contentEl.style.scrollSnapType = this.resolveSnapType();
                });
            });
        },
        onContentWheel(e) {
            if (this.wheelTimeout) clearTimeout(this.wheelTimeout);

            this.wheelTimeout = setTimeout(() => {
                const primaryDelta = this.orientation === 'horizontal' ? e.deltaX || e.deltaY : e.deltaY || e.deltaX;

                if (primaryDelta > 0 && this.isNextDisabled) return;
                if (primaryDelta < 0 && this.isPrevDisabled) return;

                this.setToClosest();
            }, WHEEL_DEBOUNCE_MS);
        },
        setContentEl(el) {
            this.contentEl = isElement(el) ? el : null;
        },
        bindResizeObserver() {
            this.resizeObserver = new ResizeObserver(() => {
                if (!this.contentEl) return;

                this.computeSnapPoints();
                const closest = this.setToClosest();

                this.scrollToPage(closest ?? this.d_page, true);
            });

            this.resizeObserver.observe(this.contentEl);
            this.observeResizeItems();
        },
        unbindResizeObserver() {
            if (this.resizeObserver) {
                this.resizeObserver.disconnect();
                this.resizeObserver = null;
            }
        },
        bindMutationObserver() {
            this.mutationObserver = new MutationObserver(() => {
                if (!this.contentEl) return;

                this.computeSnapPoints();
                this.observeResizeItems();
                this.observeIntersectionItems();
                requestAnimationFrame(() => {
                    if (!this.contentEl) return;

                    const closest = this.setToClosest();

                    this.scrollToPage(closest ?? this.d_page, true);
                });
            });

            this.mutationObserver.observe(this.contentEl, { childList: true, subtree: true });
        },
        unbindMutationObserver() {
            if (this.mutationObserver) {
                this.mutationObserver.disconnect();
                this.mutationObserver = null;
            }
        },
        bindIntersectionObserver() {
            this.intersectionObserver = new IntersectionObserver(
                (entries) => {
                    entries.forEach((entry) => {
                        entry.target.setAttribute('data-inview', entry.isIntersecting ? 'true' : 'false');
                        entry.target.setAttribute('aria-hidden', entry.isIntersecting ? 'false' : 'true');
                    });
                },
                {
                    root: this.contentEl,
                    threshold: INTERSECTION_THRESHOLD
                }
            );

            this.observeIntersectionItems();
        },
        unbindIntersectionObserver() {
            if (this.intersectionObserver) {
                this.intersectionObserver.disconnect();
                this.intersectionObserver = null;
            }
        },
        bindContentScrollListener() {
            this.onScrollHandler = () => {
                if (this.scrollTimeout) clearTimeout(this.scrollTimeout);
                this.scrollTimeout = setTimeout(() => {
                    this.setToClosest();
                }, SCROLL_DEBOUNCE_MS);
            };

            this.contentEl.addEventListener('scroll', this.onScrollHandler, { passive: true });
        },
        unbindContentScrollListener() {
            if (this.scrollTimeout) {
                clearTimeout(this.scrollTimeout);
                this.scrollTimeout = null;
            }

            if (this.wheelTimeout) {
                clearTimeout(this.wheelTimeout);
                this.wheelTimeout = null;
            }

            if (this.contentEl && this.onScrollHandler) {
                this.contentEl.removeEventListener('scroll', this.onScrollHandler);
            }

            this.onScrollHandler = null;
        }
    },
    computed: {
        hasCarouselValue() {
            return !this.$slots.default;
        },
        totalIndicators() {
            return this.value ? Math.max(Math.ceil((this.value.length - this.d_numVisible) / this.d_numScroll) + 1, 0) : 0;
        },
        backwardIsDisabled() {
            return this.value && (!this.circular || this.value.length < this.d_numVisible) && this.d_page === 0;
        },
        forwardIsDisabled() {
            return this.value && (!this.circular || this.value.length < this.d_numVisible) && (this.d_page === this.totalIndicators - 1 || this.totalIndicators === 0);
        },
        ariaSlideLabel() {
            return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.slide : undefined;
        },
        ariaPrevButtonLabel() {
            return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.prevPageLabel : undefined;
        },
        ariaNextButtonLabel() {
            return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.nextPageLabel : undefined;
        },
        empty() {
            return !this.value || this.value.length === 0;
        },
        emptyMessageText() {
            return this.$primevue.config?.locale?.emptyMessage || '';
        }
    },
    components: {
        Button,
        ChevronRight,
        ChevronDown,
        ChevronLeft,
        ChevronUp
    },
    directives: {
        ripple: Ripple
    }
};
</script>
