(function () {
    'use strict';

    function readCfg() {
        return typeof window.zertiInvTags === 'object' && window.zertiInvTags !== null
            ? window.zertiInvTags
            : {};
    }
    function toPersianDigits(n) {
        return window.zertiLocalizeDigits(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) {
        if (!root) {
            return null;
        }
        return root.querySelector('[data-zerti-inv-tags="1"]');
    }

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

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

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

    function InvTagsManager(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.newFromBarBtn = wrap.querySelector('.zerti-inv-categories__new-from-bar-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.parentSelect = wrap.querySelector('[data-zerti-field="parent"]');
        this.thumbPreview = wrap.querySelector('[data-zerti-thumb-preview]');
        this.thumbClearBtn = wrap.querySelector('.zerti-inv-categories__thumb-clear');
        this.metaLine = wrap.querySelector('.zerti-inv-categories__meta-line');

        this.flat = [];
        this.tree = [];
        this.parentOptions = [];
        this.selectedId = 0;
        this.editingNew = false;
        this.expanded = {};
        this.searchTimer = null;
        this.mediaFrame = null;
        this.loadOverlay = null;
        this.editorExplicitOpen = false;

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

    InvTagsManager.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(self.searchInput.value.trim());
                }, 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 thumbPick = this.wrap.querySelector('.zerti-inv-categories__thumb-pick');
        if (thumbPick) {
            thumbPick.addEventListener('click', function () {
                self.openMediaPicker();
            });
        }
        if (this.thumbClearBtn) {
            this.thumbClearBtn.addEventListener('click', function () {
                self.setThumbnail(0, '');
            });
        }

        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.selectCategory(editId);
                    }
                    return;
                }

                var toggle = e.target && e.target.closest ? e.target.closest('[data-zerti-cat-toggle]') : null;
                if (toggle) {
                    e.preventDefault();
                    e.stopPropagation();
                    var tid = parseInt(toggle.getAttribute('data-zerti-cat-toggle') || '0', 10);
                    if (tid > 0) {
                        self.toggleCategoryExpand(tid);
                    }
                    return;
                }

                var nameEl = e.target && e.target.closest ? e.target.closest('[data-zerti-cat-name]') : null;
                if (nameEl) {
                    e.preventDefault();
                    var nameId = parseInt(nameEl.getAttribute('data-zerti-cat-name') || '0', 10);
                    if (nameId > 0 && nameEl.getAttribute('data-zerti-cat-has-children') === '1') {
                        self.toggleCategoryExpand(nameId);
                    }
                    return;
                }
            });
        }
    };

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

    InvTagsManager.prototype.createLoadOverlay = function (label) {
        var i18n = readCfg().i18n || {};
        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;
    };

    InvTagsManager.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');
    };

    InvTagsManager.prototype.applyListData = function (payload, search) {
        if (!payload || typeof payload !== 'object') {
            return;
        }
        this.flat = Array.isArray(payload.flat) ? payload.flat : [];
        this.tree = Array.isArray(payload.tree) ? payload.tree : [];
        this.parentOptions = Array.isArray(payload.parent_options) ? payload.parent_options : [];
        this.autoExpandForSearch(search || '');
        this.renderTree();
        this.fillParentSelect(this.selectedId);

        if (this.editorExplicitOpen && this.selectedId > 0) {
            var activeItem = this.findItem(this.selectedId);
            if (activeItem) {
                this.expandEditor();
                this.showForm(activeItem);
                return;
            }
        }

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

    InvTagsManager.prototype.refreshListData = function () {
        var self = this;
        var cfg = this.getCfg();
        if (!cfg.ajaxUrl || !cfg.nonce) {
            return window.Promise.resolve();
        }
        var search = this.searchInput ? this.searchInput.value.trim() : '';
        return postAction(cfg.listAction || 'zerti_product_tags_list', { search: search }).then(function (data) {
            if (!data || !data.success || !data.data) {
                throw new Error('bad');
            }
            self.applyListData(data.data, search);
        });
    };

    InvTagsManager.prototype.loadList = function (search) {
        var self = this;
        var cfg = this.getCfg();
        var i18n = this.getI18n();
        if (!cfg.ajaxUrl || !cfg.nonce) {
            return;
        }
        this.setLoading(true);
        postAction(cfg.listAction || 'zerti_product_tags_list', { search: search || '' })
            .then(function (data) {
                if (!data || !data.success || !data.data) {
                    throw new Error('bad');
                }
                self.applyListData(data.data, search);
            })
            .catch(function () {
                if (self.treeEmpty) {
                    self.treeEmpty.textContent = i18n.loadError || '';
                    self.treeEmpty.classList.remove('d-none');
                }
            })
            .finally(function () {
                self.setLoading(false);
            });
    };

    InvTagsManager.prototype.autoExpandForSearch = function (search) {
        if (!search) {
            return;
        }
        var self = this;
        this.flat.forEach(function (row) {
            var parent = parseInt(row.parent || 0, 10);
            var id = parseInt(row.id || 0, 10);
            if (id > 0) {
                self.expanded[id] = true;
            }
            while (parent > 0) {
                self.expanded[parent] = true;
                var pRow = self.flat.find(function (r) {
                    return parseInt(r.id, 10) === parent;
                });
                parent = pRow ? parseInt(pRow.parent || 0, 10) : 0;
            }
        });
    };

    InvTagsManager.prototype.toggleCategoryExpand = function (id) {
        if (id < 1) {
            return;
        }
        this.expanded[id] = !this.expanded[id];
        this.renderTree();
    };

    InvTagsManager.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);
    };

    InvTagsManager.prototype.buildTreeUl = function (nodes, container, depth) {
        depth = typeof depth === 'number' ? depth : 0;
        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 children = Array.isArray(node.children) ? node.children : [];
            var hasChildren = children.length > 0;
            var isExpanded = !!self.expanded[id];
            var isActive = self.selectedId === id;

            var li = document.createElement('li');
            li.className = 'zerti-inv-categories__tree-item';
            li.setAttribute('role', 'treeitem');
            li.setAttribute('aria-expanded', hasChildren ? (isExpanded ? 'true' : 'false') : 'false');

            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 = hasChildren
                ? '<button type="button" class="zerti-inv-categories__tree-toggle btn btn-link btn-sm p-0" data-zerti-cat-toggle="' +
                  id +
                  '" aria-label="' +
                  escapeHtml(isExpanded ? i18n.collapse || '' : i18n.expand || '') +
                  '"><i class="fa-solid ' +
                  window.zertiTreeChevronClass(isExpanded) +
                  '" aria-hidden="true"></i></button>'
                : '<span class="zerti-inv-categories__tree-toggle-spacer" aria-hidden="true"></span>';

            var thumb = node.thumbnail_url
                ? '<span class="zerti-inv-categories__tree-thumb-wrap"><img src="' +
                  escapeHtml(node.thumbnail_url) +
                  '" alt="" class="zerti-inv-categories__tree-thumb" loading="lazy"></span>'
                : '<span class="zerti-inv-categories__tree-thumb zerti-inv-categories__tree-thumb--empty"><i class="fa-solid fa-tag" aria-hidden="true"></i></span>';

            var nameClass =
                'zerti-inv-categories__tree-name' + (hasChildren ? ' zerti-inv-categories__tree-name--branch' : '');
            var nameHtml =
                '<button type="button" class="' +
                nameClass +
                '" data-zerti-cat-name="' +
                id +
                '" data-zerti-cat-has-children="' +
                (hasChildren ? '1' : '0') +
                '"' +
                (hasChildren ? '' : ' disabled') +
                '>' +
                escapeHtml(node.name || '') +
                '</button>';

            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);

            if (hasChildren && isExpanded) {
                li.appendChild(self.buildTreeUl(children, null, depth + 1));
            }

            ul.appendChild(li);
        });

        return isRoot ? null : ul;
    };

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

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

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

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

    InvTagsManager.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();
    };

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

    InvTagsManager.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.newFromBarBtn) {
            this.newFromBarBtn.classList.add('d-none');
        }
        if (this.cancelEditBtn) {
            this.cancelEditBtn.classList.toggle('d-none', !(isEdit || isNew));
        }
    };

    InvTagsManager.prototype.selectCategory = function (id) {
        if (this.isEditorBusy() && 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();
    };

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

    InvTagsManager.prototype.openNew = function (parentId) {
        if (this.editorExplicitOpen) {
            return;
        }
        this.editorExplicitOpen = true;
        this.selectedId = 0;
        this.editingNew = true;
        this.expandEditor();
        this.showForm({
            id: 0,
            name: '',
            slug: '',
            parent: parentId || 0,
            description: '',
            display_type: 'default',
            thumbnail_id: 0,
            thumbnail_url: '',
            count: 0,
        });
        this.renderTree();
    };

    InvTagsManager.prototype.closeEditor = function () {
        this.editorExplicitOpen = false;
        this.selectedId = 0;
        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();
    };

    InvTagsManager.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 || '');

        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.productsCount || '') + ': ' + toPersianDigits(parseInt(item.count || 0, 10));
            }
        }

        this.hideFormMessages();
    };

    InvTagsManager.prototype.setField = function (name, value) {
        var el = this.form ? this.form.querySelector('[data-zerti-field="' + name + '"]') : null;
        if (!el) {
            return;
        }
        el.value = value == null ? '' : String(value);
    };

    InvTagsManager.prototype.getField = function (name) {
        var el = this.form ? this.form.querySelector('[data-zerti-field="' + name + '"]') : null;
        return el ? el.value : '';
    };

    InvTagsManager.prototype.getDescendantIds = function (termId) {
        var ids = [];
        var self = this;
        this.flat.forEach(function (row) {
            if (parseInt(row.parent, 10) === termId) {
                var cid = parseInt(row.id, 10);
                if (cid > 0) {
                    ids.push(cid);
                    ids = ids.concat(self.getDescendantIds(cid));
                }
            }
        });
        return ids;
    };

    InvTagsManager.prototype.fillParentSelect = function (excludeId) {
        if (!this.parentSelect) {
            return;
        }
        var blocked = {};
        if (excludeId > 0) {
            blocked[excludeId] = true;
            this.getDescendantIds(excludeId).forEach(function (bid) {
                blocked[bid] = true;
            });
        }
        this.parentSelect.innerHTML = '';
        this.parentOptions.forEach(function (opt) {
            var oid = parseInt(opt.id, 10);
            if (excludeId > 0 && blocked[oid]) {
                return;
            }
            var o = document.createElement('option');
            o.value = String(oid);
            o.textContent = opt.label || '';
            this.parentSelect.appendChild(o);
        }, this);
    };

    InvTagsManager.prototype.setThumbnail = function (id, url) {
        var i18n = this.getI18n();
        this.setField('thumbnail_id', id);
        if (!this.thumbPreview) {
            return;
        }
        if (url) {
            this.thumbPreview.innerHTML =
                '<img src="' + escapeHtml(url) + '" alt="" class="zerti-inv-categories__thumb-img">';
            if (this.thumbClearBtn) {
                this.thumbClearBtn.classList.remove('d-none');
            }
        } else {
            this.thumbPreview.innerHTML =
                '<span class="text-body-secondary small">' + escapeHtml(i18n.noImage || '') + '</span>';
            if (this.thumbClearBtn) {
                this.thumbClearBtn.classList.add('d-none');
            }
        }
    };

    InvTagsManager.prototype.openMediaPicker = function () {
        var self = this;
        var i18n = this.getI18n();
        if (typeof window.wp === 'undefined' || !window.wp.media) {
            return;
        }
        if (!this.mediaFrame) {
            this.mediaFrame = window.wp.media({
                title: i18n.pickImage || '',
                button: { text: i18n.useImage || '' },
                library: { type: 'image' },
                multiple: false,
            });
            this.mediaFrame.on('select', function () {
                var attachment = self.mediaFrame.state().get('selection').first().toJSON();
                var thumbUrl =
                    attachment.sizes && attachment.sizes.thumbnail
                        ? attachment.sizes.thumbnail.url
                        : attachment.url;
                self.setThumbnail(attachment.id, thumbUrl || '');
            });
        }
        this.mediaFrame.open();
    };

    InvTagsManager.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 = '';
        }
    };

    InvTagsManager.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');
        }
    };

    InvTagsManager.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
        );
    };

    InvTagsManager.prototype.saveForm = function () {
        var self = this;
        var cfg = this.getCfg();
        var i18n = this.getI18n();
        var name = this.getField('name').trim();
        if (!name) {
            this.showFormError(i18n.nameRequired || '');
            return;
        }

        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_tag_save', {
            id: this.getField('id'),
            name: name,
            slug: this.getField('slug'),
            parent: this.getField('parent'),
            description: this.getField('description'),
            display_type: this.getField('display_type'),
            thumbnail_id: this.getField('thumbnail_id'),
        })
            .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);
                var savedItem = data.data && data.data.item ? data.data.item : null;
                var savedId = savedItem && savedItem.id ? parseInt(savedItem.id, 10) : 0;

                return self.refreshListData().then(function () {
                    if (savedId > 0) {
                        self.editorExplicitOpen = true;
                        self.selectedId = savedId;
                        self.editingNew = false;
                        self.expanded[savedId] = true;
                        var freshItem = self.findItem(savedId) || savedItem;
                        self.expandEditor();
                        self.showForm(freshItem);
                        self.renderTree();
                    }
                    self.showFormSuccess(i18n.saved || '');
                });
            })
            .catch(function (err) {
                self.showFormError(err && err.message ? err.message : i18n.saveError || '');
            })
            .finally(function () {
                self.setLoadOverlay(false);
                if (saveBtn) {
                    saveBtn.disabled = false;
                }
            });
    };

    InvTagsManager.prototype.confirmDelete = function () {
        var i18n = this.getI18n();
        var item = this.findItem(this.selectedId);
        if (!item) {
            return;
        }
        var self = this;
        var hasChildren = this.flat.some(function (row) {
            return parseInt(row.parent, 10) === self.selectedId;
        });
        var msg = (i18n.deleteConfirm || '').replace('%s', item.name || '');
        if (hasChildren) {
            msg += ' ' + (i18n.deleteHasChildren || '');
        }
        zertiDeleteConfirm(msg, i18n).then(function (ok) {
            if (ok) {
                self.performDelete();
            }
        });
    };

    InvTagsManager.prototype.performDelete = function () {
        var self = this;
        var cfg = this.getCfg();
        var i18n = this.getI18n();
        var id = this.selectedId;
        if (id < 1) {
            return;
        }

        this.setLoadOverlay(true, i18n.loading || '');

        postAction(cfg.deleteAction || 'zerti_product_tag_delete', { id: id })
            .then(function (data) {
                if (!data || !data.success) {
                    var delMsg = data && data.data && data.data.message ? data.data.message : i18n.deleteError || '';
                    throw new Error(delMsg);
                }
                self.setLoadOverlay(false);
                self.closeEditor();
                return self.refreshListData();
            })
            .catch(function (err) {
                self.showFormError(err && err.message ? err.message : i18n.deleteError || '');
            })
            .finally(function () {
                self.setLoadOverlay(false);
            });
    };

    function initInventoryTags(root) {
        if (!root) {
            return;
        }

        var cfg = readCfg();
        if (!cfg.ajaxUrl || !cfg.nonce) {
            return;
        }

        var wrap = findWrap(root);
        if (!wrap || wrap.getAttribute('data-zerti-inv-tags-inited') === '1') {
            return;
        }

        window.requestAnimationFrame(function () {
            try {
                new InvTagsManager(wrap);
                wrap.setAttribute('data-zerti-inv-tags-inited', '1');
            } catch (e) {
                /* Must not break inventory tab. */
            }
        });
    }

    window.zertiInitInventoryTags = initInventoryTags;

    function bootPendingTags() {
        var root = document.getElementById('zertiAdmin');
        if (root) {
            initInventoryTags(root);
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', bootPendingTags);
    } else {
        bootPendingTags();
    }
})();
