(function () {
    'use strict';

    function readCfg() {
        return typeof window.zertiInvAttributeGroups === 'object' && window.zertiInvAttributeGroups !== null
            ? window.zertiInvAttributeGroups
            : {};
    }

    function toLatinDigits(str) {
        return typeof window.zertiToLatinDigits === 'function' ? window.zertiToLatinDigits(String(str)) : String(str);
    }

    function toLocalizedDigits(str) {
        return typeof window.zertiLocalizeDigits === 'function'
            ? window.zertiLocalizeDigits(toLatinDigits(String(str)))
            : String(str);
    }

    function arabicToConfiguredDigits(str) {
        if (window.zertiDigitLocale && window.zertiDigitLocale.script === 'persian') {
            var arabic = '٠١٢٣٤٥٦٧٨٩';
            var persian = '۰۱۲۳۴۵۶۷۸۹';
            return String(str).replace(/[٠-٩]/g, function (ch) {
                var idx = arabic.indexOf(ch);
                return idx >= 0 ? persian.charAt(idx) : ch;
            });
        }

        return String(str);
    }

    function normalizeMenuOrderInput(input) {
        if (!input) {
            return;
        }
        var latin = toLatinDigits(arabicToConfiguredDigits(String(input.value || '')));
        var normalized = '';
        var i;
        for (i = 0; i < latin.length; i++) {
            var ch = latin.charAt(i);
            if (ch >= '0' && ch <= '9') {
                normalized += ch;
            }
        }
        input.value = normalized === '' ? '' : toLocalizedDigits(normalized);
    }

    function bindMenuOrderInput(input) {
        if (!input || input.__zertiMenuOrderDigitBound) {
            return;
        }
        input.__zertiMenuOrderDigitBound = true;
        input.addEventListener('input', function () {
            normalizeMenuOrderInput(input);
        });
        input.addEventListener('blur', function () {
            normalizeMenuOrderInput(input);
        });
    }

    function toPersianDigits(n) {
        return toLocalizedDigits(n);
    }

    function escapeHtml(s) {
        var div = document.createElement('div');
        div.textContent = s == null ? '' : String(s);
        return div.innerHTML;
    }

    function zertiDeleteConfirm(message, i18n) {
        var api = window.zertiConfirmAlert;
        if (api && typeof api.showDeleteConfirm === 'function') {
            return api.showDeleteConfirm(message, i18n);
        }
        return Promise.resolve(window.confirm(message));
    }

    function parseAjaxJson(res) {
        if (!res.ok) {
            throw new Error('http');
        }
        return res.json();
    }

    function findWrap(root) {
        return root ? root.querySelector('[data-zerti-inv-attribute-groups="1"]') : null;
    }

    function postAction(action, fields) {
        var cfg = readCfg();
        var body = new window.FormData();
        body.append('action', action);
        body.append('nonce', cfg.nonce || '');
        if (fields && typeof fields === 'object') {
            Object.keys(fields).forEach(function (key) {
                var val = fields[key];
                if (val !== undefined && val !== null) {
                    body.append(key, String(val));
                }
            });
        }
        return window.fetch(cfg.ajaxUrl || '', {
            method: 'POST',
            credentials: 'same-origin',
            body: body,
        }).then(parseAjaxJson);
    }

    function InvAttributeGroupsManager(wrap) {
        this.wrap = wrap;
        this.treeEl = wrap.querySelector('.zerti-inv-categories__tree');
        this.treeLoading = wrap.querySelector('.zerti-inv-categories__tree-loading');
        this.treeEmpty = wrap.querySelector('.zerti-inv-categories__tree-empty');
        this.searchInput = wrap.querySelector('.zerti-inv-categories__search-input');
        this.editorSection = wrap.querySelector('.zerti-inv-categories__editor');
        this.editorBarTitle = wrap.querySelector('.zerti-inv-categories__editor-bar-title');
        this.addBtn = wrap.querySelector('.zerti-inv-categories__add-btn');
        this.cancelEditBtn = wrap.querySelector('.zerti-inv-categories__cancel-edit-btn');
        this.form = wrap.querySelector('.zerti-inv-categories__form');
        this.formError = wrap.querySelector('.zerti-inv-categories__form-error');
        this.formSuccess = wrap.querySelector('.zerti-inv-categories__form-success');
        this.metaLine = wrap.querySelector('.zerti-inv-categories__meta-line');
        this.picklist = wrap.querySelector('[data-zerti-attribute-picklist]');
        this.picklistEmpty = wrap.querySelector('.zerti-inv-attribute-groups-picklist-empty');

        this.groups = [];
        this.tree = [];
        this.flat = [];
        this.active = null;
        this.availableAttributes = [];
        this.selectedId = 0;
        this.editingNew = false;
        this.searchTimer = null;
        this.loadOverlay = null;
        this.saving = false;
        this.editorExplicitOpen = false;

        this.bindEvents();
        this.expandEditor();
        this.setEditorBarTitle(this.getI18n().editorBarDefault || '');
        this.updateEditorBarActions('idle');
        this.loadList();
    }

    InvAttributeGroupsManager.prototype.getCfg = function () {
        return readCfg();
    };

    InvAttributeGroupsManager.prototype.getI18n = function () {
        return readCfg().i18n || {};
    };

    InvAttributeGroupsManager.prototype.bindEvents = function () {
        var self = this;

        if (this.searchInput) {
            this.searchInput.addEventListener('input', function () {
                if (self.searchTimer) {
                    window.clearTimeout(self.searchTimer);
                }
                self.searchTimer = window.setTimeout(function () {
                    self.loadList();
                }, 280);
            });
        }

        if (this.addBtn) {
            this.addBtn.addEventListener('click', function () {
                self.requestOpenNew();
            });
        }

        if (this.cancelEditBtn) {
            this.cancelEditBtn.addEventListener('click', function () {
                self.closeEditor();
            });
        }

        var cancelBtn = this.wrap.querySelector('.zerti-inv-categories__cancel-btn');
        if (cancelBtn) {
            cancelBtn.addEventListener('click', function () {
                self.closeEditor();
            });
        }

        var deleteBtn = this.wrap.querySelector('.zerti-inv-categories__delete-btn');
        if (deleteBtn) {
            deleteBtn.addEventListener('click', function () {
                self.confirmDelete();
            });
        }

        if (this.form) {
            this.form.addEventListener('submit', function (e) {
                e.preventDefault();
                self.saveForm();
            });
            var menuOrderInput = this.form.querySelector('[data-zerti-menu-order-input]');
            if (menuOrderInput) {
                bindMenuOrderInput(menuOrderInput);
            }
        }

        if (this.treeEl) {
            this.treeEl.addEventListener('click', function (e) {
                var editBtn = e.target && e.target.closest ? e.target.closest('[data-zerti-cat-edit]') : null;
                if (editBtn) {
                    e.preventDefault();
                    e.stopPropagation();
                    var editId = parseInt(editBtn.getAttribute('data-zerti-cat-edit') || '0', 10);
                    if (editId > 0) {
                        self.selectGroup(editId);
                    }
                }
            });
        }
    };

    InvAttributeGroupsManager.prototype.syncTreeFromGroups = function () {
        var self = this;
        this.tree = this.groups.map(function (group) {
            return {
                id: group.id,
                name: group.name,
                slug: group.slug,
                count: parseInt(group.attributes_count || 0, 10),
                children: [],
                thumbnail_url: '',
            };
        });
        this.flat = this.tree.map(function (node) {
            return {
                id: node.id,
                name: node.name,
                slug: node.slug,
                count: node.count,
                parent: 0,
            };
        });
    };

    InvAttributeGroupsManager.prototype.setLoading = function (on) {
        if (this.treeLoading) {
            this.treeLoading.classList.toggle('d-none', !on);
        }
        if (this.treeEl) {
            this.treeEl.classList.toggle('opacity-50', on);
        }
    };

    InvAttributeGroupsManager.prototype.createLoadOverlay = function (label) {
        var i18n = this.getI18n();
        var el = document.createElement('div');
        el.className = 'zerti-component-load-overlay text-body-secondary';
        el.setAttribute('role', 'status');
        el.setAttribute('aria-live', 'polite');
        el.innerHTML =
            '<span class="spinner-border spinner-border-sm" aria-hidden="true"></span>' +
            '<span>' + escapeHtml(label || i18n.loading || '') + '</span>';
        return el;
    };

    InvAttributeGroupsManager.prototype.setLoadOverlay = function (on, label) {
        if (!this.wrap) {
            return;
        }
        if (on) {
            if (this.loadOverlay) {
                return;
            }
            this.loadOverlay = this.createLoadOverlay(label);
            this.wrap.appendChild(this.loadOverlay);
            this.wrap.setAttribute('aria-busy', 'true');
            return;
        }
        if (this.loadOverlay && this.loadOverlay.parentNode) {
            this.loadOverlay.remove();
        }
        this.loadOverlay = null;
        this.wrap.removeAttribute('aria-busy');
    };

    InvAttributeGroupsManager.prototype.applyPayload = function (data) {
        if (!data) {
            return;
        }
        this.groups = Array.isArray(data.groups) ? data.groups : [];
        this.availableAttributes = Array.isArray(data.available_attributes) ? data.available_attributes : [];
        this.active = data.active && typeof data.active === 'object' ? data.active : null;
        if (this.active && this.active.id) {
            this.selectedId = parseInt(this.active.id, 10);
        }
        this.syncTreeFromGroups();
        this.renderTree();

        if (this.editorExplicitOpen && this.active && this.active.id) {
            this.selectedId = parseInt(this.active.id, 10);
            this.expandEditor();
            this.showForm(this.active);
            return;
        }

        if (!this.editorExplicitOpen) {
            this.selectedId = 0;
            this.editingNew = false;
            this.active = null;
            this.collapseEditor();
            if (this.form) {
                this.form.classList.add('d-none');
            }
            this.setEditorBarTitle(this.getI18n().editorBarDefault || '');
            this.updateEditorBarActions('idle');
        }
    };

    InvAttributeGroupsManager.prototype.loadList = function () {
        var self = this;
        var cfg = this.getCfg();
        var i18n = this.getI18n();
        if (!cfg.ajaxUrl || !cfg.nonce) {
            return;
        }

        var fields = { search: this.searchInput ? this.searchInput.value.trim() : '' };
        if (this.selectedId > 0) {
            fields.group_id = this.selectedId;
        }

        this.setLoading(true);
        postAction(cfg.listAction || 'zerti_product_attribute_groups_list', fields)
            .then(function (data) {
                if (!data || !data.success || !data.data) {
                    throw new Error('bad');
                }
                self.applyPayload(data.data);
            })
            .catch(function () {
                if (self.treeEmpty) {
                    self.treeEmpty.textContent = i18n.loadError || '';
                    self.treeEmpty.classList.remove('d-none');
                }
            })
            .finally(function () {
                self.setLoading(false);
            });
    };

    InvAttributeGroupsManager.prototype.renderTree = function () {
        var i18n = this.getI18n();
        if (!this.treeEl) {
            return;
        }
        this.treeEl.innerHTML = '';
        if (this.treeEmpty) {
            this.treeEmpty.classList.add('d-none');
        }

        if (!this.tree.length) {
            if (this.treeEmpty) {
                this.treeEmpty.textContent =
                    this.searchInput && this.searchInput.value.trim()
                        ? i18n.noResults || ''
                        : i18n.emptyTree || '';
                this.treeEmpty.classList.remove('d-none');
            }
            return;
        }

        this.buildTreeUl(this.tree, this.treeEl, 0);
    };

    InvAttributeGroupsManager.prototype.buildTreeUl = function (nodes, container, depth) {
        var self = this;
        var i18n = this.getI18n();
        var isRoot =
            container &&
            container.classList &&
            container.classList.contains('zerti-inv-categories__tree');
        var ul = isRoot ? container : document.createElement('ul');
        if (!isRoot) {
            ul.className = 'zerti-inv-categories__tree-level list-unstyled mb-0';
            ul.setAttribute('role', 'group');
        }

        nodes.forEach(function (node) {
            var id = parseInt(node.id || 0, 10);
            var isActive = self.selectedId === id;

            var li = document.createElement('li');
            li.className = 'zerti-inv-categories__tree-item';
            li.setAttribute('role', 'treeitem');

            var row = document.createElement('div');
            row.className =
                'zerti-inv-categories__tree-row' + (isActive ? ' zerti-inv-categories__tree-row--active' : '');
            row.style.setProperty('--zerti-cat-depth', String(depth));

            var toggleHtml =
                '<span class="zerti-inv-categories__tree-toggle-spacer" aria-hidden="true"></span>';
            var thumb =
                '<span class="zerti-inv-categories__tree-thumb zerti-inv-categories__tree-thumb--empty"><i class="fa-solid fa-layer-group" aria-hidden="true"></i></span>';
            var nameHtml =
                '<span class="zerti-inv-categories__tree-name">' + escapeHtml(node.name || '') + '</span>';
            var editLabel = escapeHtml(i18n.editBtnLabel || i18n.editCategory || '');
            var editHtml =
                '<button type="button" class="btn btn-sm btn-outline-secondary zerti-inv-categories__tree-edit-btn" data-zerti-cat-edit="' +
                id +
                '" aria-label="' +
                editLabel +
                '"><i class="fa-solid fa-pen" aria-hidden="true"></i></button>';

            row.innerHTML =
                toggleHtml +
                thumb +
                nameHtml +
                '<span class="zerti-inv-categories__tree-count badge text-bg-light">' +
                toPersianDigits(parseInt(node.count || 0, 10)) +
                '</span>' +
                editHtml;

            li.appendChild(row);
            ul.appendChild(li);
        });

        return isRoot ? null : ul;
    };

    InvAttributeGroupsManager.prototype.findItem = function (id) {
        return this.groups.find(function (r) {
            return parseInt(r.id, 10) === id;
        });
    };

    InvAttributeGroupsManager.prototype.isEditorCollapsed = function () {
        return false;
    };

    InvAttributeGroupsManager.prototype.isEditorBusy = function () {
        return !!this.editorExplicitOpen;
    };

    InvAttributeGroupsManager.prototype.expandEditor = function () {
        if (!this.editorSection) {
            return;
        }
        this.editorSection.classList.remove('zerti-inv-categories__editor--collapsed');
        this.editorSection.setAttribute('data-zerti-editor-expanded', '1');
    };

    InvAttributeGroupsManager.prototype.collapseEditor = function () {
        if (!this.editorSection) {
            return;
        }
        this.editorSection.classList.remove('zerti-inv-categories__editor--collapsed');
        this.editorSection.setAttribute('data-zerti-editor-expanded', '1');
        if (this.form) {
            this.form.classList.add('d-none');
        }
        this.hideFormMessages();
    };

    InvAttributeGroupsManager.prototype.setEditorBarTitle = function (text) {
        var i18n = this.getI18n();
        if (this.editorBarTitle) {
            this.editorBarTitle.textContent = text || i18n.editorBarDefault || '';
        }
    };

    InvAttributeGroupsManager.prototype.updateEditorBarActions = function (mode) {
        var isIdle = mode === 'idle';
        var isEdit = mode === 'edit';
        var isNew = mode === 'new';
        if (this.addBtn) {
            this.addBtn.classList.toggle('d-none', !isIdle);
        }
        if (this.cancelEditBtn) {
            this.cancelEditBtn.classList.toggle('d-none', !(isEdit || isNew));
        }
    };

    InvAttributeGroupsManager.prototype.selectGroup = function (id) {
        if (this.editorExplicitOpen && this.selectedId !== id) {
            return;
        }
        var item = this.findItem(id);
        if (!item) {
            return;
        }
        this.editorExplicitOpen = true;
        this.selectedId = id;
        this.editingNew = false;
        this.expandEditor();
        this.showForm(item);
        this.renderTree();
    };

    InvAttributeGroupsManager.prototype.requestOpenNew = function () {
        if (this.editorExplicitOpen) {
            return;
        }
        this.openNew();
    };

    InvAttributeGroupsManager.prototype.openNew = function () {
        if (this.editorExplicitOpen) {
            return;
        }
        this.editorExplicitOpen = true;
        this.selectedId = 0;
        this.editingNew = true;
        this.expandEditor();
        this.showForm({
            id: 0,
            name: '',
            slug: '',
            description: '',
            menu_order: 0,
            attribute_ids: [],
            attributes_count: 0,
        });
        this.renderTree();
    };

    InvAttributeGroupsManager.prototype.closeEditor = function () {
        this.editorExplicitOpen = false;
        this.selectedId = 0;
        this.active = null;
        this.editingNew = false;
        if (this.form) {
            this.form.classList.add('d-none');
        }
        this.collapseEditor();
        this.setEditorBarTitle(this.getI18n().editorBarDefault || '');
        this.updateEditorBarActions('idle');
        this.hideFormMessages();
        this.renderTree();
        this.loadList();
    };

    InvAttributeGroupsManager.prototype.renderPicklist = function (selectedIds) {
        var i18n = this.getI18n();
        if (!this.picklist) {
            return;
        }
        var selected = {};
        (selectedIds || []).forEach(function (id) {
            selected[parseInt(id, 10)] = true;
        });

        this.picklist.innerHTML = '';
        var attrs = this.availableAttributes || [];
        if (this.picklistEmpty) {
            this.picklistEmpty.classList.toggle('d-none', attrs.length > 0);
        }
        if (!attrs.length) {
            return;
        }

        attrs.forEach(function (attr) {
            var id = parseInt(attr.id || 0, 10);
            if (id < 1) {
                return;
            }
            var label = document.createElement('label');
            label.className = 'zerti-inv-attribute-groups-picklist__item form-check d-flex align-items-center gap-2 mb-1';
            label.innerHTML =
                '<input class="form-check-input" type="checkbox" value="' +
                id +
                '" data-zerti-attr-id="' +
                id +
                '"' +
                (selected[id] ? ' checked' : '') +
                '>' +
                '<span class="form-check-label">' +
                escapeHtml(attr.name || '') +
                '</span>';
            this.picklist.appendChild(label);
        }, this);
    };

    InvAttributeGroupsManager.prototype.getSelectedAttributeIds = function () {
        if (!this.picklist) {
            return [];
        }
        var ids = [];
        this.picklist.querySelectorAll('input[type="checkbox"][data-zerti-attr-id]:checked').forEach(function (el) {
            var id = parseInt(el.getAttribute('data-zerti-attr-id') || '0', 10);
            if (id > 0) {
                ids.push(id);
            }
        });
        return ids;
    };

    InvAttributeGroupsManager.prototype.showForm = function (item) {
        var i18n = this.getI18n();
        if (this.form) {
            this.form.classList.remove('d-none');
        }

        var isNew = !item.id;
        if (isNew) {
            this.setEditorBarTitle(i18n.editorBarNew || i18n.newCategory || '');
            this.updateEditorBarActions('new');
        } else {
            this.setEditorBarTitle((i18n.editorBarEdit || '') + (item.name || ''));
            this.updateEditorBarActions('edit');
        }

        this.setField('id', item.id || 0);
        this.setField('name', item.name || '');
        this.setField('slug', item.slug || '');
        this.setField('description', item.description || '');
        this.setField('menu_order', item.menu_order != null ? item.menu_order : 0);
        this.renderPicklist(item.attribute_ids || []);

        var deleteBtn = this.wrap.querySelector('.zerti-inv-categories__delete-btn');
        if (deleteBtn) {
            deleteBtn.classList.toggle('d-none', isNew);
        }

        if (this.metaLine) {
            if (isNew) {
                this.metaLine.classList.add('d-none');
            } else {
                this.metaLine.classList.remove('d-none');
                this.metaLine.textContent =
                    (i18n.attributesCount || '') +
                    ': ' +
                    toPersianDigits(parseInt(item.attributes_count || 0, 10));
            }
        }

        this.hideFormMessages();
    };

    InvAttributeGroupsManager.prototype.setField = function (name, value) {
        var el = this.form ? this.form.querySelector('[data-zerti-field="' + name + '"]') : null;
        if (!el) {
            return;
        }
        if (name === 'menu_order') {
            var orderNum = parseInt(String(value == null ? '' : value), 10);
            el.value = !isNaN(orderNum) && orderNum > 0 ? toLocalizedDigits(orderNum) : '';
            return;
        }
        el.value = value == null ? '' : String(value);
    };

    InvAttributeGroupsManager.prototype.getField = function (name) {
        var el = this.form ? this.form.querySelector('[data-zerti-field="' + name + '"]') : null;
        if (!el) {
            return '';
        }
        if (name === 'menu_order') {
            var latin = toLatinDigits(arabicToConfiguredDigits(String(el.value || ''))).replace(/\D/g, '');
            return latin === '' ? '0' : latin;
        }
        return el.value;
    };

    InvAttributeGroupsManager.prototype.hideFormMessages = function () {
        if (this.formError) {
            this.formError.classList.add('d-none');
            this.formError.textContent = '';
        }
        if (this.formSuccess) {
            this.formSuccess.classList.add('d-none');
            this.formSuccess.textContent = '';
        }
    };

    InvAttributeGroupsManager.prototype.showFormError = function (msg) {
        if (this.formError) {
            this.formError.textContent = msg;
            this.formError.classList.remove('d-none');
        }
        if (this.formSuccess) {
            this.formSuccess.classList.add('d-none');
        }
    };

    InvAttributeGroupsManager.prototype.showFormSuccess = function (msg) {
        var i18n = this.getI18n();
        if (this.formSuccess) {
            this.formSuccess.textContent = msg;
            this.formSuccess.classList.remove('d-none');
        }
        if (this.formError) {
            this.formError.classList.add('d-none');
        }
        window.setTimeout(
            function (mgr) {
                if (mgr.formSuccess) {
                    mgr.formSuccess.classList.add('d-none');
                }
            },
            parseInt(i18n.feedbackDurationMs || '2000', 10),
            this
        );
    };

    InvAttributeGroupsManager.prototype.saveForm = function () {
        var self = this;
        var cfg = this.getCfg();
        var i18n = this.getI18n();

        if (this.saving) {
            return;
        }

        var name = this.getField('name').trim();
        if (!name) {
            this.showFormError(i18n.nameRequired || '');
            return;
        }

        this.saving = true;
        var saveBtn = this.wrap.querySelector('.zerti-inv-categories__save-btn');
        if (saveBtn) {
            saveBtn.disabled = true;
        }
        this.setLoadOverlay(true, i18n.saving || i18n.loading || '');

        postAction(cfg.saveAction || 'zerti_product_attribute_group_save', {
            id: this.getField('id'),
            name: name,
            slug: this.getField('slug'),
            description: this.getField('description'),
            menu_order: this.getField('menu_order'),
            attribute_ids: JSON.stringify(this.getSelectedAttributeIds()),
        })
            .then(function (data) {
                if (!data || !data.success) {
                    var errMsg = data && data.data && data.data.message ? data.data.message : i18n.saveError || '';
                    throw new Error(errMsg);
                }
                self.setLoadOverlay(false);
                self.editorExplicitOpen = true;
                self.applyPayload(data.data);
                self.showFormSuccess(i18n.saved || '');
            })
            .catch(function (err) {
                self.showFormError(err && err.message ? err.message : i18n.saveError || '');
            })
            .finally(function () {
                self.saving = false;
                self.setLoadOverlay(false);
                if (saveBtn) {
                    saveBtn.disabled = false;
                }
            });
    };

    InvAttributeGroupsManager.prototype.confirmDelete = function () {
        var i18n = this.getI18n();
        var name = this.active ? this.active.name : '';
        var self = this;
        var msg = (i18n.deleteConfirm || '').replace('%s', name);
        zertiDeleteConfirm(msg, i18n).then(function (ok) {
            if (ok) {
                self.performDelete();
            }
        });
    };

    InvAttributeGroupsManager.prototype.performDelete = function () {
        var self = this;
        var cfg = this.getCfg();
        var i18n = this.getI18n();
        var id = parseInt(this.getField('id') || '0', 10);
        if (id < 1) {
            return;
        }

        this.setLoadOverlay(true, i18n.loading || '');
        postAction(cfg.deleteAction || 'zerti_product_attribute_group_delete', { id: id })
            .then(function (data) {
                if (!data || !data.success) {
                    var msg = data && data.data && data.data.message ? data.data.message : i18n.deleteError || '';
                    throw new Error(msg);
                }
                self.editorExplicitOpen = false;
                self.closeEditor();
            })
            .catch(function (err) {
                self.showFormError(err && err.message ? err.message : i18n.deleteError || '');
            })
            .finally(function () {
                self.setLoadOverlay(false);
            });
    };

    function initInventoryAttributeGroups(root) {
        if (!root) {
            return;
        }
        var cfg = readCfg();
        if (!cfg.ajaxUrl || !cfg.nonce) {
            return;
        }
        var wrap = findWrap(root);
        if (!wrap || wrap.getAttribute('data-zerti-inv-attribute-groups-inited') === '1') {
            return;
        }
        wrap.setAttribute('data-zerti-inv-attribute-groups-inited', '1');
        window.requestAnimationFrame(function () {
            try {
                new InvAttributeGroupsManager(wrap);
            } catch (e) {
                wrap.removeAttribute('data-zerti-inv-attribute-groups-inited');
            }
        });
    }

    window.zertiInitInventoryAttributeGroups = initInventoryAttributeGroups;
})();
