class CardsSwap {
    static selectors = {
        root: '.cards-swap',
        card: '.cards-swap__card',
        toggle: '.cards-swap__toggle',
        activeCard: '.cards-swap__card.active',
    };

    static classes = {
        static: 'static',
        active: 'active',
    };

    constructor(element) {
        this.element = element;
        this.cards = this.element.querySelectorAll(CardsSwap.selectors.card);
        this.toggles = this.element.querySelectorAll(CardsSwap.selectors.toggle);
        this.init();
    }

    init() {
        if (this.cards.length !== 2 || this.toggles.length !== 2) return;
        this.cards.forEach((card) => {
            card.classList.remove(CardsSwap.classes.static);
        });
        this.attachToggleListeners();
        this.updateHeight();

        window.addEventListener(
            'resize',
            _.debounce(() => {
                this.updateHeight();
            }, 250)
        );
    }

    attachToggleListeners() {
        this.toggles.forEach((toggle) => {
            toggle.addEventListener('click', () => {
                this.toggleCards();
            });
        });
    }

    toggleCards() {
        this.cards.forEach((card) => {
            card.classList.toggle(CardsSwap.classes.active);
        });
        this.animateHeight();
    }

    updateHeight() {
        const activeCard = this.element.querySelector(CardsSwap.selectors.activeCard);
        if (activeCard) {
            this.element.style.transition = 'none';
            this.element.style.height = activeCard.offsetHeight + 'px';
        }
    }

    animateHeight() {
        const activeCard = this.element.querySelector(CardsSwap.selectors.activeCard);
        if (activeCard) {
            this.element.style.transition = 'height 0.5s linear';
            this.element.style.height = activeCard.offsetHeight + 'px';
        }
    }
}

$(document).ready(function () {
    const cardsSwapElements = document.querySelectorAll(CardsSwap.selectors.root);
    cardsSwapElements.forEach((element) => {
        new CardsSwap(element);
    });
});
