(function () {
    'use strict';

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

    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) {
        return root ? root.querySelector('[data-zerti-inv-attributes="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 InvAttributesManager(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.termSearchInput = wrap.querySelector('.zerti-inv-categories__term-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.metaLine = wrap.querySelector('.zerti-inv-categories__meta-line');
        this.termsPanel = wrap.querySelector('.zerti-inv-categories__terms-panel');
        this.termsList = wrap.querySelector('.zerti-inv-categories__terms-list');
        this.termsEmpty = wrap.querySelector('.zerti-inv-categories__terms-empty');
        this.termForm = wrap.querySelector('.zerti-inv-categories__term-form');
        this.termFormTitle = wrap.querySelector('.zerti-inv-categories__term-form-title');
        this.termFormError = wrap.querySelector('.zerti-inv-categories__term-form-error');

        this.attributes = [];
        this.tree = [];
        this.flat = [];
        this.active = null;
        this.terms = [];
        this.selectedId = 0;
        this.editingNew = false;
        this.selectedTermId = 0;
        this.searchTimer = null;
        this.termSearchTimer = null;
        this.loadOverlay = null;
        this.savingAttr = false;
        this.editorExplicitOpen = false;

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

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

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

    InvAttributesManager.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.termSearchInput) {
            this.termSearchInput.addEventListener('input', function () {
                if (self.termSearchTimer) {
                    window.clearTimeout(self.termSearchTimer);
                }
                self.termSearchTimer = window.setTimeout(function () {
                    if (self.selectedId > 0) {
                        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.confirmDeleteAttribute();
            });
        }

        if (this.form) {
            this.form.addEventListener('submit', function (e) {
                e.preventDefault();
                self.saveForm();
            });
            var typeField = this.form.querySelector('[data-zerti-field="type"]');
            if (typeField) {
                typeField.addEventListener('change', function () {
                    self.updateTermsPanelVisibility();
                });
            }
        }

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

        if (this.termsList) {
            this.termsList.addEventListener('click', function (e) {
                var editBtn = e.target && e.target.closest ? e.target.closest('[data-zerti-term-edit]') : null;
                if (!editBtn) {
                    return;
                }
                e.preventDefault();
                var tid = parseInt(editBtn.getAttribute('data-zerti-term-edit') || '0', 10);
                if (tid > 0) {
                    self.editTerm(tid);
                }
            });
        }

        var termSaveBtn = this.wrap.querySelector('.zerti-inv-categories__term-save-btn');
        if (termSaveBtn) {
            termSaveBtn.addEventListener('click', function () {
                self.saveTerm();
            });
        }

        if (this.termForm) {
            this.termForm.addEventListener('keydown', function (e) {
                if (e.key === 'Enter' && e.target && e.target.tagName !== 'TEXTAREA') {
                    e.preventDefault();
                    self.saveTerm();
                }
            });
        }

        var termCancel = this.wrap.querySelector('.zerti-inv-categories__term-cancel-btn');
        if (termCancel) {
            termCancel.addEventListener('click', function () {
                self.resetTermForm(true);
            });
        }

        var termDelete = this.wrap.querySelector('.zerti-inv-categories__term-delete-btn');
        if (termDelete) {
            termDelete.addEventListener('click', function () {
                self.confirmDeleteTerm();
            });
        }
    };

    InvAttributesManager.prototype.syncTreeFromAttributes = function () {
        var self = this;
        this.tree = this.attributes.map(function (attr) {
            return {
                id: attr.id,
                name: attr.name,
                slug: attr.slug,
                count: parseInt(attr.terms_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,
            };
        });
    };

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

    InvAttributesManager.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;
    };

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

    InvAttributesManager.prototype.applyPayload = function (data) {
        if (!data) {
            return;
        }
        this.attributes = Array.isArray(data.attributes) ? data.attributes : [];
        this.active = data.active && typeof data.active === 'object' ? data.active : null;
        this.terms = Array.isArray(data.terms) ? data.terms : [];
        if (this.active && this.active.id) {
            this.selectedId = parseInt(this.active.id, 10);
        }
        this.syncTreeFromAttributes();
        this.renderTree();

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

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

    InvAttributesManager.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.attribute_id = this.selectedId;
            fields.term_search = this.termSearchInput ? this.termSearchInput.value.trim() : '';
        }

        this.setLoading(true);
        postAction(cfg.listAction || 'zerti_product_attributes_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);
            });
    };

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

    InvAttributesManager.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 isActive = self.selectedId === id;

            var li = document.createElement('li');
            li.className = 'zerti-inv-categories__tree-item';
            li.setAttribute('role', 'treeitem');
            li.setAttribute('aria-expanded', '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 =
                '<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-sliders" 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;
    };

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

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

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

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

    InvAttributesManager.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');
        }
        if (this.termsPanel) {
            this.termsPanel.classList.add('d-none');
        }
        this.hideFormMessages();
    };

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

    InvAttributesManager.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);
        }
        /* Attributes: no “add another” while editing — close the card first. */
        if (this.newFromBarBtn) {
            this.newFromBarBtn.classList.add('d-none');
        }
        if (this.cancelEditBtn) {
            this.cancelEditBtn.classList.toggle('d-none', !(isEdit || isNew));
        }
    };

    InvAttributesManager.prototype.selectAttribute = function (id) {
        if (this.isEditorBusy() && this.selectedId !== id) {
            return;
        }
        this.editorExplicitOpen = true;
        this.selectedId = id;
        this.editingNew = false;
        this.loadList();
    };

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

    InvAttributesManager.prototype.openNew = function () {
        if (this.editorExplicitOpen) {
            return;
        }
        this.editorExplicitOpen = true;
        this.selectedId = 0;
        this.active = null;
        this.editingNew = true;
        this.terms = [];
        this.expandEditor();
        this.showForm({
            id: 0,
            name: '',
            slug: '',
            type: 'select',
            order_by: 'menu_order',
            has_archives: false,
            terms_count: 0,
        });
        this.renderTree();
    };

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

    InvAttributesManager.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('type', item.type || 'select');
        this.setField('order_by', item.order_by || 'menu_order');
        var archivesEl = this.form ? this.form.querySelector('[data-zerti-field="has_archives"]') : null;
        if (archivesEl) {
            archivesEl.checked = !!item.has_archives;
        }

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

        this.updateTermsPanelVisibility();
        this.hideFormMessages();
        this.resetTermForm(true);
    };

    InvAttributesManager.prototype.updateTermsPanelVisibility = function () {
        if (!this.termsPanel) {
            return;
        }
        var type = this.getField('type') || 'select';
        var id = parseInt(this.getField('id') || '0', 10);
        var show = id > 0 && !this.editingNew && type === 'select';
        this.termsPanel.classList.toggle('d-none', !show);
    };

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

    InvAttributesManager.prototype.getField = function (name) {
        var el = this.form ? this.form.querySelector('[data-zerti-field="' + name + '"]') : null;
        if (!el) {
            return '';
        }
        if (el.type === 'checkbox') {
            return el.checked ? '1' : '';
        }
        return el.value;
    };

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

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

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

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

        if (this.savingAttr) {
            return;
        }

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

        this.savingAttr = 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.saveAttrAction || 'zerti_product_attribute_save', {
            id: this.getField('id'),
            name: name,
            slug: this.getField('slug'),
            type: this.getField('type'),
            order_by: this.getField('order_by'),
            has_archives: this.getField('has_archives') ? '1' : '',
        })
            .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 || i18n.attrSaved || '');
            })
            .catch(function (err) {
                self.showFormError(err && err.message ? err.message : i18n.saveError || '');
            })
            .finally(function () {
                self.savingAttr = false;
                self.setLoadOverlay(false);
                if (saveBtn) {
                    saveBtn.disabled = false;
                }
            });
    };

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

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

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

        postAction(cfg.deleteAttrAction || 'zerti_product_attribute_delete', { id: this.selectedId })
            .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();
            })
            .catch(function (err) {
                self.showFormError(err && err.message ? err.message : i18n.deleteError || '');
            })
            .finally(function () {
                self.setLoadOverlay(false);
            });
    };

    InvAttributesManager.prototype.renderTerms = function () {
        var i18n = this.getI18n();
        if (!this.termsList) {
            return;
        }
        this.termsList.innerHTML = '';
        if (this.termsEmpty) {
            this.termsEmpty.classList.add('d-none');
        }

        if (!this.terms.length) {
            if (this.termsEmpty) {
                this.termsEmpty.textContent = i18n.emptyTerms || '';
                this.termsEmpty.classList.remove('d-none');
            }
            return;
        }

        var self = this;
        this.terms.forEach(function (term) {
            var id = parseInt(term.id || 0, 10);
            var li = document.createElement('li');
            li.className =
                'list-group-item d-flex flex-wrap align-items-center justify-content-between gap-2' +
                (self.selectedTermId === id ? ' active' : '');
            li.innerHTML =
                '<span>' +
                escapeHtml(term.name || '') +
                ' <span class="text-body-secondary small">(' +
                escapeHtml(toPersianDigits(parseInt(term.count || 0, 10))) +
                ')</span></span>' +
                '<button type="button" class="btn btn-sm btn-outline-secondary" data-zerti-term-edit="' +
                id +
                '">' +
                escapeHtml(i18n.editTermBtn || i18n.editBtnLabel || '') +
                '</button>';
            self.termsList.appendChild(li);
        });
    };

    InvAttributesManager.prototype.findTerm = function (id) {
        return this.terms.find(function (t) {
            return parseInt(t.id, 10) === id;
        });
    };

    InvAttributesManager.prototype.resetTermForm = function (asNew) {
        var i18n = this.getI18n();
        this.selectedTermId = 0;
        if (this.termFormTitle) {
            this.termFormTitle.textContent = i18n.newTerm || '';
        }
        this.setTermField('id', 0);
        this.setTermField('name', '');
        this.setTermField('slug', '');
        this.setTermField('description', '');
        var termDelete = this.wrap.querySelector('.zerti-inv-categories__term-delete-btn');
        var termCancel = this.wrap.querySelector('.zerti-inv-categories__term-cancel-btn');
        if (termDelete) {
            termDelete.classList.add('d-none');
        }
        if (termCancel) {
            termCancel.classList.toggle('d-none', !asNew);
        }
        if (this.termFormError) {
            this.termFormError.classList.add('d-none');
        }
        if (asNew) {
            this.renderTerms();
        }
    };

    InvAttributesManager.prototype.editTerm = function (id) {
        var i18n = this.getI18n();
        var term = this.findTerm(id);
        if (!term) {
            return;
        }
        this.selectedTermId = id;
        if (this.termFormTitle) {
            this.termFormTitle.textContent = (i18n.editTerm || '') + (term.name || '');
        }
        this.setTermField('id', term.id);
        this.setTermField('name', term.name);
        this.setTermField('slug', term.slug);
        this.setTermField('description', term.description);
        var termDelete = this.wrap.querySelector('.zerti-inv-categories__term-delete-btn');
        var termCancel = this.wrap.querySelector('.zerti-inv-categories__term-cancel-btn');
        if (termDelete) {
            termDelete.classList.remove('d-none');
        }
        if (termCancel) {
            termCancel.classList.remove('d-none');
        }
        this.renderTerms();
    };

    InvAttributesManager.prototype.setTermField = function (name, value) {
        var el = this.termForm ? this.termForm.querySelector('[data-zerti-term-field="' + name + '"]') : null;
        if (el) {
            el.value = value == null ? '' : String(value);
        }
    };

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

    InvAttributesManager.prototype.saveTerm = function () {
        var self = this;
        var cfg = this.getCfg();
        var i18n = this.getI18n();
        if (this.selectedId < 1) {
            return;
        }
        var name = this.getTermField('name').trim();
        if (!name) {
            if (this.termFormError) {
                this.termFormError.textContent = i18n.termNameRequired || '';
                this.termFormError.classList.remove('d-none');
            }
            return;
        }

        var termSaveBtn = this.wrap.querySelector('.zerti-inv-categories__term-save-btn');
        if (termSaveBtn) {
            termSaveBtn.disabled = true;
        }

        postAction(cfg.saveTermAction || 'zerti_product_attribute_term_save', {
            attribute_id: this.selectedId,
            term_id: this.getTermField('id'),
            name: name,
            slug: this.getTermField('slug'),
            description: this.getTermField('description'),
        })
            .then(function (data) {
                if (!data || !data.success) {
                    var msg = data && data.data && data.data.message ? data.data.message : i18n.termSaveError || '';
                    throw new Error(msg);
                }
                self.applyPayload(data.data);
                self.resetTermForm(true);
                self.showFormSuccess(i18n.termSaved || '');
            })
            .catch(function (err) {
                if (self.termFormError) {
                    self.termFormError.textContent = err && err.message ? err.message : i18n.termSaveError || '';
                    self.termFormError.classList.remove('d-none');
                }
            })
            .finally(function () {
                if (termSaveBtn) {
                    termSaveBtn.disabled = false;
                }
            });
    };

    InvAttributesManager.prototype.confirmDeleteTerm = function () {
        var i18n = this.getI18n();
        var self = this;
        var term = this.findTerm(this.selectedTermId);
        var text = (i18n.deleteTermConfirm || '').replace('%s', term ? term.name : '');
        zertiDeleteConfirm(text, i18n).then(function (ok) {
            if (ok) {
                self.performDeleteTerm();
            }
        });
    };

    InvAttributesManager.prototype.performDeleteTerm = function () {
        var self = this;
        var cfg = this.getCfg();
        var i18n = this.getI18n();
        if (this.selectedId < 1 || this.selectedTermId < 1) {
            return;
        }

        postAction(cfg.deleteTermAction || 'zerti_product_attribute_term_delete', {
            attribute_id: this.selectedId,
            term_id: this.selectedTermId,
        })
            .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.applyPayload(data.data);
                self.resetTermForm(true);
            })
            .catch(function (err) {
                self.showFormError(err && err.message ? err.message : i18n.deleteError || '');
            });
    };

    function initInventoryAttributes(root) {
        if (!root) {
            return;
        }
        var cfg = readCfg();
        if (!cfg.ajaxUrl || !cfg.nonce) {
            return;
        }
        var wrap = findWrap(root);
        if (!wrap || wrap.getAttribute('data-zerti-inv-attributes-inited') === '1') {
            return;
        }
        /* Mark inited before rAF — boot() and admin-components can both call init in the same tick. */
        wrap.setAttribute('data-zerti-inv-attributes-inited', '1');
        window.requestAnimationFrame(function () {
            try {
                new InvAttributesManager(wrap);
            } catch (e) {
                wrap.removeAttribute('data-zerti-inv-attributes-inited');
            }
        });
    }

    window.zertiInitInventoryAttributes = initInventoryAttributes;
})();
