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

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

    function editI18n() {
        var cfg = readCfg();
        return (cfg && cfg.i18n) || {};
    }

    function escapeHtml(str) {
        return String(str)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
    }

    function setProductCatChevron(icon, isExpanded) {
        if (!icon) {
            return;
        }
        var cls =
            typeof window.zertiTreeChevronClass === 'function'
                ? window.zertiTreeChevronClass(isExpanded)
                : isExpanded
                  ? 'fa-chevron-down'
                  : 'fa-chevron-left';
        icon.classList.remove('fa-chevron-down', 'fa-chevron-left', 'fa-chevron-right');
        icon.classList.add(cls);
    }

    function debounce(fn, ms) {
        var timer = null;
        return function () {
            var ctx = this;
            var args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function () {
                fn.apply(ctx, args);
            }, ms);
        };
    }

    function syncStockFields(root) {
        var manage = root.querySelector('[data-zerti-product-manage-stock]');
        var qtyField = root.querySelector('.zerti-wc-form-field--stock-qty');
        var statusField = root.querySelector('.zerti-wc-form-field--stock-status');
        if (!manage) {
            return;
        }
        var on = manage.checked;
        if (qtyField) {
            qtyField.hidden = !on;
        }
        if (statusField) {
            statusField.hidden = on;
        }
    }

    function syncVirtualShipping(root) {
        var virtual = root.querySelector('[data-zerti-product-virtual]');
        var panel = root.querySelector('[data-zerti-wc-panel="shipping"]');
        var fields = root.querySelector('[data-zerti-shipping-fields]');
        var hint = root.querySelector('[data-zerti-shipping-hint]');
        var tabLi = root.querySelector('[data-zerti-shipping-tab]');
        var tabLink = tabLi ? tabLi.querySelector('[data-zerti-wc-tab]') : null;
        if (!virtual) {
            return;
        }
        var isVirtual = virtual.checked;
        if (fields) {
            fields.hidden = isVirtual;
        }
        if (hint) {
            hint.hidden = !isVirtual;
        }
        if (panel) {
            panel.classList.toggle('zerti-wc-panel--disabled', isVirtual);
        }
        if (tabLi) {
            tabLi.classList.toggle('disabled', isVirtual);
        }
        if (tabLink) {
            tabLink.setAttribute('aria-disabled', isVirtual ? 'true' : 'false');
        }
    }

    function syncDownloadablePanel(root) {
        var checkbox = root.querySelector('[data-zerti-product-downloadable]');
        var tabLi = root.querySelector('[data-zerti-downloads-tab]');
        var panel = root.querySelector('[data-zerti-wc-panel="downloads"]');
        var typeSelect = root.querySelector('[data-zerti-product-type]');
        var type = typeSelect ? typeSelect.value || 'simple' : 'simple';
        var typeAllowsDownloads = type === 'simple' || type === 'variable';
        if (!checkbox) {
            return;
        }
        var on = checkbox.checked && typeAllowsDownloads;
        if (tabLi) {
            tabLi.hidden = !on;
        }
        if (panel && !on) {
            panel.hidden = true;
            panel.classList.remove('active');
        }
    }

    function productTypeAllowsTab(type, tabId) {
        var map = {
            inventory: ['simple'],
            shipping: ['simple', 'variable'],
            linked: ['simple', 'grouped', 'external', 'variable'],
            attributes: ['simple', 'variable'],
            variations: ['variable'],
            advanced: ['simple', 'grouped', 'external', 'variable'],
            downloads: ['simple', 'variable'],
            general: ['simple', 'grouped', 'external', 'variable'],
        };
        var allowed = map[tabId];
        if (!allowed) {
            return true;
        }
        return allowed.indexOf(type) !== -1;
    }

    function syncProductType(root) {
        var select = root.querySelector('[data-zerti-product-type]');
        if (!select) {
            return;
        }
        var type = select.value || 'simple';

        var flags = root.querySelector('[data-zerti-product-flags]');
        if (flags) {
            flags.hidden = type === 'grouped' || type === 'external';
        }

        var pricing = root.querySelector('[data-zerti-general-pricing]');
        if (pricing) {
            pricing.hidden = type === 'grouped' || type === 'variable';
        }

        var external = root.querySelector('[data-zerti-general-external]');
        if (external) {
            external.hidden = type !== 'external';
        }

        var variableNotice = root.querySelector('[data-zerti-variable-notice]');
        if (variableNotice) {
            variableNotice.hidden = type !== 'variable';
        }

        root.querySelectorAll('[data-zerti-attr-variation-col]').forEach(function (el) {
            el.hidden = type !== 'variable';
        });

        var variationsTab = root.querySelector('[data-zerti-variations-tab]');
        if (variationsTab) {
            variationsTab.hidden = type !== 'variable';
        }

        var variationsPanel = root.querySelector('[data-zerti-wc-panel="variations"]');
        if (variationsPanel && type !== 'variable') {
            variationsPanel.hidden = true;
            variationsPanel.classList.remove('active');
        }

        var linkedStandard = root.querySelector('[data-zerti-linked-standard]');
        if (linkedStandard) {
            linkedStandard.hidden = type === 'grouped';
        }

        var linkedGrouped = root.querySelector('[data-zerti-linked-grouped]');
        if (linkedGrouped) {
            linkedGrouped.hidden = type !== 'grouped';
        }

        root.querySelectorAll('.zerti-wc-tabs__item').forEach(function (li) {
            var link = li.querySelector('[data-zerti-wc-tab]');
            if (!link) {
                return;
            }
            var tabId = link.getAttribute('data-zerti-wc-tab') || '';
            if (tabId === 'downloads') {
                return;
            }
            li.hidden = !productTypeAllowsTab(type, tabId);
        });

        syncDownloadablePanel(root);
        syncVirtualShipping(root);

        var activeItem = root.querySelector('.zerti-wc-tabs__item.active');
        if (activeItem && activeItem.hidden) {
            activateTab(root, 'general');
        }
    }

    function activateTab(root, tabId) {
        var tabItems = root.querySelectorAll('.zerti-wc-tabs__item');
        var tabLinks = root.querySelectorAll('[data-zerti-wc-tab]');
        var panels = root.querySelectorAll('[data-zerti-wc-panel]');
        tabLinks.forEach(function (link) {
            var active = link.getAttribute('data-zerti-wc-tab') === tabId;
            link.classList.toggle('active', active);
            link.setAttribute('aria-selected', active ? 'true' : 'false');
        });
        tabItems.forEach(function (item) {
            var link = item.querySelector('[data-zerti-wc-tab]');
            item.classList.toggle('active', link && link.getAttribute('data-zerti-wc-tab') === tabId);
        });
        panels.forEach(function (panel) {
            var active = panel.getAttribute('data-zerti-wc-panel') === tabId;
            panel.classList.toggle('active', active);
            panel.hidden = !active;
        });
    }

    function bindTabs(root) {
        root.querySelectorAll('[data-zerti-wc-tab]').forEach(function (link) {
            link.addEventListener('click', function (e) {
                e.preventDefault();
                var li = link.closest('.zerti-wc-tabs__item');
                if (li && li.classList.contains('disabled')) {
                    return;
                }
                var tabId = link.getAttribute('data-zerti-wc-tab');
                if (tabId) {
                    activateTab(root, tabId);
                }
            });
        });
    }

    function setImagePreview(root, url, id) {
        var preview = root.querySelector('.zerti-inventory-product-edit__image-preview');
        var input = root.querySelector('[data-zerti-product-image-id]');
        var removeBtn = root.querySelector('[data-zerti-product-remove-image]');
        if (input) {
            input.value = id > 0 ? String(id) : '';
        }
        if (!preview) {
            return;
        }
        preview.classList.toggle('zerti-inventory-product-edit__image-preview--empty', !url);
        if (url) {
            preview.innerHTML =
                '<img src="' +
                escapeHtml(url) +
                '" alt="" class="zerti-inventory-product-edit__image-img" decoding="async" />';
        } else {
            preview.innerHTML = '<i class="fa-solid fa-image" aria-hidden="true"></i>';
        }
        if (removeBtn) {
            removeBtn.hidden = !(id > 0);
        }
    }

    function galleryThumbUrl(attachment) {
        if (!attachment) {
            return '';
        }
        if (attachment.sizes && attachment.sizes.thumbnail && attachment.sizes.thumbnail.url) {
            return attachment.sizes.thumbnail.url;
        }
        if (attachment.sizes && attachment.sizes.medium && attachment.sizes.medium.url) {
            return attachment.sizes.medium.url;
        }

        return attachment.url || '';
    }

    function addGalleryItem(list, id, url) {
        if (!list || id < 1 || !url) {
            return;
        }
        if (list.querySelector('[data-id="' + String(id) + '"]')) {
            return;
        }
        var li = document.createElement('li');
        li.className = 'zerti-inventory-product-edit__gallery-item';
        li.setAttribute('data-id', String(id));
        var removeLabel = editI18n().remove || '';
        li.innerHTML =
            '<img src="' +
            escapeHtml(url) +
            '" alt="" decoding="async" />' +
            '<button type="button" class="btn btn-sm btn-outline-danger" data-zerti-gallery-remove aria-label="' +
            escapeHtml(removeLabel) +
            '">&times;</button>' +
            '<input type="hidden" name="gallery_ids[]" value="' +
            escapeHtml(String(id)) +
            '" />';
        list.appendChild(li);
    }

    function bindGallery(list) {
        if (!list || list.getAttribute('data-zerti-gallery-bound') === '1') {
            return;
        }
        list.setAttribute('data-zerti-gallery-bound', '1');
        list.addEventListener('click', function (e) {
            var btn = e.target.closest('[data-zerti-gallery-remove]');
            if (!btn) {
                return;
            }
            var item = btn.closest('.zerti-inventory-product-edit__gallery-item');
            if (item) {
                item.remove();
            }
        });
    }

    function openMediaFrame(cfg, options, onSelect) {
        if (!window.wp || !window.wp.media) {
            return null;
        }
        var frame = window.wp.media(
            Object.assign(
                {
                    library: { type: 'image' },
                },
                options
            )
        );
        frame.on('select', function () {
            var selection = frame.state().get('selection');
            if (onSelect) {
                onSelect(selection);
            }
        });
        frame.open();

        return frame;
    }

    function getExcludeProductId(form) {
        var wrap = form.closest('.zerti-inventory-product-edit');
        if (!wrap) {
            return 0;
        }
        return parseInt(String(wrap.getAttribute('data-zerti-product-id') || '0'), 10) || 0;
    }

    function linkedChipExists(chips, id) {
        return !!chips.querySelector('[data-id="' + String(id) + '"]');
    }

    function addLinkedChip(chips, field, product) {
        var id = parseInt(String(product.id), 10);
        if (id < 1 || linkedChipExists(chips, id)) {
            return;
        }
        var li = document.createElement('li');
        li.className = 'zerti-product-linked-picker__chip';
        li.setAttribute('data-id', String(id));
        var skuHtml =
            product.sku && String(product.sku) !== ''
                ? ' <span class="text-body-secondary small">(' + escapeHtml(product.sku) + ')</span>'
                : '';
        var removeLabel = editI18n().remove || '';
        li.innerHTML =
            '<span class="zerti-product-linked-picker__chip-label">' +
            escapeHtml(product.name || '') +
            skuHtml +
            '</span>' +
            '<input type="hidden" name="' +
            escapeHtml(field) +
            '[]" value="' +
            escapeHtml(String(id)) +
            '" />' +
            '<button type="button" class="btn-close btn-close-sm" data-zerti-linked-remove aria-label="' +
            escapeHtml(removeLabel) +
            '"></button>';
        chips.appendChild(li);
    }

    function bindLinkedPickers(form) {
        var cfg = readCfg();
        var excludeId = getExcludeProductId(form);

        form.querySelectorAll('[data-zerti-linked-picker]').forEach(function (picker) {
            var field = picker.getAttribute('data-zerti-linked-picker') || '';
            var chips = picker.querySelector('[data-zerti-linked-chips]');
            var input = picker.querySelector('[data-zerti-linked-search]');
            var results = picker.querySelector('[data-zerti-linked-results]');
            if (!chips || !input || !results) {
                return;
            }

            picker.addEventListener('click', function (e) {
                var removeBtn = e.target.closest('[data-zerti-linked-remove]');
                if (removeBtn) {
                    var chip = removeBtn.closest('.zerti-product-linked-picker__chip');
                    if (chip) {
                        chip.remove();
                    }
                }
            });

            var doSearch = debounce(function () {
                var term = (input.value || '').trim();
                if (term.length < 1) {
                    results.hidden = true;
                    results.innerHTML = '';
                    return;
                }
                var ajaxUrl = cfg.ajaxUrl || '';
                var nonce = cfg.nonce || '';
                var action = cfg.searchAction || 'zerti_product_search';
                if (!ajaxUrl || !nonce) {
                    return;
                }
                var body = new window.FormData();
                body.append('action', action);
                body.append('nonce', nonce);
                body.append('term', term);
                body.append('exclude', String(excludeId));

                window
                    .fetch(ajaxUrl, { method: 'POST', credentials: 'same-origin', body: body })
                    .then(function (res) {
                        return res.json();
                    })
                    .then(function (data) {
                        var products =
                            data && data.success && data.data && Array.isArray(data.data.products)
                                ? data.data.products
                                : [];
                        results.innerHTML = '';
                        if (products.length === 0) {
                            results.innerHTML =
                                '<li class="zerti-product-linked-picker__empty text-body-secondary small px-2 py-1">' +
                                escapeHtml((cfg.i18n && cfg.i18n.noProducts) || '') +
                                '</li>';
                        } else {
                            products.forEach(function (p) {
                                var li = document.createElement('li');
                                var btn = document.createElement('button');
                                btn.type = 'button';
                                btn.className = 'zerti-product-linked-picker__result';
                                var sku =
                                    p.sku && String(p.sku) !== ''
                                        ? ' — ' + escapeHtml(p.sku)
                                        : '';
                                btn.innerHTML = escapeHtml(p.name || '') + sku;
                                btn.addEventListener('click', function () {
                                    addLinkedChip(chips, field, p);
                                    input.value = '';
                                    results.hidden = true;
                                    results.innerHTML = '';
                                });
                                li.appendChild(btn);
                                results.appendChild(li);
                            });
                        }
                        results.hidden = false;
                    })
                    .catch(function () {
                        results.hidden = true;
                    });
            }, 280);

            input.addEventListener('input', doSearch);
            input.addEventListener('focus', function () {
                if ((input.value || '').trim() !== '') {
                    doSearch();
                }
            });

            document.addEventListener('click', function (e) {
                if (!picker.contains(e.target)) {
                    results.hidden = true;
                }
            });
        });
    }

    function splitTagParts(value) {
        return String(value || '').split(/[,،]/);
    }

    function parseTagsInput(value) {
        var parts = splitTagParts(value);
        var completed = [];
        var i;
        for (i = 0; i < parts.length - 1; i += 1) {
            var name = String(parts[i] || '').trim();
            if (name !== '') {
                completed.push(name);
            }
        }
        return {
            completed: completed,
            current: String(parts[parts.length - 1] || '').trim(),
        };
    }

    function tagsIncludeName(completed, name) {
        var needle = String(name || '').trim().toLowerCase();
        if (needle === '') {
            return false;
        }
        return completed.some(function (tag) {
            return String(tag).trim().toLowerCase() === needle;
        });
    }

    function formatTagsValue(completed) {
        if (!completed.length) {
            return '';
        }
        return completed.join(', ') + ', ';
    }

    function bindProductTags(form) {
        var cfg = readCfg();
        var wrap = form.querySelector('[data-zerti-product-tags]');
        if (!wrap) {
            return;
        }
        var input = wrap.querySelector('[data-zerti-product-tags-input]');
        var results = wrap.querySelector('[data-zerti-product-tags-results]');
        if (!input || !results || input.disabled || input.readOnly) {
            return;
        }

        var tagsPostbox = wrap.closest('.zerti-wc-postbox');

        function setTagsResultsOpen(open) {
            wrap.classList.toggle('zerti-product-tags-input--open', !!open);
            if (tagsPostbox) {
                tagsPostbox.classList.toggle('zerti-wc-postbox--tags-open', !!open);
            }
        }

        var doSearch = debounce(function () {
            var parsed = parseTagsInput(input.value);
            var term = parsed.current;
            if (term.length < 1) {
                results.hidden = true;
                results.innerHTML = '';
                setTagsResultsOpen(false);
                return;
            }

            var ajaxUrl = cfg.ajaxUrl || '';
            var nonce = cfg.tagsNonce || '';
            var action = cfg.tagsSearchAction || 'zerti_product_tags_search';
            if (!ajaxUrl || !nonce) {
                return;
            }

            var body = new window.FormData();
            body.append('action', action);
            body.append('nonce', nonce);
            body.append('term', term);

            window
                .fetch(ajaxUrl, { method: 'POST', credentials: 'same-origin', body: body })
                .then(function (res) {
                    return res.json();
                })
                .then(function (data) {
                    var tags =
                        data && data.success && data.data && Array.isArray(data.data.tags) ? data.data.tags : [];
                    results.innerHTML = '';
                    var shown = 0;
                    tags.forEach(function (tag) {
                        var name = tag && tag.name ? String(tag.name) : '';
                        if (name === '' || tagsIncludeName(parsed.completed, name)) {
                            return;
                        }
                        shown += 1;
                        var li = document.createElement('li');
                        var btn = document.createElement('button');
                        btn.type = 'button';
                        btn.className = 'zerti-product-tags-input__result';
                        btn.textContent = name;
                        btn.addEventListener('click', function () {
                            var latest = parseTagsInput(input.value);
                            var merged = latest.completed.slice();
                            if (!tagsIncludeName(merged, name)) {
                                merged.push(name);
                            }
                            input.value = formatTagsValue(merged);
                            results.hidden = true;
                            results.innerHTML = '';
                            setTagsResultsOpen(false);
                            input.focus();
                        });
                        li.appendChild(btn);
                        results.appendChild(li);
                    });
                    if (shown === 0) {
                        results.innerHTML =
                            '<li class="zerti-product-tags-input__empty text-body-secondary small px-2 py-1">' +
                            escapeHtml((cfg.i18n && cfg.i18n.noTags) || '') +
                            '</li>';
                    }
                    results.hidden = false;
                    setTagsResultsOpen(true);
                })
                .catch(function () {
                    results.hidden = true;
                    setTagsResultsOpen(false);
                });
        }, 280);

        input.addEventListener('input', doSearch);
        input.addEventListener('focus', function () {
            if (parseTagsInput(input.value).current !== '') {
                doSearch();
            }
        });

        document.addEventListener('click', function (e) {
            if (!wrap.contains(e.target)) {
                results.hidden = true;
                setTagsResultsOpen(false);
            }
        });
    }

    function bindProductBrands(form) {
        var cfg = readCfg();
        var wrap = form.querySelector('[data-zerti-product-brands]');
        if (!wrap) {
            return;
        }
        var input = wrap.querySelector('[data-zerti-product-brands-input]');
        var results = wrap.querySelector('[data-zerti-product-brands-results]');
        if (!input || !results || input.disabled || input.readOnly) {
            return;
        }

        var brandsPostbox = wrap.closest('.zerti-wc-postbox');

        function setBrandsResultsOpen(open) {
            wrap.classList.toggle('zerti-product-tags-input--open', !!open);
            if (brandsPostbox) {
                brandsPostbox.classList.toggle('zerti-wc-postbox--brands-open', !!open);
            }
        }

        var doSearch = debounce(function () {
            var parsed = parseTagsInput(input.value);
            var term = parsed.current;
            if (term.length < 1) {
                results.hidden = true;
                results.innerHTML = '';
                setBrandsResultsOpen(false);
                return;
            }

            var ajaxUrl = cfg.ajaxUrl || '';
            var nonce = cfg.brandsNonce || '';
            var action = cfg.brandsSearchAction || 'zerti_product_brands_search';
            if (!ajaxUrl || !nonce) {
                return;
            }

            var body = new window.FormData();
            body.append('action', action);
            body.append('nonce', nonce);
            body.append('term', term);

            window
                .fetch(ajaxUrl, { method: 'POST', credentials: 'same-origin', body: body })
                .then(function (res) {
                    return res.json();
                })
                .then(function (data) {
                    var brands =
                        data && data.success && data.data && Array.isArray(data.data.brands)
                            ? data.data.brands
                            : [];
                    results.innerHTML = '';
                    var shown = 0;
                    brands.forEach(function (brand) {
                        var name = brand && brand.name ? String(brand.name) : '';
                        if (name === '' || tagsIncludeName(parsed.completed, name)) {
                            return;
                        }
                        shown += 1;
                        var li = document.createElement('li');
                        var btn = document.createElement('button');
                        btn.type = 'button';
                        btn.className = 'zerti-product-tags-input__result';
                        btn.textContent = name;
                        btn.addEventListener('click', function () {
                            var latest = parseTagsInput(input.value);
                            var merged = latest.completed.slice();
                            if (!tagsIncludeName(merged, name)) {
                                merged.push(name);
                            }
                            input.value = formatTagsValue(merged);
                            results.hidden = true;
                            results.innerHTML = '';
                            setBrandsResultsOpen(false);
                            input.focus();
                        });
                        li.appendChild(btn);
                        results.appendChild(li);
                    });
                    if (shown === 0) {
                        results.innerHTML =
                            '<li class="zerti-product-tags-input__empty text-body-secondary small px-2 py-1">' +
                            escapeHtml((cfg.i18n && cfg.i18n.noBrands) || '') +
                            '</li>';
                    }
                    results.hidden = false;
                    setBrandsResultsOpen(true);
                })
                .catch(function () {
                    results.hidden = true;
                    setBrandsResultsOpen(false);
                });
        }, 280);

        input.addEventListener('input', doSearch);
        input.addEventListener('focus', function () {
            if (parseTagsInput(input.value).current !== '') {
                doSearch();
            }
        });

        document.addEventListener('click', function (e) {
            if (!wrap.contains(e.target)) {
                results.hidden = true;
                setBrandsResultsOpen(false);
            }
        });
    }

    function buildAttributeTaxonomyOptions(cfg) {
        var attrs = cfg.globalAttributes || {};
        var html = '';
        Object.keys(attrs).forEach(function (slug) {
            if (slug === '') {
                html +=
                    '<option value="">' +
                    escapeHtml(attrs[slug]) +
                    '</option>';
                return;
            }
            html +=
                '<option value="' +
                escapeHtml(slug) +
                '">' +
                escapeHtml(attrs[slug]) +
                '</option>';
        });
        return html;
    }

    function parseAttributeValueNames(values) {
        if (!values) {
            return [];
        }
        return String(values)
            .replace(/\s*[,،]+\s*/g, ' | ')
            .split('|')
            .map(function (part) {
                return part.trim();
            })
            .filter(Boolean);
    }

    function implodeAttributeValueNames(names) {
        if (!names || !names.length) {
            return '';
        }
        return names.filter(Boolean).join(' | ');
    }

    function $attrValuesSelectEl(select) {
        return window.jQuery && select ? window.jQuery(select) : null;
    }

    function destroyAttributeSelect2(row) {
        var globalWrap = row.querySelector('[data-zerti-attr-values-global]');
        var select = globalWrap ? globalWrap.querySelector('[data-zerti-attr-values-select]') : null;
        var $el = $attrValuesSelectEl(select);
        if ($el && $el.data('select2') && typeof $el.selectWoo === 'function') {
            $el.off('change.zertiAttrValues');
            $el.selectWoo('destroy');
        }
    }

    function initAttributeSelect2(row, attempt) {
        attempt = attempt || 0;
        var globalWrap = row.querySelector('[data-zerti-attr-values-global]');
        if (!globalWrap || globalWrap.classList.contains('d-none')) {
            return;
        }
        var select = globalWrap.querySelector('[data-zerti-attr-values-select]');
        var $el = $attrValuesSelectEl(select);
        if (!$el || !$el.length) {
            return;
        }
        if (typeof window.jQuery.fn.selectWoo !== 'function') {
            if (attempt < 40) {
                window.setTimeout(function () {
                    initAttributeSelect2(row, attempt + 1);
                }, 50);
            }
            return;
        }
        if ($el.data('select2')) {
            return;
        }
        var cfg = readCfg();
        var attrI18n = (cfg && cfg.i18n) || {};
        $el.addClass('zerti-admin-select');
        $el.selectWoo({
            width: '100%',
            placeholder: $el.data('placeholder') || attrI18n.selectValues || '',
            dropdownParent: window.jQuery(document.body),
            containerCssClass: 'zerti-admin-select2',
            dropdownCssClass: 'zerti-admin-select2-dropdown',
            selectionCssClass: 'zerti-admin-select2-selection',
        });
        $el.on('change.zertiAttrValues', function () {
            syncAttributeValuesFromSelect(row);
        });
    }

    function getAttributeSelectedNames(select) {
        if (!select) {
            return [];
        }
        var $el = $attrValuesSelectEl(select);
        if ($el && $el.data('select2')) {
            var val = $el.val();
            if (Array.isArray(val)) {
                return val.filter(Boolean);
            }
            return val ? [val] : [];
        }
        var names = [];
        Array.prototype.forEach.call(select.selectedOptions, function (opt) {
            names.push(opt.value);
        });
        return names;
    }

    function setAttributeSelectedNames(select, names) {
        if (!select) {
            return;
        }
        var $el = $attrValuesSelectEl(select);
        if ($el && $el.data('select2')) {
            $el.val(names).trigger('change');
            return;
        }
        var nameSet = {};
        names.forEach(function (name) {
            nameSet[name] = true;
        });
        Array.prototype.forEach.call(select.options, function (opt) {
            opt.selected = !!nameSet[opt.value];
        });
        select.dispatchEvent(new Event('change', { bubbles: true }));
    }

    function buildAttributeValuesCellHtml(index, cfg) {
        var attrI18n = (cfg && cfg.i18n) || {};
        var valuesField = 'attribute_rows[' + index + '][values]';
        return (
            '<td data-zerti-attr-values-cell>' +
            '<div class="zerti-product-attr-values" data-zerti-attr-values>' +
            '<input type="text" class="form-control form-control-sm" name="' +
            escapeHtml(valuesField) +
            '" data-zerti-attr-values-text data-zerti-attr-values-name="' +
            escapeHtml(valuesField) +
            '" dir="rtl" placeholder="' +
            escapeHtml(attrI18n.attributeValuesPlaceholder || '') +
            '" />' +
            '<div class="zerti-product-attr-values-global d-none" data-zerti-attr-values-global data-zerti-attr-attribute-id="0">' +
            '<select class="wc-enhanced-select zerti-product-attr-values-select" data-zerti-attr-values-select data-placeholder="' +
            escapeHtml(attrI18n.selectValues || '') +
            '" multiple aria-label="' +
            escapeHtml(attrI18n.selectValues || '') +
            '"></select>' +
            '<div class="zerti-product-attr-values-toolbar">' +
            '<button type="button" class="btn btn-outline-secondary btn-sm" data-zerti-attr-select-all>' +
            escapeHtml(attrI18n.selectAll || '') +
            '</button>' +
            '<button type="button" class="btn btn-outline-secondary btn-sm" data-zerti-attr-select-none>' +
            escapeHtml(attrI18n.selectNone || '') +
            '</button>' +
            '<button type="button" class="btn btn-outline-secondary btn-sm ms-auto" data-zerti-attr-create-value>' +
            escapeHtml(attrI18n.createValue || '') +
            '</button>' +
            '</div>' +
            '<input type="hidden" data-zerti-attr-values-input data-zerti-attr-values-name="' +
            escapeHtml(valuesField) +
            '" value="" />' +
            '</div></div></td>'
        );
    }

    function syncAttributeValuesFromSelect(row) {
        var globalWrap = row.querySelector('[data-zerti-attr-values-global]');
        if (!globalWrap) {
            return;
        }
        var hidden = globalWrap.querySelector('[data-zerti-attr-values-input]');
        var select = globalWrap.querySelector('[data-zerti-attr-values-select]');
        if (!hidden || !select) {
            return;
        }
        hidden.value = implodeAttributeValueNames(getAttributeSelectedNames(select));
    }

    function setAttributeValuesFieldName(row, isGlobal) {
        var textInput = row.querySelector('[data-zerti-attr-values-text]');
        var globalWrap = row.querySelector('[data-zerti-attr-values-global]');
        var hidden = globalWrap ? globalWrap.querySelector('[data-zerti-attr-values-input]') : null;
        var fieldName = '';
        if (textInput) {
            fieldName = textInput.getAttribute('data-zerti-attr-values-name') || '';
        } else if (hidden) {
            fieldName = hidden.getAttribute('data-zerti-attr-values-name') || '';
        }
        if (!fieldName) {
            return;
        }
        if (textInput) {
            if (isGlobal) {
                textInput.removeAttribute('name');
            } else {
                textInput.setAttribute('name', fieldName);
            }
        }
        if (hidden) {
            if (isGlobal) {
                hidden.setAttribute('name', fieldName);
            } else {
                hidden.removeAttribute('name');
            }
        }
    }

    function loadAttributeTerms(row, taxonomy, selectedNames) {
        var cfg = readCfg();
        var globalWrap = row.querySelector('[data-zerti-attr-values-global]');
        if (!globalWrap || !taxonomy) {
            return Promise.resolve();
        }
        var select = globalWrap.querySelector('[data-zerti-attr-values-select]');
        var hidden = globalWrap.querySelector('[data-zerti-attr-values-input]');
        if (!select || !hidden) {
            return Promise.resolve();
        }

        var selected = Array.isArray(selectedNames) ? selectedNames : parseAttributeValueNames(hidden.value);
        select.disabled = true;

        var body = new FormData();
        body.append('action', cfg.attrTermsAction || 'zerti_product_edit_attribute_terms');
        body.append('nonce', cfg.attrTermsNonce || '');
        body.append('taxonomy', taxonomy);

        return fetch(cfg.ajaxUrl || '', { method: 'POST', body: body, credentials: 'same-origin' })
            .then(function (res) {
                return res.json();
            })
            .then(function (json) {
                if (!json || !json.success || !json.data) {
                    throw new Error('load_failed');
                }
                var data = json.data;
                globalWrap.setAttribute('data-zerti-attr-attribute-id', String(data.attribute_id || 0));
                select.innerHTML = '';
                (data.terms || []).forEach(function (term) {
                    if (!term || !term.name) {
                        return;
                    }
                    var opt = document.createElement('option');
                    opt.value = term.name;
                    opt.textContent = term.name;
                    if (term.slug) {
                        opt.setAttribute('data-slug', term.slug);
                    }
                    select.appendChild(opt);
                });
                initAttributeSelect2(row);
                setAttributeSelectedNames(select, selected);
                syncAttributeValuesFromSelect(row);
            })
            .catch(function () {
                /* keep existing options when reload fails */
            })
            .finally(function () {
                select.disabled = false;
            });
    }

    function syncAttributeValuesMode(row, skipTermsReload) {
        var taxonomySelect = row.querySelector('[data-zerti-attr-taxonomy]');
        var textInput = row.querySelector('[data-zerti-attr-values-text]');
        var globalWrap = row.querySelector('[data-zerti-attr-values-global]');
        if (!taxonomySelect || !textInput || !globalWrap) {
            return;
        }

        var isGlobal = taxonomySelect.value !== '';
        var hidden = globalWrap.querySelector('[data-zerti-attr-values-input]');

        if (isGlobal) {
            var carry = textInput.value || '';
            if (hidden && carry) {
                hidden.value = carry;
            }
            textInput.classList.add('d-none');
            globalWrap.classList.remove('d-none');
            setAttributeValuesFieldName(row, true);
            if (!skipTermsReload) {
                destroyAttributeSelect2(row);
                loadAttributeTerms(
                    row,
                    taxonomySelect.value,
                    parseAttributeValueNames(hidden ? hidden.value : carry)
                );
            } else {
                initAttributeSelect2(row);
                syncAttributeValuesFromSelect(row);
            }
            return;
        }

        destroyAttributeSelect2(row);
        if (hidden && hidden.value) {
            textInput.value = hidden.value;
        }
        textInput.classList.remove('d-none');
        globalWrap.classList.add('d-none');
        setAttributeValuesFieldName(row, false);
    }

    function syncAttributeCustomName(row, skipTermsReload) {
        var select = row.querySelector('[data-zerti-attr-taxonomy]');
        var custom = row.querySelector('[data-zerti-attr-custom-name]');
        if (!select || !custom) {
            return;
        }
        var isGlobal = select.value !== '';
        custom.classList.toggle('d-none', isGlobal);
        if (isGlobal) {
            custom.value = '';
        }
        syncAttributeValuesMode(row, skipTermsReload);
    }

    function createAttributeValue(row) {
        var cfg = readCfg();
        var attrI18n = (cfg && cfg.i18n) || {};
        var globalWrap = row.querySelector('[data-zerti-attr-values-global]');
        if (!globalWrap) {
            return;
        }
        var attributeId = parseInt(globalWrap.getAttribute('data-zerti-attr-attribute-id') || '0', 10);
        if (attributeId < 1) {
            return;
        }
        var name = window.prompt(attrI18n.createValuePrompt || '');
        if (!name || !String(name).trim()) {
            return;
        }
        name = String(name).trim();

        var body = new FormData();
        body.append('action', cfg.attrSaveTermAction || 'zerti_product_attribute_term_save');
        body.append('nonce', cfg.attrTermsNonce || '');
        body.append('attribute_id', String(attributeId));
        body.append('name', name);

        fetch(cfg.ajaxUrl || '', { method: 'POST', body: body, credentials: 'same-origin' })
            .then(function (res) {
                return res.json();
            })
            .then(function (json) {
                if (!json || !json.success) {
                    throw new Error('save_failed');
                }
                var select = globalWrap.querySelector('[data-zerti-attr-values-select]');
                if (!select) {
                    return;
                }
                var item = json.data && json.data.item ? json.data.item : null;
                var termName = item && item.name ? item.name : name;
                var termSlug = item && item.slug ? item.slug : '';
                var existing = select.querySelector('option[value="' + CSS.escape(termName) + '"]');
                if (!existing) {
                    existing = document.createElement('option');
                    existing.value = termName;
                    existing.textContent = termName;
                    select.appendChild(existing);
                }
                if (termSlug) {
                    existing.setAttribute('data-slug', termSlug);
                }
                var selected = getAttributeSelectedNames(select);
                if (selected.indexOf(termName) === -1) {
                    selected.push(termName);
                }
                setAttributeSelectedNames(select, selected);
                syncAttributeValuesFromSelect(row);
            })
            .catch(function () {
                window.alert(attrI18n.termSaveFailed || '');
            });
    }

    function initAttributeRow(row) {
        var taxonomySelect = row.querySelector('[data-zerti-attr-taxonomy]');
        if (taxonomySelect) {
            taxonomySelect.addEventListener('change', function () {
                syncAttributeCustomName(row, false);
            });
        }

        var isGlobal = taxonomySelect && taxonomySelect.value !== '';
        var valuesSelect = row.querySelector('[data-zerti-attr-values-select]');
        var hasPrefilledTerms = valuesSelect && valuesSelect.options.length > 0;
        syncAttributeCustomName(row, isGlobal && hasPrefilledTerms);
        if (isGlobal) {
            initAttributeSelect2(row);
        }
    }

    function bindAttributeRows(form) {
        var cfg = readCfg();
        var tbody = form.querySelector('[data-zerti-attribute-rows]');
        if (!tbody) {
            return;
        }

        tbody.querySelectorAll('[data-zerti-attribute-row]').forEach(function (row) {
            initAttributeRow(row);
        });

        tbody.addEventListener('click', function (e) {
            var removeBtn = e.target.closest('[data-zerti-attribute-remove]');
            if (removeBtn) {
                var removeRow = removeBtn.closest('[data-zerti-attribute-row]');
                if (removeRow) {
                    removeRow.remove();
                }
                return;
            }

            var selectAllBtn = e.target.closest('[data-zerti-attr-select-all]');
            if (selectAllBtn) {
                var allRow = selectAllBtn.closest('[data-zerti-attribute-row]');
                var allSelect = allRow ? allRow.querySelector('[data-zerti-attr-values-select]') : null;
                if (allSelect) {
                    var allNames = [];
                    Array.prototype.forEach.call(allSelect.options, function (opt) {
                        allNames.push(opt.value);
                    });
                    setAttributeSelectedNames(allSelect, allNames);
                    syncAttributeValuesFromSelect(allRow);
                }
                return;
            }

            var selectNoneBtn = e.target.closest('[data-zerti-attr-select-none]');
            if (selectNoneBtn) {
                var noneRow = selectNoneBtn.closest('[data-zerti-attribute-row]');
                var noneSelect = noneRow ? noneRow.querySelector('[data-zerti-attr-values-select]') : null;
                if (noneSelect) {
                    setAttributeSelectedNames(noneSelect, []);
                    syncAttributeValuesFromSelect(noneRow);
                }
                return;
            }

            var createBtn = e.target.closest('[data-zerti-attr-create-value]');
            if (createBtn) {
                var createRow = createBtn.closest('[data-zerti-attribute-row]');
                if (createRow) {
                    createAttributeValue(createRow);
                }
            }
        });

        var addBtn = form.querySelector('[data-zerti-attribute-add]');
        if (addBtn) {
            addBtn.addEventListener('click', function () {
                var index = tbody.querySelectorAll('[data-zerti-attribute-row]').length;
                var tr = document.createElement('tr');
                tr.className = 'zerti-product-attribute-row';
                tr.setAttribute('data-zerti-attribute-row', '');
                var attrI18n = (cfg && cfg.i18n) || {};
                var typeSelect = form.querySelector('[data-zerti-product-type]');
                tr.innerHTML =
                    '<td><select class="form-select form-select-sm" name="attribute_rows[' +
                    index +
                    '][taxonomy]" data-zerti-attr-taxonomy>' +
                    buildAttributeTaxonomyOptions(cfg) +
                    '</select><input type="text" class="form-control form-control-sm mt-1" name="attribute_rows[' +
                    index +
                    '][name]" data-zerti-attr-custom-name placeholder="' +
                    escapeHtml(attrI18n.attributeNamePlaceholder || '') +
                    '" /></td>' +
                    buildAttributeValuesCellHtml(index, cfg) +
                    '<td class="text-center"><input class="form-check-input" type="checkbox" name="attribute_rows[' +
                    index +
                    '][visible]" value="1" checked /></td>' +
                    '<td class="text-center" data-zerti-attr-variation-col><input class="form-check-input" type="checkbox" name="attribute_rows[' +
                    index +
                    '][variation]" value="1" data-zerti-attr-variation' +
                    (typeSelect && typeSelect.value === 'variable' ? ' checked' : '') +
                    ' /></td>' +
                    '<td class="text-end"><button type="button" class="btn btn-outline-danger btn-sm" data-zerti-attribute-remove>&times;</button></td>';
                tbody.appendChild(tr);
                initAttributeRow(tr);
                syncProductType(form);
            });
        }

        form.addEventListener(
            'submit',
            function () {
                tbody.querySelectorAll('[data-zerti-attribute-row]').forEach(function (row) {
                    syncAttributeValuesFromSelect(row);
                });
            },
            true
        );
    }

    function slugifyAttributeKey(str) {
        return String(str || '')
            .trim()
            .toLowerCase()
            .replace(/\s+/g, '-')
            .replace(/[^a-z0-9\u0600-\u06FF_-]+/g, '')
            .replace(/-+/g, '-')
            .replace(/^-|-$/g, '');
    }

    function getAttributeValueOptions(row) {
        var taxonomySelect = row.querySelector('[data-zerti-attr-taxonomy]');
        var isGlobal = taxonomySelect && taxonomySelect.value !== '';
        var options = [];
        if (isGlobal) {
            var select = row.querySelector('[data-zerti-attr-values-select]');
            getAttributeSelectedNames(select).forEach(function (name) {
                var opt = select ? select.querySelector('option[value="' + CSS.escape(name) + '"]') : null;
                options.push({
                    slug: opt && opt.getAttribute('data-slug') ? opt.getAttribute('data-slug') : slugifyAttributeKey(name),
                    label: name,
                });
            });
        } else {
            var textInput = row.querySelector('[data-zerti-attr-values-text]');
            parseAttributeValueNames(textInput ? textInput.value : '').forEach(function (name) {
                options.push({ slug: name, label: name });
            });
        }
        return options;
    }

    function collectVariationAttributeDefs(form) {
        var defs = [];
        form.querySelectorAll('[data-zerti-attribute-row]').forEach(function (row) {
            var variationCb = row.querySelector('[data-zerti-attr-variation]');
            if (!variationCb || !variationCb.checked) {
                return;
            }
            var taxonomySelect = row.querySelector('[data-zerti-attr-taxonomy]');
            var taxonomy = taxonomySelect ? taxonomySelect.value : '';
            var customName = row.querySelector('[data-zerti-attr-custom-name]');
            var name = taxonomy === '' && customName ? customName.value.trim() : '';
            var key = taxonomy || slugifyAttributeKey(name);
            if (!key) {
                return;
            }
            var label = name;
            if (taxonomy && taxonomySelect) {
                label = taxonomySelect.options[taxonomySelect.selectedIndex]
                    ? taxonomySelect.options[taxonomySelect.selectedIndex].text
                    : taxonomy;
            }
            var options = getAttributeValueOptions(row);
            if (options.length === 0) {
                return;
            }
            defs.push({ key: key, label: label, options: options });
        });
        return defs;
    }

    function variationAttributesKey(attributes) {
        return Object.keys(attributes)
            .sort()
            .map(function (key) {
                return key + '=' + attributes[key];
            })
            .join('|');
    }

    function getExistingVariationKeys(tbody) {
        var keys = {};
        tbody.querySelectorAll('[data-zerti-variation-row]').forEach(function (row) {
            var attrs = {};
            row.querySelectorAll('[data-zerti-variation-attr]').forEach(function (input) {
                var attrKey = input.getAttribute('data-zerti-variation-attr') || '';
                if (attrKey) {
                    attrs[attrKey] = input.value;
                }
            });
            if (Object.keys(attrs).length > 0) {
                keys[variationAttributesKey(attrs)] = true;
            }
        });
        return keys;
    }

    function cartesianProduct(arrays) {
        if (!arrays.length) {
            return [[]];
        }
        return arrays.reduce(
            function (acc, curr) {
                var result = [];
                acc.forEach(function (a) {
                    curr.forEach(function (b) {
                        result.push(a.concat([b]));
                    });
                });
                return result;
            },
            [[]]
        );
    }

    function appendVariationHtml(container, html) {
        var temp = document.createElement('div');
        temp.innerHTML = html;
        var row = temp.firstElementChild;
        if (row && container) {
            container.appendChild(row);
        }
        return row || null;
    }

    function setVariationChevron(toggle, expanded) {
        if (!toggle) {
            return;
        }
        var icon = toggle.querySelector('.zerti-variation-item__chevron');
        if (icon) {
            icon.classList.remove('fa-chevron-down', 'fa-chevron-left');
            icon.classList.add(expanded ? 'fa-chevron-down' : 'fa-chevron-left');
        }
        toggle.setAttribute('aria-expanded', expanded ? 'true' : 'false');
    }

    function toggleVariationRow(row, forceExpanded) {
        if (!row) {
            return;
        }
        var body = row.querySelector('[data-zerti-variation-body]');
        var toggle = row.querySelector('[data-zerti-variation-toggle]');
        if (!body) {
            return;
        }
        var expanded = typeof forceExpanded === 'boolean' ? forceExpanded : body.hidden;
        body.hidden = !expanded;
        setVariationChevron(toggle, expanded);
        row.classList.toggle('zerti-variation-item--collapsed', !expanded);
    }

    function variationInputValue(el) {
        if (!el) {
            return '';
        }
        var val = String(el.value || '');
        if (typeof window.zertiToLatinDigits === 'function') {
            val = window.zertiToLatinDigits(val);
        }
        return val;
    }

    function reindexVariationRows(form) {
        var container = form.querySelector('[data-zerti-variation-rows]');
        if (!container) {
            return;
        }
        container.querySelectorAll('[data-zerti-variation-row]:not([data-zerti-variation-draft])').forEach(function (row, index) {
            row.querySelectorAll('[name^="variation_rows["]').forEach(function (input) {
                input.name = input.name.replace(/variation_rows\[\d+]/, 'variation_rows[' + index + ']');
            });
        });
    }

    function syncAllAttributeValueFields(form) {
        if (!form || !form.querySelectorAll) {
            return;
        }
        form.querySelectorAll('[data-zerti-attribute-row]').forEach(function (row) {
            syncAttributeValuesFromSelect(row);
        });
    }

    function clearVariationRowsFromFormData(body) {
        if (!body || typeof body.keys !== 'function' || typeof body.delete !== 'function') {
            return;
        }
        Array.from(body.keys()).forEach(function (key) {
            if (key.indexOf('variation_rows[') === 0) {
                body.delete(key);
            }
        });
    }

    function parseProductSaveResponse(res, cfg) {
        return res.text().then(function (text) {
            var trimmed = String(text || '').trim();
            if (!trimmed) {
                throw new Error((cfg.i18n && cfg.i18n.saveError) || 'Save failed');
            }
            try {
                return JSON.parse(trimmed);
            } catch (parseErr) {
                var plain = trimmed.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
                if (plain.length > 220) {
                    plain = plain.slice(0, 220) + '…';
                }
                throw new Error(plain || (cfg.i18n && cfg.i18n.saveError) || 'Save failed');
            }
        });
    }

    function syncVariationRowsToFormData(form, body) {
        var container = form.querySelector('[data-zerti-variation-rows]');
        if (!container || !body || typeof body.set !== 'function') {
            return;
        }

        reindexVariationRows(form);

        var rows = container.querySelectorAll('[data-zerti-variation-row]:not([data-zerti-variation-draft])');
        rows.forEach(function (row, index) {
            var prefix = 'variation_rows[' + index + ']';

            var variationId = row.querySelector('input[name*="[variation_id]"]');
            body.set(prefix + '[variation_id]', variationId ? variationInputValue(variationId) || '0' : '0');

            row.querySelectorAll('[data-zerti-variation-attr]').forEach(function (input) {
                var attrKey = input.getAttribute('data-zerti-variation-attr') || '';
                var attrVal = variationInputValue(input);
                if (attrKey && attrVal) {
                    body.set(prefix + '[attributes][' + attrKey + ']', attrVal);
                }
            });

            ['sku', 'regular_price', 'sale_price', 'stock_quantity'].forEach(function (field) {
                var el = row.querySelector('[name*="[' + field + ']"]');
                if (!el || el.disabled) {
                    return;
                }
                body.set(prefix + '[' + field + ']', variationInputValue(el));
            });

            var manage = row.querySelector('[data-zerti-variation-manage-stock]');
            if (manage && manage.checked) {
                body.set(prefix + '[manage_stock]', '1');
            }

            var enabled = row.querySelector('[name*="[enabled]"]');
            if (enabled && enabled.checked) {
                body.set(prefix + '[enabled]', '1');
            }
        });
    }

    function syncVariationStockFields(row) {
        if (!row) {
            return;
        }
        var manage = row.querySelector('[data-zerti-variation-manage-stock]');
        var stock = row.querySelector('[data-zerti-variation-stock]');
        if (stock && manage) {
            stock.disabled = !manage.checked;
        }
    }

    function buildVariationRowHtml(index, attributes, label, cfg) {
        var varI18n = (cfg && cfg.i18n) || {};
        var attrInputs = '';
        Object.keys(attributes).forEach(function (key) {
            attrInputs +=
                '<input type="hidden" name="variation_rows[' +
                index +
                '][attributes][' +
                escapeHtml(key) +
                ']" value="' +
                escapeHtml(attributes[key]) +
                '" data-zerti-variation-attr="' +
                escapeHtml(key) +
                '" />';
        });
        return (
            '<div class="zerti-variation-item" data-zerti-variation-row>' +
            '<input type="hidden" name="variation_rows[' +
            index +
            '][variation_id]" value="0" />' +
            attrInputs +
            '<div class="zerti-variation-item__head">' +
            '<button type="button" class="zerti-variation-item__toggle btn btn-link btn-sm" data-zerti-variation-toggle aria-expanded="true">' +
            '<i class="fa-solid fa-chevron-down zerti-variation-item__chevron" aria-hidden="true"></i>' +
            '<span class="zerti-variation-item__label" data-zerti-variation-label>' +
            escapeHtml(label || varI18n.variationLabel || 'Variation') +
            '</span></button>' +
            '<div class="zerti-variation-item__head-actions d-flex align-items-center gap-2">' +
            '<label class="form-check form-check-inline mb-0 small">' +
            '<input class="form-check-input" type="checkbox" name="variation_rows[' +
            index +
            '][enabled]" value="1" checked /> ' +
            escapeHtml(varI18n.enabled || 'Enabled') +
            '</label>' +
            '<button type="button" class="btn btn-outline-danger btn-sm" data-zerti-variation-remove aria-label="' +
            escapeHtml(varI18n.remove || '') +
            '">&times;</button>' +
            '</div></div>' +
            '<div class="zerti-variation-item__body" data-zerti-variation-body>' +
            '<div class="row g-2">' +
            '<div class="col-sm-6 col-md-4"><label class="form-label small mb-1">' +
            escapeHtml(varI18n.sku || 'SKU') +
            '</label><input type="text" class="form-control form-control-sm" name="variation_rows[' +
            index +
            '][sku]" dir="ltr" /></div>' +
            '<div class="col-sm-6 col-md-4"><label class="form-label small mb-1">' +
            escapeHtml(varI18n.regularPrice || 'Regular price') +
            '</label><input type="text" class="form-control form-control-sm wc_input_price" name="variation_rows[' +
            index +
            '][regular_price]" dir="ltr" inputmode="decimal" placeholder="0" /></div>' +
            '<div class="col-sm-6 col-md-4"><label class="form-label small mb-1">' +
            escapeHtml(varI18n.salePrice || 'Sale price') +
            '</label><input type="text" class="form-control form-control-sm wc_input_price" name="variation_rows[' +
            index +
            '][sale_price]" dir="ltr" inputmode="decimal" placeholder="0" /></div>' +
            '<div class="col-sm-6 col-md-4"><label class="form-check form-check-inline mb-1 small d-block">' +
            '<input class="form-check-input" type="checkbox" name="variation_rows[' +
            index +
            '][manage_stock]" value="1" data-zerti-variation-manage-stock /> ' +
            escapeHtml(varI18n.manageStock || 'Manage stock') +
            '</label><input type="text" class="form-control form-control-sm" name="variation_rows[' +
            index +
            '][stock_quantity]" dir="ltr" inputmode="numeric" placeholder="0" data-zerti-variation-stock disabled /></div>' +
            '</div></div></div>'
        );
    }

    function buildVariationDraftRowHtml(defs, cfg) {
        var varI18n = (cfg && cfg.i18n) || {};
        var picks = '';
        defs.forEach(function (def) {
            picks +=
                '<label class="d-flex flex-column gap-1 small mb-0"><span>' +
                escapeHtml(def.label) +
                '</span><select class="form-select form-select-sm" data-zerti-variation-pick data-zerti-variation-pick-key="' +
                escapeHtml(def.key) +
                '"><option value="">' +
                escapeHtml(varI18n.selectVariationValue || '') +
                '</option>';
            def.options.forEach(function (opt) {
                picks +=
                    '<option value="' +
                    escapeHtml(opt.slug) +
                    '" data-label="' +
                    escapeHtml(opt.label) +
                    '">' +
                    escapeHtml(opt.label) +
                    '</option>';
            });
            picks += '</select></label>';
        });
        return (
            '<div class="zerti-variation-item zerti-variation-item--draft" data-zerti-variation-row data-zerti-variation-draft>' +
            '<div class="zerti-variation-item__body p-3" data-zerti-variation-body>' +
            '<div class="d-flex flex-wrap gap-2 align-items-end" data-zerti-variation-picks>' +
            picks +
            '<button type="button" class="btn btn-outline-secondary btn-sm" data-zerti-variation-draft-add>' +
            escapeHtml(varI18n.addVariation || 'Add variation') +
            '</button>' +
            '<button type="button" class="btn btn-outline-danger btn-sm" data-zerti-variation-remove>&times;</button>' +
            '</div></div></div>'
        );
    }

    function finalizeVariationDraftRow(row, index, cfg, container) {
        var picksWrap = row.querySelector('[data-zerti-variation-picks]');
        if (!picksWrap) {
            return false;
        }
        var attributes = {};
        var labelParts = [];
        var complete = true;
        picksWrap.querySelectorAll('[data-zerti-variation-pick]').forEach(function (select) {
            var key = select.getAttribute('data-zerti-variation-pick-key') || '';
            var slug = select.value;
            if (!key || !slug) {
                complete = false;
                return;
            }
            attributes[key] = slug;
            var opt = select.options[select.selectedIndex];
            labelParts.push(opt && opt.getAttribute('data-label') ? opt.getAttribute('data-label') : slug);
        });
        if (!complete) {
            return false;
        }
        var newRow = appendVariationHtml(container, buildVariationRowHtml(index, attributes, labelParts.join(' / '), cfg));
        if (!newRow) {
            return false;
        }
        row.remove();
        syncVariationStockFields(newRow);
        toggleVariationRow(newRow, true);
        return true;
    }

    function bindVariationRows(form) {
        var cfg = readCfg();
        var container = form.querySelector('[data-zerti-variation-rows]');
        if (!container) {
            return;
        }

        container.querySelectorAll('[data-zerti-variation-row]:not([data-zerti-variation-draft])').forEach(function (row) {
            syncVariationStockFields(row);
            toggleVariationRow(row, true);
        });

        container.addEventListener('click', function (e) {
            var toggleBtn = e.target.closest('[data-zerti-variation-toggle]');
            if (toggleBtn) {
                e.preventDefault();
                toggleVariationRow(toggleBtn.closest('[data-zerti-variation-row]'));
                return;
            }

            var removeBtn = e.target.closest('[data-zerti-variation-remove]');
            if (removeBtn) {
                var removeRow = removeBtn.closest('[data-zerti-variation-row]');
                if (removeRow) {
                    removeRow.remove();
                }
                return;
            }

            var draftAddBtn = e.target.closest('[data-zerti-variation-draft-add]');
            if (draftAddBtn) {
                var draftRow = draftAddBtn.closest('[data-zerti-variation-row]');
                if (!draftRow) {
                    return;
                }
                var index = container.querySelectorAll('[data-zerti-variation-row]:not([data-zerti-variation-draft])').length;
                if (!finalizeVariationDraftRow(draftRow, index, cfg, container)) {
                    window.alert((cfg.i18n && cfg.i18n.selectVariationValue) || '');
                }
            }
        });

        container.addEventListener('change', function (e) {
            var manage = e.target.closest('[data-zerti-variation-manage-stock]');
            if (manage) {
                syncVariationStockFields(manage.closest('[data-zerti-variation-row]'));
            }
        });

        var generateBtn = form.querySelector('[data-zerti-variation-generate]');
        if (generateBtn) {
            generateBtn.addEventListener('click', function () {
                container.querySelectorAll('[data-zerti-variation-draft]').forEach(function (draft) {
                    draft.remove();
                });
                var defs = collectVariationAttributeDefs(form);
                if (defs.length === 0) {
                    window.alert((cfg.i18n && cfg.i18n.variationsHint) || '');
                    return;
                }
                var existing = getExistingVariationKeys(container);
                var optionSets = defs.map(function (def) {
                    return def.options.map(function (opt) {
                        return { key: def.key, slug: opt.slug, label: opt.label };
                    });
                });
                var combos = cartesianProduct(optionSets);
                var added = 0;
                combos.forEach(function (combo) {
                    var attributes = {};
                    var labelParts = [];
                    combo.forEach(function (item) {
                        attributes[item.key] = item.slug;
                        labelParts.push(item.label);
                    });
                    var sig = variationAttributesKey(attributes);
                    if (existing[sig]) {
                        return;
                    }
                    var index = container.querySelectorAll('[data-zerti-variation-row]:not([data-zerti-variation-draft])').length;
                    var newRow = appendVariationHtml(
                        container,
                        buildVariationRowHtml(index, attributes, labelParts.join(' / '), cfg)
                    );
                    if (newRow) {
                        syncVariationStockFields(newRow);
                        toggleVariationRow(newRow, true);
                        existing[sig] = true;
                        added += 1;
                    }
                });
                if (added === 0) {
                    window.alert((cfg.i18n && cfg.i18n.noNewVariations) || '');
                    return;
                }
                activateTab(form, 'variations');
                var hint = form.querySelector('[data-zerti-variations-hint]');
                if (hint && cfg.i18n && cfg.i18n.variationsGenerated) {
                    hint.textContent = cfg.i18n.variationsGenerated.replace('%d', String(added));
                }
            });
        }

        var addBtn = form.querySelector('[data-zerti-variation-add]');
        if (addBtn) {
            addBtn.addEventListener('click', function () {
                var defs = collectVariationAttributeDefs(form);
                if (defs.length === 0) {
                    window.alert((cfg.i18n && cfg.i18n.variationsHint) || '');
                    return;
                }
                appendVariationHtml(container, buildVariationDraftRowHtml(defs, cfg));
                activateTab(form, 'variations');
            });
        }

        form.addEventListener(
            'submit',
            function () {
                reindexVariationRows(form);
            },
            true
        );
    }

    function expandCategoryTreeItem(item) {
        if (!item) {
            return;
        }
        var toggle = item.querySelector(':scope > .zerti-product-cat-tree__row [data-zerti-product-cat-toggle]');
        var children = item.querySelector(':scope > .zerti-product-cat-tree__children');
        if (!children) {
            return;
        }
        children.hidden = false;
        item.setAttribute('aria-expanded', 'true');
        if (toggle) {
            toggle.setAttribute('aria-expanded', 'true');
            var icon = toggle.querySelector('i');
            setProductCatChevron(icon, true);
        }
    }

    function bindCategoryTree(form) {
        var tree = form.querySelector('[data-zerti-product-cat-tree]');
        if (!tree) {
            return;
        }

        tree.addEventListener('click', function (e) {
            var toggle = e.target.closest('[data-zerti-product-cat-toggle]');
            if (!toggle) {
                return;
            }
            e.preventDefault();
            var item = toggle.closest('[data-zerti-product-cat-tree-item]');
            if (!item) {
                return;
            }
            var children = item.querySelector(':scope > .zerti-product-cat-tree__children');
            if (!children) {
                return;
            }
            var expanded = toggle.getAttribute('aria-expanded') === 'true';
            children.hidden = expanded;
            toggle.setAttribute('aria-expanded', expanded ? 'false' : 'true');
            item.setAttribute('aria-expanded', expanded ? 'false' : 'true');
            var icon = toggle.querySelector('i');
            setProductCatChevron(icon, !expanded);
        });

        tree.querySelectorAll('input[type="checkbox"]:checked').forEach(function (cb) {
            var item = cb.closest('[data-zerti-product-cat-tree-item]');
            var ancestor = item ? item.parentElement : null;
            while (ancestor) {
                var parentItem = ancestor.closest
                    ? ancestor.closest('[data-zerti-product-cat-tree-item]')
                    : null;
                if (!parentItem) {
                    break;
                }
                expandCategoryTreeItem(parentItem);
                ancestor = parentItem.parentElement;
            }
        });
    }

    function bindDownloadRows(form) {
        var cfg = readCfg();
        var container = form.querySelector('[data-zerti-download-rows]');
        if (!container) {
            return;
        }

        container.addEventListener('click', function (e) {
            var removeBtn = e.target.closest('[data-zerti-download-remove]');
            if (removeBtn) {
                var row = removeBtn.closest('tr[data-zerti-download-row]');
                if (row) {
                    row.remove();
                }
                return;
            }
            var pickBtn = e.target.closest('[data-zerti-download-pick-file]');
            if (pickBtn && window.wp && window.wp.media) {
                var row = pickBtn.closest('[data-zerti-download-row]');
                var fileInput = row ? row.querySelector('[data-zerti-download-file]') : null;
                var fileI18n = (cfg && cfg.i18n) || {};
                var frame = window.wp.media({
                    title: fileI18n.pickFile || '',
                    button: { text: fileI18n.useFile || '' },
                    multiple: false,
                    library: { type: '' },
                });
                frame.on('select', function () {
                    var attachment = frame.state().get('selection').first().toJSON();
                    if (fileInput && attachment && attachment.url) {
                        fileInput.value = attachment.url;
                    }
                    var nameInput = row ? row.querySelector('input[name*="[name]"]') : null;
                    if (nameInput && nameInput.value === '' && attachment && attachment.filename) {
                        nameInput.value = attachment.filename;
                    }
                });
                frame.open();
            }
        });

        var addBtn = form.querySelector('[data-zerti-download-add]');
        if (addBtn) {
            addBtn.addEventListener('click', function () {
                var index = container.querySelectorAll('[data-zerti-download-row]').length;
                var tr = document.createElement('tr');
                tr.setAttribute('data-zerti-download-row', '');
                var downloadI18n = (cfg && cfg.i18n) || {};
                tr.innerHTML =
                    '<td><input type="hidden" name="download_rows[' +
                    index +
                    '][key]" value="" /><input type="text" class="form-control form-control-sm" name="download_rows[' +
                    index +
                    '][name]" /></td>' +
                    '<td><div class="input-group input-group-sm">' +
                    '<input type="url" class="form-control" name="download_rows[' +
                    index +
                    '][file]" dir="ltr" data-zerti-download-file />' +
                    '<button type="button" class="btn btn-outline-secondary" data-zerti-download-pick-file>' +
                    escapeHtml(downloadI18n.pickFileButton || '') +
                    '</button>' +
                    '</div></td>' +
                    '<td class="text-end"><button type="button" class="btn btn-outline-danger btn-sm" data-zerti-download-remove>&times;</button></td>';
                container.appendChild(tr);
            });
        }
    }

    function showFeedback(root, message, isError) {
        var el = root.querySelector('.zerti-inventory-product-edit__feedback');
        if (!el) {
            return;
        }
        el.textContent = message || '';
        el.classList.remove('alert-success', 'alert-danger');
        el.classList.add('alert', isError ? 'alert-danger' : 'alert-success', 'py-2', 'small', 'mb-0');
        el.hidden = !message;
    }

    function readCalendar() {
        var cfg = readCfg();
        if (cfg.calendar === 'gregorian' || cfg.calendar === 'jalali' || cfg.calendar === 'hijri') {
            return cfg.calendar;
        }
        var clock = typeof window.zertiAdminClock === 'object' && window.zertiAdminClock ? window.zertiAdminClock : null;
        if (clock && clock.calendar) {
            return clock.calendar;
        }
        var components = typeof window.zertiComponents === 'object' && window.zertiComponents ? window.zertiComponents : null;
        if (components && components.calendar) {
            return components.calendar;
        }
        return 'jalali';
    }

    function initProductDatepickers(form) {
        if (!form) {
            return;
        }
        var calendar = readCalendar();
        if (calendar === 'gregorian') {
            if (typeof window.zertiInitGregorianDatepickers === 'function') {
                window.zertiInitGregorianDatepickers(form);
            } else if (typeof window.zertiInitDatepickers === 'function') {
                window.zertiInitDatepickers(form);
            }
            return;
        }
        if (calendar === 'hijri') {
            if (typeof window.zertiInitHijriDatepickers === 'function') {
                window.zertiInitHijriDatepickers(form);
            } else if (typeof window.zertiInitDatepickers === 'function') {
                window.zertiInitDatepickers(form);
            }
            return;
        }
        if (typeof window.zertiInitDatepickers === 'function') {
            window.zertiInitDatepickers(form);
        } else if (typeof window.zertiInitJalaliDatepickers === 'function') {
            window.zertiInitJalaliDatepickers(form);
        }
    }

    function bindForm(root) {
        var form = root.querySelector('.zerti-inventory-product-edit__form');
        if (!form || form.getAttribute('data-zerti-product-readonly') === '1') {
            return;
        }

        var cfg = readCfg();
        bindTabs(form);
        syncProductType(form);

        var typeSelect = form.querySelector('[data-zerti-product-type]');
        if (typeSelect) {
            typeSelect.addEventListener('change', function () {
                syncProductType(form);
            });
        }

        var manage = form.querySelector('[data-zerti-product-manage-stock]');
        if (manage) {
            manage.addEventListener('change', function () {
                syncStockFields(form);
            });
            syncStockFields(form);
        }

        var virtual = form.querySelector('[data-zerti-product-virtual]');
        if (virtual) {
            virtual.addEventListener('change', function () {
                syncVirtualShipping(form);
            });
        }

        var downloadable = form.querySelector('[data-zerti-product-downloadable]');
        if (downloadable) {
            downloadable.addEventListener('change', function () {
                syncDownloadablePanel(form);
            });
        }

        bindLinkedPickers(form);
        bindProductTags(form);
        bindProductBrands(form);
        bindAttributeRows(form);
        bindVariationRows(form);
        bindDownloadRows(form);
        bindCategoryTree(form);

        initProductDatepickers(form);

        if (typeof window.zertiInitRichEditors === 'function') {
            window.zertiInitRichEditors(form);
        }

        var pickBtn = form.querySelector('[data-zerti-product-pick-image]');
        if (pickBtn && window.wp && window.wp.media) {
            var imageFrame = null;
            pickBtn.addEventListener('click', function () {
                if (imageFrame) {
                    imageFrame.open();
                    return;
                }
                var mediaI18n = (cfg && cfg.i18n) || {};
                imageFrame = openMediaFrame(
                    cfg,
                    {
                        title: mediaI18n.pickImage || '',
                        button: {
                            text: mediaI18n.useImage || '',
                        },
                        multiple: false,
                    },
                    function (selection) {
                        var attachment = selection.first().toJSON();
                        setImagePreview(
                            form,
                            galleryThumbUrl(attachment) || attachment.url || '',
                            attachment.id || 0
                        );
                    }
                );
            });
        }

        var removeImg = form.querySelector('[data-zerti-product-remove-image]');
        if (removeImg) {
            removeImg.addEventListener('click', function () {
                setImagePreview(form, '', 0);
            });
        }

        var galleryList = form.querySelector('[data-zerti-product-gallery]');
        bindGallery(galleryList);

        var pickGallery = form.querySelector('[data-zerti-product-pick-gallery]');
        if (pickGallery && galleryList) {
            var galleryFrame = null;
            pickGallery.addEventListener('click', function () {
                if (galleryFrame) {
                    galleryFrame.open();
                    return;
                }
                var galleryI18n = (cfg && cfg.i18n) || {};
                galleryFrame = openMediaFrame(
                    cfg,
                    {
                        title: galleryI18n.pickGallery || '',
                        button: {
                            text: galleryI18n.addGallery || '',
                        },
                        multiple: true,
                    },
                    function (selection) {
                        selection.each(function (att) {
                            var json = att.toJSON();
                            addGalleryItem(
                                galleryList,
                                json.id || 0,
                                galleryThumbUrl(json) || json.url || ''
                            );
                        });
                    }
                );
            });
        }

        form.addEventListener('submit', function (e) {
            e.preventDefault();
            var submitCfg = readCfg();
            var ajaxUrl = submitCfg.ajaxUrl || '';
            var nonce = submitCfg.nonce || '';
            var action = submitCfg.saveAction || 'zerti_product_save';
            var i18n = (submitCfg && submitCfg.i18n) || {};
            if (!ajaxUrl || !nonce) {
                showFeedback(form, i18n.saveError || '', true);
                return;
            }

            if (typeof window.zertiSyncRichEditors === 'function') {
                window.zertiSyncRichEditors(form);
            }

            var saveBtn = form.querySelector('.zerti-inventory-product-save');
            var saveBtnDefaultLabel = saveBtn ? saveBtn.textContent : '';
            if (saveBtn) {
                saveBtn.disabled = true;
                saveBtn.setAttribute('aria-busy', 'true');
                saveBtn.textContent = i18n.applying || i18n.saving || 'Applying…';
            }
            showFeedback(form, i18n.saving || '', false);

            syncAllAttributeValueFields(form);
            reindexVariationRows(form);

            var body = new window.FormData(form);
            var typeSelect = form.querySelector('[data-zerti-product-type]');
            if (typeSelect && typeSelect.name) {
                body.set(typeSelect.name, typeSelect.value || 'simple');
            }
            clearVariationRowsFromFormData(body);
            syncVariationRowsToFormData(form, body);
            body.append('action', action);
            body.append('nonce', nonce);

            window
                .fetch(ajaxUrl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: body,
                })
                .then(function (res) {
                    return parseProductSaveResponse(res, submitCfg);
                })
                .then(function (data) {
                    if (!data || !data.success) {
                        var msg =
                            (data && data.data && data.data.message) ||
                            i18n.saveError ||
                            '';
                        throw new Error(msg);
                    }
                    showFeedback(form, (data.data && data.data.message) || '', false);
                    if (typeof window.zertiRefreshDashboard === 'function') {
                        window.zertiRefreshDashboard();
                    }
                    var newId = data.data && data.data.product_id ? parseInt(String(data.data.product_id), 10) : 0;
                    if (newId > 0 && typeof window.zertiOpenInventoryProductEdit === 'function') {
                        window.zertiOpenInventoryProductEdit(newId, true);
                    } else if (typeof window.zertiReloadInventoryPartial === 'function') {
                        window.zertiReloadInventoryPartial('warehouse');
                    }
                })
                .catch(function (err) {
                    showFeedback(form, err && err.message ? err.message : '', true);
                })
                .finally(function () {
                    if (saveBtn) {
                        saveBtn.disabled = false;
                        saveBtn.removeAttribute('aria-busy');
                        if (saveBtnDefaultLabel) {
                            saveBtn.textContent = saveBtnDefaultLabel;
                        }
                    }
                });
        });
    }

    window.zertiInitProductEdit = function (root) {
        if (!root) {
            root = document;
        }
        var editors = root.querySelectorAll
            ? root.querySelectorAll('.zerti-inventory-product-edit')
            : [];
        if (!editors.length && root.classList && root.classList.contains('zerti-inventory-product-edit')) {
            editors = [root];
        }
        editors.forEach(function (el) {
            if (el.getAttribute('data-zerti-product-edit-bound') === '1') {
                return;
            }
            el.setAttribute('data-zerti-product-edit-bound', '1');
            bindForm(el);
        });
    };
})(window, document);
