import anime from 'animejs';

class TextRotator {
    constructor(container, options = {}) {
        this.container = container;

        const defaultOptions = {
            itemsSelector: '.textRotator_item',
            currentClass: 'textRotator_item--current',
            firstClass: 'textRotator_item--first',
            interval: 4000,
            initIndex: 0
        };

        this.options = {...defaultOptions, ...options};

        this.items = this.container.querySelectorAll(this.options.itemsSelector);
        this.currentIndex = this.options.initIndex;
        this.maxIndex = this.items.length;

        if (this.maxIndex > 1) {
            setTimeout(() => {
                this.animateNext();
            }, this.options.interval);
        }
    }

    animateNext () {
        this.currentIndex = (this.currentIndex === this.maxIndex - 1) ? 0 : this.currentIndex + 1;
        let outItem = this.container.querySelector('.' + this.options.currentClass);
        let inItem = this.container.querySelector('[data-item="' + this.currentIndex + '"]');
        let newHeight = inItem.getBoundingClientRect().height;
        
        const TL = anime.timeline({ easing: 'easeInOutCubic' });

        TL.add({
            targets: outItem,
            translateY: [0, '-60%'],
            translateZ: 0,
            opacity: [1, 0],
            duration: 400,
            begin: () => {
                outItem.classList.remove(this.options.currentClass);
                outItem.classList.remove(this.options.firstClass);
            }
        });

        TL.add({
            targets: this.container,
            height: newHeight,
            duration: 400
        }, '-=100');

        TL.add({
            targets: inItem,
            translateY: ['60%','0%'],
            translateZ: 0,
            opacity: [0,1],
            duration: 600,
            easing: 'easeOutExpo',
            complete: () => {
                inItem.classList.add(this.options.currentClass);
                setTimeout(() => {
                    this.animateNext();
                }, this.options.interval);
            }
        });
    }
}

export default TextRotator;