(function () {
    'use strict';

    function whenReady(callback) {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', callback);
            return;
        }
        callback();
    }

    function createController() {
        var state = {
            cards: [],
            observer: null
        };

        function animationDelayFor(index) {
            return (index % 3) * 0.1;
        }

        function revealCard(card) {
            var delay = parseFloat(card.dataset.animationDelay) || 0;
            setTimeout(function () {
                card.classList.remove('card-hidden');
                card.classList.add('card-visible');
            }, delay * 1000);
        }

        function observeVisibleCards(entries) {
            entries.forEach(function (entry) {
                if (!entry.isIntersecting) {
                    return;
                }

                revealCard(entry.target);
                if (state.observer) {
                    state.observer.unobserve(entry.target);
                }
            });
        }

        function buildObserver() {
            state.observer = new IntersectionObserver(observeVisibleCards, {
                root: null,
                rootMargin: '50px',
                threshold: 0.1
            });
        }

        function resetCards() {
            state.cards.forEach(function (card, index) {
                card.style.animation = 'none';
                card.classList.add('card-hidden');
                card.dataset.animationDelay = animationDelayFor(index);
            });
        }

        function observeCards() {
            if (!state.observer) {
                return;
            }
            state.cards.forEach(function (card) {
                state.observer.observe(card);
            });
        }

        function setup() {
            state.cards = Array.prototype.slice.call(document.querySelectorAll('.post-card'));
            if (!state.cards.length) {
                return;
            }

            buildObserver();
            resetCards();
            observeCards();
        }

        return {
            setup: setup,
            animateAllCards: function () {
                state.cards.forEach(function (card, index) {
                    setTimeout(function () {
                        card.classList.remove('card-hidden');
                        card.classList.add('card-visible');
                    }, index * 100);
                });
            }
        };
    }

    var controller = createController();
    whenReady(controller.setup);
    window.nxtEventPlannerCardAnimationController = controller;
})();
