(function ($, window) {
    'use strict';

    var cfg =
        typeof window.zertiInvImportExport === 'object' && window.zertiInvImportExport !== null
            ? window.zertiInvImportExport
            : {};

    function parseUrlQuery(url) {
        var out = {};
        try {
            var u = new URL(url, window.location.origin);
            u.searchParams.forEach(function (val, key) {
                out[key] = val;
            });
        } catch (e) {
            /* ignore */
        }
        return out;
    }

    function buildZertiExportDownloadUrl(wcUrl) {
        var base = cfg.exportDownloadBase || '';
        if (!base) {
            return wcUrl;
        }
        var q = parseUrlQuery(wcUrl);
        var parts = [];
        ['action', 'nonce', 'filename'].forEach(function (key) {
            if (q[key]) {
                parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(q[key]));
            }
        });
        if (!parts.length) {
            return wcUrl;
        }
        return base + (base.indexOf('?') === -1 ? '?' : '&') + parts.join('&');
    }

    function bindAdvancedImportToggle(root) {
        $(root)
            .find('.woocommerce-importer-toggle-advanced-options')
            .off('click.zertiInvIe')
            .on('click.zertiInvIe', function (e) {
                e.preventDefault();
                var $link = $(this);
                var $rows = $(root).find('.woocommerce-importer-advanced');
                if ($rows.hasClass('hidden')) {
                    $rows.removeClass('hidden');
                    $link.text($link.data('hidetext') || '');
                } else {
                    $rows.addClass('hidden');
                    $link.text($link.data('showtext') || '');
                }
            });
    }

    function isInvIeNarrowViewport() {
        return window.matchMedia('(max-width: 991.98px)').matches;
    }

    function fitSelect2ToParent($el) {
        var instance = $el.data('select2');
        if (!instance || !instance.$container) {
            return;
        }
        if (!isInvIeNarrowViewport()) {
            instance.$container.css({ width: '', maxWidth: '' });
            return;
        }
        instance.$container.css({
            width: '100%',
            maxWidth: '100%',
        });
    }

    function fitSelect2Dropdown($el) {
        if (!isInvIeNarrowViewport()) {
            return;
        }
        var instance = $el.data('select2');
        if (!instance || !instance.$dropdown || !instance.$container) {
            return;
        }
        var rect = instance.$container[0].getBoundingClientRect();
        var gutter = 10;
        var maxW = window.innerWidth - gutter * 2;
        var width = Math.min(Math.max(rect.width, 0), maxW);
        var left = rect.left;
        if (left + width > window.innerWidth - gutter) {
            left = window.innerWidth - gutter - width;
        }
        if (left < gutter) {
            left = gutter;
            width = Math.min(width, maxW);
        }
        instance.$dropdown.css({
            position: 'fixed',
            top: Math.round(rect.bottom + 2) + 'px',
            left: Math.round(left) + 'px',
            width: Math.round(width) + 'px',
            maxWidth: Math.round(maxW) + 'px',
            right: 'auto',
            bottom: 'auto',
            boxSizing: 'border-box',
            zIndex: 100100,
        });
    }

    function bindSelect2ResponsiveFit($el) {
        $el.off('select2:open.zertiInvIeFit');
        $el.on('select2:open.zertiInvIeFit', function () {
            fitSelect2ToParent($el);
            var reposition = function () {
                fitSelect2Dropdown($el);
            };
            window.requestAnimationFrame(function () {
                reposition();
                window.requestAnimationFrame(reposition);
            });
        });
        fitSelect2ToParent($el);
    }

    function bindSelect2ResponsiveResize() {
        if (window.zertiInvIeSelect2ResizeBound) {
            return;
        }
        window.zertiInvIeSelect2ResizeBound = true;
        $(window).on('resize.zertiInvIeFit', function () {
            $('.zerti-component-inventory-import-export .wc-enhanced-select').each(function () {
                var $el = $(this);
                fitSelect2ToParent($el);
                var instance = $el.data('select2');
                if (instance && instance.isOpen && instance.isOpen()) {
                    fitSelect2Dropdown($el);
                }
            });
        });
    }

    function syncExportCheckboxPicker($picker) {
        if (!$picker || !$picker.length) {
            return;
        }
        var syncSelector = $picker.attr('data-sync-select');
        if (!syncSelector) {
            return;
        }
        var $sync = $picker.closest('td').find(syncSelector);
        if (!$sync.length) {
            return;
        }
        var selected = [];
        $picker.find('.zerti-inv-ie-checkbox-picker__check:checked').each(function () {
            selected.push(String(this.value || ''));
        });
        $sync.find('option').each(function () {
            var $opt = $(this);
            $opt.prop('selected', selected.indexOf(String($opt.val() || '')) !== -1);
        });
        $sync.trigger('change');
    }

    function initExportCheckboxPickers(root) {
        $(root)
            .find('.zerti-inv-ie-checkbox-picker')
            .each(function () {
                var $picker = $(this);
                if ($picker.data('zertiCheckboxPicker')) {
                    return;
                }
                $picker.data('zertiCheckboxPicker', 1);

                $picker.on('change.zertiInvIeCheckbox', '.zerti-inv-ie-checkbox-picker__check', function () {
                    syncExportCheckboxPicker($picker);
                });

                $picker.find('.zerti-inv-ie-checkbox-picker__select-all').on('click.zertiInvIeCheckbox', function (e) {
                    e.preventDefault();
                    $picker.find('.zerti-inv-ie-checkbox-picker__check').prop('checked', true);
                    syncExportCheckboxPicker($picker);
                });

                $picker.find('.zerti-inv-ie-checkbox-picker__clear-all').on('click.zertiInvIeCheckbox', function (e) {
                    e.preventDefault();
                    $picker.find('.zerti-inv-ie-checkbox-picker__check').prop('checked', false);
                    syncExportCheckboxPicker($picker);
                });

                syncExportCheckboxPicker($picker);
            });
    }

    function initEnhancedSelect(root, attempt) {
        attempt = attempt || 0;
        var $root = $(root);
        var $selects = $root
            .find('.wc-enhanced-select')
            .not('.woocommerce-exporter-columns, .woocommerce-exporter-types, .woocommerce-exporter-category');
        if (!$selects.length) {
            return;
        }
        if (typeof $.fn.selectWoo !== 'function') {
            if (attempt < 40) {
                window.setTimeout(function () {
                    initEnhancedSelect(root, attempt + 1);
                }, 50);
            }
            return;
        }
        bindSelect2ResponsiveResize();
        $selects.each(function () {
            var $el = $(this);
            if ($el.data('select2')) {
                $el.selectWoo('destroy');
            }
            $el.addClass('zerti-admin-select');
            $el.selectWoo({
                width: '100%',
                allowClear: !$el.prop('multiple'),
                placeholder: $el.data('placeholder') || '',
                dropdownParent: $(document.body),
                containerCssClass: 'zerti-admin-select2',
                dropdownCssClass: 'zerti-admin-select2-dropdown',
                selectionCssClass: 'zerti-admin-select2-selection',
            });
            $el.addClass('enhanced');
            bindSelect2ResponsiveFit($el);
        });
    }

    /**
     * WooCommerce export form with redirects kept on the zerti admin screen.
     */
    function initExportForm($form) {
        if (!$form.length || $form.data('zertiInvIeExport')) {
            return;
        }
        $form.data('zertiInvIeExport', 1);

        var productExportForm = function ($f) {
            this.$form = $f;
            this.processStep = this.processStep.bind(this);
            $f.on('submit', { productExportForm: this }, this.onSubmit);
            $f.find('.woocommerce-exporter-types').on('change', { productExportForm: this }, this.exportTypeFields);
            this.$form.find('.woocommerce-exporter-progress').val(0);
        };

        productExportForm.prototype.onSubmit = function (event) {
            event.preventDefault();
            var currentDate = new Date();
            var filename =
                'wc-product-export-' +
                currentDate.getDate() +
                '-' +
                (currentDate.getMonth() + 1) +
                '-' +
                currentDate.getFullYear() +
                '-' +
                currentDate.getTime() +
                '.csv';

            var ctx = event.data.productExportForm;
            ctx.$form.addClass('woocommerce-exporter__exporting');
            ctx.$form.find('.woocommerce-exporter-progress').val(0);
            ctx.$form.find('.woocommerce-exporter-button').prop('disabled', true);
            ctx.$form.closest('.zerti-inv-ie-export').find('.zerti-inv-ie-export-spinner').removeClass('d-none');
            ctx.processStep(1, ctx.$form.serialize(), '', filename);
        };

        productExportForm.prototype.processStep = function (step, data, columns, filename) {
            var $this = this;
            var selected_columns = $this.$form.find('.woocommerce-exporter-columns').val();
            var export_meta = $this.$form.find('#woocommerce-exporter-meta:checked').length ? 1 : 0;
            var export_types = $this.$form.find('.woocommerce-exporter-types').val();
            var export_category = $this.$form.find('.woocommerce-exporter-category').val();
            var export_product_ids = $this.$form.find('input[name="product_ids"]').val() || '';

            $.ajax({
                type: 'POST',
                url: window.ajaxurl,
                data: {
                    form: data,
                    action: 'woocommerce_do_ajax_product_export',
                    step: step,
                    columns: columns,
                    selected_columns: selected_columns,
                    export_meta: export_meta,
                    export_types: export_types,
                    export_category: export_category,
                    export_product_ids: export_product_ids,
                    filename: filename,
                    security: window.zerti_product_export_params.export_nonce,
                },
                dataType: 'json',
                success: function (response) {
                    if (!response.success) {
                        return;
                    }
                    if (response.data.step === 'done') {
                        $this.$form.find('.woocommerce-exporter-progress').val(response.data.percentage);
                        window.location = buildZertiExportDownloadUrl(response.data.url);
                        setTimeout(function () {
                            $this.$form.removeClass('woocommerce-exporter__exporting');
                            $this.$form.find('.woocommerce-exporter-button').prop('disabled', false);
                            $this.$form
                                .closest('.zerti-inv-ie-export')
                                .find('.zerti-inv-ie-export-spinner')
                                .addClass('d-none');
                        }, 2000);
                    } else {
                        $this.$form.find('.woocommerce-exporter-progress').val(response.data.percentage);
                        $this.processStep(parseInt(response.data.step, 10), data, response.data.columns, filename);
                    }
                },
            }).fail(function (response) {
                if (window.console && window.console.log) {
                    window.console.log(response);
                }
            });
        };

        productExportForm.prototype.exportTypeFields = function () {
            var $form = $(this).closest('form');
            var types = $form.find('.woocommerce-exporter-types').val() || [];
            var $categoryRow = $form.find('.zerti-inv-ie-export-category-row');
            if ($.inArray('variation', types) !== -1) {
                $categoryRow.hide();
                $form.find('#zerti-exporter-category-picker .zerti-inv-ie-checkbox-picker__check').prop('checked', false);
                $form.find('.woocommerce-exporter-category option').prop('selected', false);
                $form.find('.woocommerce-exporter-category').trigger('change');
            } else {
                $categoryRow.show();
            }
        };

        new productExportForm($form);
    }

    /**
     * WooCommerce import progress (batch AJAX) with done redirect on zerti URL.
     */
    function initImportProgress($form) {
        if (!$form.length || $form.data('zertiInvIeImport')) {
            return;
        }
        if (typeof window.zerti_product_import_params !== 'object' || !window.zerti_product_import_params) {
            return;
        }
        $form.data('zertiInvIeImport', 1);

        var productImportForm = function ($f) {
            this.$form = $f;
            this.mapping = window.zerti_product_import_params.mapping;
            this.position = 0;
            this.file = window.zerti_product_import_params.file;
            this.update_existing = window.zerti_product_import_params.update_existing;
            this.delimiter = window.zerti_product_import_params.delimiter;
            this.security = window.zerti_product_import_params.import_nonce;
            this.character_encoding = window.zerti_product_import_params.character_encoding;
            this.imported = 0;
            this.imported_variations = 0;
            this.failed = 0;
            this.updated = 0;
            this.skipped = 0;
            this.$form.find('.woocommerce-importer-progress').val(0);
            this.run_import = this.run_import.bind(this);
            this.run_import();
        };

        productImportForm.prototype.run_import = function () {
            var $this = this;
            $.ajax({
                type: 'POST',
                url: window.ajaxurl,
                data: {
                    action: 'woocommerce_do_ajax_product_import',
                    position: $this.position,
                    mapping: $this.mapping,
                    file: $this.file,
                    update_existing: $this.update_existing,
                    delimiter: $this.delimiter,
                    security: $this.security,
                    character_encoding: $this.character_encoding,
                },
                dataType: 'json',
                success: function (response) {
                    if (!response.success) {
                        return;
                    }
                    $this.position = response.data.position;
                    $this.imported += response.data.imported;
                    $this.imported_variations += response.data.imported_variations;
                    $this.failed += response.data.failed;
                    $this.updated += response.data.updated;
                    $this.skipped += response.data.skipped;
                    $this.$form.find('.woocommerce-importer-progress').val(response.data.percentage);

                    if (response.data.position === 'done') {
                        var file_name = String($this.file).split('/').pop();
                        var base = cfg.importDoneBase || response.data.url;
                        window.location =
                            base +
                            '&products-imported=' +
                            parseInt($this.imported, 10) +
                            '&products-imported-variations=' +
                            parseInt($this.imported_variations, 10) +
                            '&products-failed=' +
                            parseInt($this.failed, 10) +
                            '&products-updated=' +
                            parseInt($this.updated, 10) +
                            '&products-skipped=' +
                            parseInt($this.skipped, 10) +
                            '&file-name=' +
                            encodeURIComponent(file_name);
                    } else {
                        $this.run_import();
                    }
                },
            }).fail(function (response) {
                if (window.console && window.console.log) {
                    window.console.log(response);
                }
            });
        };

        new productImportForm($form);
    }

    function bindImportFileUpload(root) {
        $(root)
            .find('.zerti-file-upload__input[data-zerti-file-empty]')
            .off('change.zertiInvIeFile')
            .on('change.zertiInvIeFile', function () {
                var input = this;
                var wrap = input.closest('.zerti-file-upload');
                var nameEl = wrap ? wrap.querySelector('[data-zerti-file-name]') : null;
                if (!nameEl) {
                    return;
                }
                var emptyText = input.getAttribute('data-zerti-file-empty') || '';
                nameEl.textContent =
                    input.files && input.files.length > 0 ? input.files[0].name : emptyText;
            });
    }

    function bindDoneErrorToggle(root) {
        $(root)
            .find('.woocommerce-importer-done-view-errors')
            .off('click.zertiInvIe')
            .on('click.zertiInvIe', function (e) {
                e.preventDefault();
                $(root).find('.wc-importer-error-log').slideToggle();
            });
    }

    window.zertiInitInventoryImportExport = function (root) {
        root = root || document;
        var slot = root.querySelector
            ? root.querySelector('.zerti-component-inventory-import-export')
            : null;
        if (!slot) {
            slot = root.querySelector ? root.querySelector('[data-zerti-inv-component="import-export"]') : null;
        }
        if (!slot) {
            return;
        }

        bindAdvancedImportToggle(slot);
        bindDoneErrorToggle(slot);
        bindImportFileUpload(slot);
        initExportCheckboxPickers(slot);
        initEnhancedSelect(slot);
        window.setTimeout(function () {
            initExportCheckboxPickers(slot);
            initEnhancedSelect(slot);
        }, 150);

        var $exportForm = $(slot).find('form.woocommerce-exporter');
        if ($exportForm.length) {
            initExportForm($exportForm);
        }

        var $importProgress = $(slot).find('.woocommerce-importer__importing');
        if ($importProgress.length) {
            initImportProgress($importProgress);
        }
    };
})(jQuery, window);
