(function ($) {
    'use strict';
    /*let haveOptions = false;
    if ($('#product_form_options')) {
        $('#product_form_options')[0].addEventListener('DOMNodeInserted', function () {
            let firstElementId = $('#product_form_options')[0].children[0].id;
            if (firstElementId !== "undefined") {
                console.log(firstElementId);
                haveOptions = true;
            }
        })
    };*/


    var DynamicCollection = function ($container) {
        this.$container = $container;
        this.$index = this.$container.find(':input').length;
        this.$container.on('click', '[data-collection-adder]', this.onAdderClicked.bind(this));
        this.$container.on('click', '[data-collection-remover]', this.onRemoverClicked.bind(this));
    };

    DynamicCollection.prototype = {
        onAdderClicked: function (e) {
            e.preventDefault();

            this.$container.append($(this.$container.data('prototype').replace(/__name__/g, this.$index)));
            this.$index++;
        },
        onRemoverClicked: function (e) {
            e.preventDefault();

            $(e.target).parents('[data-collection-row]:first').remove();
            this.$index--;
        }
    };

    $.fn.dynamicForm = function () {
        return this.each(function () {
            new DynamicCollection($(this));
        });
    };

    $(function () {
        $('[data-prototype]').dynamicForm();
    });

    $('.multiple-collection').collection({
        'preserve_names': false,
        'add': '<a href="#" class="btn btn-success btn-rounded">Ajouter</a>',
        'add_at_the_end': true,
        after_add: function (collection, element) {
            initSelect2($(element[0].querySelectorAll('.select2')));
        },
    });

    $('.disable-country-collection').collection({
        'preserve_names': false,
        'add': '<a href="#" class="btn btn-success btn-rounded">Ajouter</a>',
        'add_at_the_end': true,
        after_add: function (collection, element) {
            initSelect2($(element[0].querySelectorAll('.select2')));
            let trumbowyg = $(element[0]).find('.trumbowyg');
            $.each(trumbowyg, function (key, value) {
                $(value).trumbowyg({
                    lang: 'fr',
                    svgPath: '/bundles/cpcreationviticore/fonts/icons.svg',
                    btns: [
                        ['viewHTML'],
                        ['undo', 'redo'], // Only supported in Blink browsers
                        ['formatting'],
                        ['strong', 'em', 'del'],
                        ['superscript', 'subscript'],
                        ['link'],
                        ['removeformat'],
                        ['fullscreen']
                    ]

                });
            });
        },
    });

    function syncVariantDefaultCheckbox(collection, element) {
        var variantCount = collection.find('> div, > fieldset').length;
        var byDefaultCheckbox = $(element).find('input[type="checkbox"][id$="_byDefault"]');

        if (byDefaultCheckbox.length) {
            byDefaultCheckbox.prop('checked', variantCount === 1);
        }
    }

    function getVariantElements(collection) {
        return collection.find('> div, > fieldset');
    }

    function getVariantPreferredElement(collection, preferredElement) {
        var elements = getVariantElements(collection);

        if (preferredElement) {
            var preferred = $(preferredElement);

            if (preferred.length && elements.index(preferred.first()) !== -1) {
                return preferred;
            }
        }

        var expandedElement = elements.filter(function () {
            return $(this).find('[data-variant-collapse]').first().hasClass('in');
        }).first();

        return expandedElement.length ? expandedElement : elements.first();
    }

    function getVariantTitle(element, index) {
        var selectedType = $.trim($(element).find('select[id$="_type"] option:selected').text());

        if (selectedType) {
            return selectedType;
        }

        return 'Variant ' + (index + 1);
    }

    function syncVariantChevron(element) {
        var toggle = $(element).find('.product-variant-toggle').first();
        var collapse = $(element).find('[data-variant-collapse]').first();
        var chevron = toggle.find('[data-variant-chevron]').first();

        if (!toggle.length || !collapse.length || !chevron.length) {
            return;
        }

        var isExpanded = toggle.attr('aria-expanded') === 'true' || (!toggle.hasClass('collapsed') && collapse.hasClass('in'));

        setVariantChevronState(element, isExpanded);
    }

    function setVariantChevronState(element, isExpanded) {
        var toggle = $(element).find('.product-variant-toggle').first();
        var chevron = toggle.find('[data-variant-chevron]').first();

        if (!toggle.length || !chevron.length) {
            return;
        }

        if (isExpanded) {
            toggle.removeClass('collapsed').attr('aria-expanded', 'true');
            chevron.removeClass('fa-chevron-right').addClass('fa-chevron-down');
        } else {
            toggle.addClass('collapsed').attr('aria-expanded', 'false');
            chevron.removeClass('fa-chevron-down').addClass('fa-chevron-right');
        }
    }

    function syncVariantPanels(collection, preferredElement) {
        var elements = getVariantElements(collection);

        if (!elements.length) {
            return;
        }

        var activeElement = getVariantPreferredElement(collection, preferredElement);

        elements.each(function (index) {
            var element = $(this);
            var collapse = element.find('[data-variant-collapse]').first();

            element.find('[data-variant-title]').first().text(getVariantTitle(element, index));

            if (!collapse.length) {
                return;
            }

            if (elements.length === 1 || element.is(activeElement)) {
                collapse.collapse('show');
            } else {
                collapse.collapse('hide');
            }

            syncVariantChevron(element);
        });
    }

    $('.variant-collection').collection({
        preserve_names: false,
        add: '<a href="#" class="btn btn-default">Ajouter</a>',
        position_field_selector: '.position-form',
        add_at_the_end: true,
        after_init: function (collection) {
            syncVariantPanels(collection);
        },
        after_add: function (collection, element) {
            syncVariantDefaultCheckbox(collection, element);
            syncVariantPanels(collection, element);
        },
        after_up: function (collection, element) {
            syncVariantPanels(collection, element);
        },
        after_down: function (collection, element) {
            syncVariantPanels(collection, element);
        },
        after_remove: function (collection) {
            syncVariantPanels(collection);
        }
    });

    $(document).on('change', '.variant-collection select[id$="_type"]', function () {
        syncVariantPanels($(this).closest('.variant-collection'), $(this).closest('.product-variant-panel'));
    });

    $(document).on('click', '.variant-collection .product-variant-toggle', function () {
        var panel = $(this).closest('.product-variant-panel');
        var shouldExpand = $(this).hasClass('collapsed');

        setVariantChevronState(panel, shouldExpand);

        window.setTimeout(function () {
            syncVariantChevron(panel);
        }, 30);
    });

    $(document).on('show.bs.collapse shown.bs.collapse', '.variant-collection [data-variant-collapse]', function () {
        setVariantChevronState($(this).closest('.product-variant-panel'), true);
    });

    $(document).on('hide.bs.collapse hidden.bs.collapse', '.variant-collection [data-variant-collapse]', function () {
        setVariantChevronState($(this).closest('.product-variant-panel'), false);
    });

    $('.room-collection').collection({
        add: '<a href="#" class="btn btn-default">Ajouter</a>',
        add_at_the_end: true,
        children: [{
            selector: '.image-collection',
            min: 1,
            add: '<a href="#" class="btn btn-default">Ajouter</span></a>'
        }],
        after_add: function (collection, element) {
            let trumbowyg = $(element[0]).find('.trumbowyg');
            $.each(trumbowyg, function (key, value) {
                $(value).trumbowyg({
                    lang: 'fr',
                    svgPath: '/bundles/cpcreationviticore/fonts/icons.svg',
                    btns: [
                        ['viewHTML'],
                        ['undo', 'redo'], // Only supported in Blink browsers
                        ['formatting'],
                        ['strong', 'em', 'del'],
                        ['superscript', 'subscript'],
                        ['link'],
                        ['removeformat'],
                        ['fullscreen']
                    ]

                });
            });
        },
    });
    $('.assemblage-collection').collection({

        'add': '<a href="#" class="btn btn-default">Ajouter</a>',
        'add_at_the_end': true
    });

    $('.image-collection').collection({

        'add': '<a href="#" class="btn btn-default">Ajouter</a>',
        'position_field_selector': '.position-form',
        'add_at_the_end': true
    });
})($);
    function initSelect2($elements) {
        $elements.each(function () {
            let $element = $(this);
            let options = {};
            let placeholder = $element.data('placeholder') || $element.attr('placeholder');
            let allowClear = $element.data('allow-clear');

            if (placeholder) {
                options.placeholder = placeholder;
            }

            if (allowClear === true || allowClear === 'true' || allowClear === 1 || allowClear === '1') {
                options.allowClear = true;
            }

            $element.select2(options);
        });
    }
