(function() {
    function init() {
        $('.card[stag-collapsible-card]:not([stag-collapsible-card-initialized])').each(function() {
            let header = $(this).find('>.card-header').first();
            if(header.length) {
                let html = header.html();
                let newHeader = $('<div class="d-flex align-items-center"></div>');
                newHeader.append(html);
                let collapseTrigger = $('<a href="#" class="stag-collapse-trigger ml-auto" />');
                collapseTrigger.append('<i class="fa fa-chevron-up if-not-collapsed"/>');
                collapseTrigger.append('<i class="fa fa-chevron-down if-collapsed"/>');
                newHeader.append(collapseTrigger);
                header
                    .empty()
                    .append(newHeader);
            }
            if(!!$(this).attr('stag-collapsible-card')) {
                let state = localStorage['collapseState_' + $(this).attr('stag-collapsible-card')];
                if(state === 'collapsed') {
                    $(this).attr('collapsed', 1);
                }
                else if(state === 'not-collapsed') {
                    $(this).removeAttr('collapsed');
                }
            }
            $(this).attr('stag-collapsible-card-initialized', 1);
        });

        $(document)
            .off('click.stag-collapse-toggle', '.card[stag-collapsible-card][stag-collapsible-card-initialized] .stag-collapse-trigger')
            .on('click.stag-collapse-toggle', '.card[stag-collapsible-card][stag-collapsible-card-initialized] .stag-collapse-trigger', function() {
                let card = $(this).closest('.card');
                if(card.is('[collapsed]')) {
                    card.removeAttr('collapsed');
                    if(!!card.attr('stag-collapsible-card')) {
                        localStorage['collapseState_' + card.attr('stag-collapsible-card')] = 'not-collapsed';
                    }
                }
                else {
                    card.attr('collapsed', 1);
                    if(!!card.attr('stag-collapsible-card')) {
                        localStorage['collapseState_' + card.attr('stag-collapsible-card')] = 'collapsed';
                    }
                }
                return false;
            });
    }
    addMCInitializer('stag-collapsible-card', init);
}).call(window);