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

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

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

    function panelRoot(root) {
        if (!root) {
            return null;
        }
        return root.querySelector('[data-zerti-coupons-root="1"]');
    }

    function activateCouponTab(form, tabId) {
        if (!form) {
            return;
        }
        form.querySelectorAll('[data-zerti-coupon-tab]').forEach(function (link) {
            var active = link.getAttribute('data-zerti-coupon-tab') === tabId;
            link.classList.toggle('active', active);
            link.setAttribute('aria-selected', active ? 'true' : 'false');
            var item = link.closest('.zerti-wc-tabs__item');
            if (item) {
                item.classList.toggle('active', active);
            }
        });
        form.querySelectorAll('[data-zerti-coupon-panel]').forEach(function (panel) {
            var active = panel.getAttribute('data-zerti-coupon-panel') === tabId;
            panel.classList.toggle('active', active);
            panel.hidden = !active;
        });
    }

    function bindCouponTabs(form) {
        if (!form) {
            return;
        }
        form.querySelectorAll('[data-zerti-coupon-tab]').forEach(function (link) {
            if (link.__zertiCouponTabBound) {
                return;
            }
            link.__zertiCouponTabBound = true;
            link.addEventListener('click', function (event) {
                event.preventDefault();
                var tabId = link.getAttribute('data-zerti-coupon-tab');
                if (tabId) {
                    activateCouponTab(form, tabId);
                }
            });
        });
    }

    function setupCouponTabs(form) {
        if (!form) {
            return;
        }
        var wcMeta = form.querySelector('.zerti-coupon-wc-meta');
        if (!wcMeta) {
            return;
        }
        var panelWrap = wcMeta.querySelector('.panel-wrap.coupon_data');
        if (!panelWrap) {
            return;
        }

        form.querySelectorAll('.zerti-coupon-section-heading').forEach(function (node) {
            node.remove();
        });

        var labels = i18n();
        var sections = [
            {
                id: 'general_coupon_data',
                tab: 'general',
                label: labels.sectionGeneral || 'General',
                icon: 'fa-sliders',
            },
            {
                id: 'usage_restriction_coupon_data',
                tab: 'usage-restriction',
                label: labels.sectionUsageRestriction || 'Usage restriction',
                icon: 'fa-filter',
            },
            {
                id: 'usage_limit_coupon_data',
                tab: 'usage-limit',
                label: labels.sectionUsageLimits || 'Usage limits',
                icon: 'fa-gauge-high',
            },
        ];

        var layout = document.createElement('div');
        layout.className = 'zerti-settings-layout zerti-wc-product-data';

        var body = document.createElement('div');
        body.className = 'zerti-settings-layout__body d-flex flex-column flex-lg-row';

        var nav = document.createElement('nav');
        nav.className = 'zerti-settings-nav';
        nav.setAttribute('aria-label', labels.couponEditorTabs || labels.sectionGeneral || 'Coupon sections');

        var tabList = document.createElement('ul');
        tabList.className = 'zerti-wc-tabs zerti-settings-tabs wc-tabs nav flex-lg-column';
        tabList.setAttribute('role', 'tablist');

        var main = document.createElement('div');
        main.className = 'zerti-settings-main flex-grow-1 min-w-0';

        sections.forEach(function (section, index) {
            var wcPanel = panelWrap.querySelector('#' + section.id);
            if (!wcPanel) {
                return;
            }
            var isActive = index === 0;

            var li = document.createElement('li');
            li.className = 'zerti-wc-tabs__item' + (isActive ? ' active' : '');
            li.setAttribute('role', 'presentation');

            var link = document.createElement('a');
            link.href = '#' + section.id;
            link.className = 'zerti-wc-tabs__link' + (isActive ? ' active' : '');
            link.setAttribute('role', 'tab');
            link.setAttribute('data-zerti-coupon-tab', section.tab);
            link.setAttribute('aria-selected', isActive ? 'true' : 'false');
            link.setAttribute('id', 'zerti-coupon-tab-' + section.tab);
            link.innerHTML =
                '<i class="fa-solid ' +
                section.icon +
                '" aria-hidden="true"></i> <span>' +
                section.label +
                '</span>';

            li.appendChild(link);
            tabList.appendChild(li);

            var shell = document.createElement('div');
            shell.className = 'zerti-settings-panel' + (isActive ? ' active' : '');
            shell.setAttribute('data-zerti-coupon-panel', section.tab);
            shell.setAttribute('role', 'tabpanel');
            shell.setAttribute('aria-labelledby', 'zerti-coupon-tab-' + section.tab);
            shell.hidden = !isActive;
            shell.appendChild(wcPanel);
            main.appendChild(shell);
        });

        nav.appendChild(tabList);
        body.appendChild(nav);
        body.appendChild(main);
        layout.appendChild(body);

        wcMeta.parentNode.insertBefore(layout, wcMeta);
        wcMeta.remove();

        var basics = form.querySelector('.zerti-coupon-form-basics');
        var generalShell = main.querySelector('[data-zerti-coupon-panel="general"]');
        if (basics && generalShell) {
            generalShell.insertBefore(basics, generalShell.firstChild);
        }

        bindCouponTabs(form);
        styleCouponNativeFields(form);
        activateCouponTab(form, 'general');
    }

    function styleCouponNativeFields(scope) {
        if (!scope) {
            return;
        }
        scope.querySelectorAll(
            '.zerti-coupon-form-basics input:not([type="hidden"]), .form-field input:not([type="checkbox"]):not([type="hidden"]):not([type="radio"])'
        ).forEach(function (el) {
            if (el.classList.contains('zerti-admin-date-input') || el.id === 'expiry_date') {
                return;
            }
            el.classList.add('form-control');
            el.classList.remove('form-control-sm', 'short', 'wc-input-text', 'input-text', 'date-picker');
        });
        scope.querySelectorAll('.form-field select:not(.select2-hidden-accessible)').forEach(function (el) {
            el.classList.add('form-select', 'zerti-admin-select');
            el.classList.remove('short', 'select');
            el.style.width = '100%';
            el.style.maxWidth = 'none';
        });
        scope.querySelectorAll('.wc-product-search, .wc-customer-search, .wc-page-search, .wc-enhanced-select').forEach(function (el) {
            el.style.width = '100%';
            el.style.maxWidth = 'none';
        });
    }

    function applyCouponSelect2Skin(scope) {
        if (!scope || typeof window.jQuery === 'undefined') {
            return;
        }
        var $ = window.jQuery;
        if (typeof $.fn.selectWoo !== 'function') {
            return;
        }
        $(scope)
            .find('.wc-enhanced-select, .wc-product-search, .wc-customer-search, .wc-page-search')
            .filter('.select2-hidden-accessible')
            .each(function () {
                var $el = $(this);
                if ($el.data('zertiCouponSelect2')) {
                    return;
                }
                var instance = $el.data('select2');
                if (!instance || !instance.options) {
                    return;
                }
                var opts = $.extend(true, {}, instance.options.options, {
                    width: '100%',
                    dropdownParent: $(document.body),
                    containerCssClass: 'zerti-admin-select2',
                    dropdownCssClass: 'zerti-admin-select2-dropdown',
                    selectionCssClass: 'zerti-admin-select2-selection',
                });
                $el.selectWoo('destroy');
                $el.removeClass('enhanced');
                $el.selectWoo(opts);
                $el.addClass('enhanced');
                $el.data('zertiCouponSelect2', 1);
            });
    }

    function initWcCouponFields(scope) {
        if (!scope || typeof window.jQuery === 'undefined') {
            return;
        }
        var $ = window.jQuery;
        styleCouponNativeFields(scope);
        $(document.body).trigger('wc-enhanced-select-init');
        applyCouponSelect2Skin(scope);
        if ($('#discount_type', scope).length) {
            $('#discount_type', scope).trigger('change');
        }
        if (typeof $.fn.tipTip === 'function') {
            $('.tips, .help_tip, .woocommerce-help-tip', scope).tipTip({
                attribute: 'data-tip',
                fadeIn: 50,
                fadeOut: 50,
                delay: 200,
            });
        }
        var generateBtn = scope.querySelector('[data-zerti-coupon-generate]');
        if (generateBtn && !generateBtn.__zertiBound) {
            generateBtn.__zertiBound = true;
            generateBtn.addEventListener('click', function (e) {
                e.preventDefault();
                var cfg = window.zerti_woocommerce_admin_meta_boxes_coupon || {};
                var chars = cfg.characters || 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
                var len = Number(cfg.char_length || 8);
                var result = '';
                for (var i = 0; i < len; i++) {
                    result += chars.charAt(Math.floor(Math.random() * chars.length));
                }
                result = (cfg.prefix || '') + result + (cfg.suffix || '');
                var titleInput = scope.querySelector('#title');
                if (titleInput) {
                    titleInput.value = result;
                    titleInput.focus();
                }
            });
        }
    }

    function destroyWcCouponFields(scope) {
        if (!scope || typeof window.jQuery === 'undefined') {
            return;
        }
        if (typeof window.zertiResetAdminDateInputs === 'function') {
            window.zertiResetAdminDateInputs(scope);
        }
        var $ = window.jQuery;
        $('.wc-enhanced-select, .wc-product-search, .wc-customer-search, .wc-page-search', scope)
            .filter('.select2-hidden-accessible')
            .each(function () {
                var $el = $(this);
                $el.removeData('zertiCouponSelect2');
                try {
                    $el.selectWoo('destroy');
                } catch (e) {}
            });
    }

    function formPayload(form) {
        var payload = {};
        if (!form) {
            return payload;
        }
        var elements = form.querySelectorAll('input, select, textarea');
        elements.forEach(function (el) {
            if (!el.name || el.disabled) {
                return;
            }
            var name = el.name;
            if (el.type === 'checkbox') {
                if (el.checked) {
                    payload[name] = el.value || '1';
                }
                return;
            }
            if (el.type === 'radio') {
                if (el.checked) {
                    payload[name] = el.value;
                }
                return;
            }
            if (name.endsWith('[]')) {
                var key = name.slice(0, -2);
                if (!Array.isArray(payload[key])) {
                    payload[key] = [];
                }
                if (el.tagName === 'SELECT' && el.multiple) {
                    Array.prototype.forEach.call(el.selectedOptions, function (opt) {
                        payload[key].push(opt.value);
                    });
                } else if (el.value !== '') {
                    payload[key].push(el.value);
                }
                return;
            }
            if (el.tagName === 'SELECT' && el.multiple) {
                payload[name] = [];
                Array.prototype.forEach.call(el.selectedOptions, function (opt) {
                    payload[name].push(opt.value);
                });
                return;
            }
            payload[name] = el.value;
        });
        return payload;
    }

    function postForm(action, payload) {
        var cfg = readCfg();
        var body = new window.FormData();
        body.append('action', action);
        body.append('nonce', cfg.nonce || '');
        Object.keys(payload).forEach(function (key) {
            var value = payload[key];
            if (Array.isArray(value)) {
                value.forEach(function (item) {
                    body.append(key + '[]', item);
                });
                return;
            }
            body.append(key, value);
        });
        return window
            .fetch(cfg.ajaxUrl || '', {
                method: 'POST',
                credentials: 'same-origin',
                body: body,
            })
            .then(function (res) {
                return res.json();
            });
    }

    function clearAlertAutoHide(el) {
        if (!el) {
            return;
        }
        if (el.__zertiAlertHideTimer) {
            window.clearTimeout(el.__zertiAlertHideTimer);
            el.__zertiAlertHideTimer = null;
        }
        el.style.opacity = '';
        el.style.transition = '';
    }

    function scheduleAlertAutoHide(el, onHide) {
        if (!el) {
            return;
        }
        clearAlertAutoHide(el);
        el.__zertiAlertHideTimer = window.setTimeout(function () {
            el.__zertiAlertHideTimer = null;
            el.style.transition = 'opacity 0.2s ease';
            el.style.opacity = '0';
            window.setTimeout(function () {
                if (el.classList.contains('d-none')) {
                    el.style.opacity = '';
                    el.style.transition = '';
                    return;
                }
                if (typeof onHide === 'function') {
                    onHide();
                }
                el.style.opacity = '';
                el.style.transition = '';
            }, 220);
        }, 5000);
    }

    function clearFormMessages(form) {
        if (!form) {
            return;
        }
        var err = form.querySelector('.zerti-coupon-form-error');
        var ok = form.querySelector('.zerti-coupon-form-success');
        if (err) {
            clearAlertAutoHide(err);
            err.classList.add('d-none');
            err.textContent = '';
        }
        if (ok) {
            clearAlertAutoHide(ok);
            ok.classList.add('d-none');
            ok.textContent = '';
        }
    }

    function showFormMessage(form, kind, message) {
        if (!form) {
            return;
        }
        var text = message == null ? '' : String(message);
        var err = form.querySelector('.zerti-coupon-form-error');
        var ok = form.querySelector('.zerti-coupon-form-success');
        if (err) {
            clearAlertAutoHide(err);
            var showErr = kind === 'error' && text !== '';
            err.classList.toggle('d-none', !showErr);
            err.textContent = showErr ? text : '';
        }
        if (ok) {
            clearAlertAutoHide(ok);
            var showOk = kind === 'success' && text !== '';
            ok.classList.toggle('d-none', !showOk);
            ok.textContent = showOk ? text : '';
            if (showOk) {
                scheduleAlertAutoHide(ok, function () {
                    ok.classList.add('d-none');
                    ok.textContent = '';
                });
            }
        }
    }

    function showListFlash(panel, message) {
        if (!panel) {
            return;
        }
        var flash = panel.querySelector('.zerti-coupons-list-flash');
        if (!flash) {
            return;
        }
        clearAlertAutoHide(flash);
        var text = message == null ? '' : String(message);
        if (text === '') {
            flash.classList.add('d-none');
            flash.textContent = '';
            return;
        }
        flash.textContent = text;
        flash.classList.remove('d-none');
        scheduleAlertAutoHide(flash, function () {
            flash.classList.add('d-none');
            flash.textContent = '';
        });
    }

    function hideListFlash(panel) {
        showListFlash(panel, '');
    }

    function escapeHtml(text) {
        return String(text)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function createCouponEditorLoadOverlay(label) {
        var overlay = document.createElement('div');
        overlay.className = 'zerti-component-load-overlay text-body-secondary';
        overlay.setAttribute('data-zerti-coupon-editor-load', '1');
        overlay.setAttribute('role', 'status');
        overlay.setAttribute('aria-live', 'polite');
        overlay.innerHTML =
            '<span class="spinner-border spinner-border-sm" aria-hidden="true"></span>' +
            '<span>' + escapeHtml(label || 'Loading') + '</span>';
        return overlay;
    }

    function attachCouponEditorLoadOverlay(scrollEl, label) {
        if (!scrollEl) {
            return null;
        }
        detachCouponEditorLoadOverlay(scrollEl);
        scrollEl.classList.add('zerti-coupons-editor-scroll--loading');
        scrollEl.setAttribute('aria-busy', 'true');
        var overlay = createCouponEditorLoadOverlay(label);
        scrollEl.appendChild(overlay);
        return overlay;
    }

    function detachCouponEditorLoadOverlay(scrollEl) {
        if (!scrollEl) {
            return;
        }
        var overlay = scrollEl.querySelector('.zerti-component-load-overlay[data-zerti-coupon-editor-load]');
        if (overlay) {
            overlay.remove();
        }
        scrollEl.classList.remove('zerti-coupons-editor-scroll--loading');
        scrollEl.removeAttribute('aria-busy');
    }

    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 ensureFinancialBundles(callback) {
        if (typeof window.zertiEnsureTabBundles === 'function') {
            window.zertiEnsureTabBundles('financial', callback);
            return;
        }
        callback();
    }

    function whenCouponEditorAssetsReady(callback, attempt) {
        attempt = attempt || 0;
        var $ = window.jQuery;
        var ready = typeof $ === 'function' && typeof $.fn.selectWoo === 'function';
        if (ready || attempt >= 120) {
            callback();
            return;
        }
        window.requestAnimationFrame(function () {
            whenCouponEditorAssetsReady(callback, attempt + 1);
        });
    }

    function couponDeleteConfirmMessage(form) {
        var labels = i18n();
        var template = labels.deleteConfirm || 'Are you sure you want to delete coupon «%s»?';
        var code = '';
        if (form) {
            var codeInput = form.querySelector('#title');
            if (codeInput && codeInput.value) {
                code = String(codeInput.value);
            }
        }
        var msg = template.replace('%s', code);
        if (typeof window.zertiLocalizeDigits === 'function') {
            return window.zertiLocalizeDigits(msg);
        }
        return msg;
    }

    function zertiInitFinancialCoupons(root) {
        var panel = panelRoot(root);
        if (!panel) {
            return;
        }

        var listView = panel.querySelector('[data-zerti-coupons-list]');
        var editorView = panel.querySelector('[data-zerti-coupons-editor]');
        var editorScroll = panel.querySelector('.zerti-coupons-editor-scroll');
        var editorSlot = panel.querySelector('[data-zerti-coupons-editor-slot]');
        var editorTitle = panel.querySelector('[data-zerti-coupons-editor-title]');
        var deleteBtn = panel.querySelector('[data-zerti-coupons-delete]');
        var saveBtn = panel.querySelector('[data-zerti-coupons-save]');
        var backBtn = panel.querySelector('[data-zerti-coupons-back]');
        var addBtn = panel.querySelector('[data-zerti-coupons-add]');

        if (!listView || !editorView || !editorSlot) {
            return;
        }

        if (panel.__zertiCouponsPanelCleanup) {
            panel.__zertiCouponsPanelCleanup();
            panel.__zertiCouponsPanelCleanup = null;
        }

        var labels = i18n();
        var activeCouponId = 0;
        var gridHandle = null;
        var pendingListRefresh = false;
        var pendingListFlash = '';

        function setEditorVisible(show) {
            listView.classList.toggle('d-none', show);
            editorView.classList.toggle('d-none', !show);
            editorView.setAttribute('aria-hidden', show ? 'false' : 'true');
            if (show) {
                hideListFlash(panel);
            }
        }

        function loadEditor(couponId) {
            activeCouponId = couponId > 0 ? couponId : 0;
            setEditorVisible(true);
            if (editorTitle) {
                editorTitle.textContent =
                    activeCouponId > 0
                        ? (labels.editCouponTitle || 'Edit coupon') + (couponId ? '' : '')
                        : labels.addCouponTitle || 'Add coupon';
            }
            if (deleteBtn) {
                deleteBtn.classList.toggle('d-none', activeCouponId <= 0);
            }
            destroyWcCouponFields(editorSlot);
            editorSlot.innerHTML = '';
            attachCouponEditorLoadOverlay(editorScroll, labels.loading || 'Loading');

            ensureFinancialBundles(function () {
                whenCouponEditorAssetsReady(function () {
                    postForm('zerti_wc_coupon_editor', { coupon_id: String(activeCouponId) })
                        .then(function (data) {
                            if (!data || !data.success || !data.data || typeof data.data.html !== 'string') {
                                throw new Error('bad response');
                            }
                            editorSlot.innerHTML = data.data.html;
                            var form = editorSlot.querySelector('[data-zerti-coupon-form]');
                            setupCouponTabs(form);
                            initWcCouponFields(editorSlot);
                            if (typeof window.zertiInitDatepickers === 'function') {
                                window.zertiInitDatepickers(editorSlot);
                            } else if (typeof window.zertiInitJalaliDatepickers === 'function') {
                                window.zertiInitJalaliDatepickers(editorSlot);
                            }
                            if (editorTitle && form) {
                                var codeInput = form.querySelector('#title');
                                if (activeCouponId > 0 && codeInput && codeInput.value) {
                                    editorTitle.textContent =
                                        (labels.editCouponTitle || 'Edit coupon') + ': ' + codeInput.value;
                                }
                            }
                        })
                        .catch(function () {
                            editorSlot.innerHTML =
                                '<p class="alert alert-danger mb-0">' +
                                (labels.loadFailed || 'Failed to load coupon.') +
                                '</p>';
                        })
                        .finally(function () {
                            detachCouponEditorLoadOverlay(editorScroll);
                        });
                });
            });
        }

        function backToList(refresh) {
            detachCouponEditorLoadOverlay(editorScroll);
            destroyWcCouponFields(editorSlot);
            editorSlot.innerHTML = '';
            activeCouponId = 0;
            setEditorVisible(false);
            if ((refresh || pendingListRefresh) && gridHandle && typeof gridHandle.refresh === 'function') {
                gridHandle.refresh();
            }
            if (pendingListFlash) {
                showListFlash(panel, pendingListFlash);
                pendingListFlash = '';
            }
            pendingListRefresh = false;
        }

        if (typeof window.zertiInitCouponsTable === 'function') {
            gridHandle = window.zertiInitCouponsTable(panel, {
                onRowClick: function (row) {
                    if (row && row.id) {
                        loadEditor(Number(row.id));
                    }
                },
            });
        } else {
            (function retryGridInit(attempt) {
                if (!panel.isConnected || gridHandle) {
                    return;
                }
                if (typeof window.zertiInitCouponsTable === 'function') {
                    gridHandle = window.zertiInitCouponsTable(panel, {
                        onRowClick: function (row) {
                            if (row && row.id) {
                                loadEditor(Number(row.id));
                            }
                        },
                    });
                    return;
                }
                if (attempt < 80) {
                    window.requestAnimationFrame(function () {
                        retryGridInit(attempt + 1);
                    });
                }
            })(0);
        }

        function onAddClick() {
            loadEditor(0);
        }

        function onBackClick() {
            backToList(pendingListRefresh);
        }

        function onSaveClick() {
            var form = editorSlot.querySelector('[data-zerti-coupon-form]');
            if (!form) {
                return;
            }
            clearFormMessages(form);
            if (saveBtn) {
                saveBtn.disabled = true;
            }
            attachCouponEditorLoadOverlay(editorScroll, labels.saving || 'Saving');
            var payload = formPayload(form);
            postForm('zerti_wc_coupon_save', payload)
                .then(function (data) {
                    if (!data || !data.success) {
                        var msg =
                            (data && data.data && data.data.message) ||
                            labels.saveFailed ||
                            'Could not save coupon.';
                        showFormMessage(form, 'error', msg);
                        return;
                    }
                    var successMsg = labels.saveSuccess || 'Coupon saved.';
                    showFormMessage(form, 'success', successMsg);
                    pendingListRefresh = true;
                    pendingListFlash = successMsg;
                    if (data.data && data.data.id) {
                        activeCouponId = Number(data.data.id);
                        if (deleteBtn) {
                            deleteBtn.classList.remove('d-none');
                        }
                    }
                    if (gridHandle && typeof gridHandle.refresh === 'function') {
                        gridHandle.refresh();
                    }
                })
                .catch(function () {
                    showFormMessage(form, 'error', labels.saveFailed || 'Could not save coupon.');
                })
                .finally(function () {
                    detachCouponEditorLoadOverlay(editorScroll);
                    if (saveBtn) {
                        saveBtn.disabled = false;
                    }
                });
        }

        function onDeleteClick() {
            if (activeCouponId <= 0) {
                return;
            }
            var form = editorSlot.querySelector('[data-zerti-coupon-form]');
            zertiDeleteConfirm(couponDeleteConfirmMessage(form), labels).then(function (ok) {
                if (!ok) {
                    return;
                }
                if (deleteBtn) {
                    deleteBtn.disabled = true;
                }
                postForm('zerti_wc_coupon_delete', { coupon_id: String(activeCouponId) })
                    .then(function (data) {
                        if (!data || !data.success) {
                            window.alert(labels.deleteFailed || 'Could not delete coupon.');
                            return;
                        }
                        pendingListRefresh = true;
                        pendingListFlash = labels.deleteSuccess || 'Coupon deleted.';
                        backToList(true);
                    })
                    .catch(function () {
                        window.alert(labels.deleteFailed || 'Could not delete coupon.');
                    })
                    .finally(function () {
                        if (deleteBtn) {
                            deleteBtn.disabled = false;
                        }
                    });
            });
        }

        if (addBtn) {
            addBtn.addEventListener('click', onAddClick);
        }
        if (backBtn) {
            backBtn.addEventListener('click', onBackClick);
        }
        if (saveBtn) {
            saveBtn.addEventListener('click', onSaveClick);
        }
        if (deleteBtn) {
            deleteBtn.addEventListener('click', onDeleteClick);
        }

        panel.__zertiCouponsPanelCleanup = function () {
            if (addBtn) {
                addBtn.removeEventListener('click', onAddClick);
            }
            if (backBtn) {
                backBtn.removeEventListener('click', onBackClick);
            }
            if (saveBtn) {
                saveBtn.removeEventListener('click', onSaveClick);
            }
            if (deleteBtn) {
                deleteBtn.removeEventListener('click', onDeleteClick);
            }
            destroyWcCouponFields(editorSlot);
            detachCouponEditorLoadOverlay(editorScroll);
            if (gridHandle && typeof gridHandle.destroy === 'function') {
                gridHandle.destroy();
            }
            gridHandle = null;
        };
    }

    window.zertiInitFinancialCoupons = zertiInitFinancialCoupons;
})(window, document);
