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

    var paymentsUrlSyncTimer = null;

    function zertiPersianToLatinDigits(str) {
        return window.zertiToLatinDigits(str);
    }

    function zertiLatinToPersianDigits(str) {
        return window.zertiLocalizeDigits(str);
    }

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

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

    function isValidPaymentsScope(cfg, scope) {
        if (!scope) {
            return false;
        }
        var slugs = Array.isArray(cfg.paymentsScopeSlugs) ? cfg.paymentsScopeSlugs : ['today_success', 'period_success'];
        return slugs.indexOf(scope) !== -1;
    }

    function readPaymentsScope(cfg) {
        try {
            var sp = new URLSearchParams(window.location.search);
            var pScope = cfg.paramPaymentsScope || 'zerti_payments_scope';
            var raw = sp.get(pScope);
            return raw && isValidPaymentsScope(cfg, String(raw)) ? String(raw) : '';
        } catch (eScope) {
            return '';
        }
    }

    function paymentsScopeFilterLabel(cfg, scope) {
        var i18n = (cfg && cfg.i18n) || {};
        if (scope === 'today_success') {
            return i18n.scopeFilterTodaySuccess || '';
        }
        if (scope === 'period_success') {
            return i18n.scopeFilterPeriodSuccess || '';
        }
        return '';
    }

    function readUrlParams(cfg) {
        var out = { search: '', orderCol: NaN, orderDir: 'desc', paymentsScope: '' };
        try {
            var sp = new URLSearchParams(window.location.search);
            var ps = cfg.paramSearch || 'zerti_payments_search';
            var pc = cfg.paramOrderCol || 'zerti_payments_order_col';
            var pd = cfg.paramOrderDir || 'zerti_payments_order_dir';
            out.search = sp.get(ps) ? String(sp.get(ps)) : '';
            var colRaw = sp.get(pc);
            if (colRaw !== null && colRaw !== '') {
                out.orderCol = parseInt(colRaw, 10);
            }
            var dirRaw = (sp.get(pd) || 'desc').toLowerCase();
            out.orderDir = dirRaw === 'asc' ? 'asc' : 'desc';
            out.paymentsScope = readPaymentsScope(cfg);
        } catch (e1) {
            return out;
        }
        return out;
    }

    function replacePaymentsGridUrlParams(api, cfg, searchInput) {
        if (paymentsUrlSyncTimer) {
            window.clearTimeout(paymentsUrlSyncTimer);
        }
        paymentsUrlSyncTimer = window.setTimeout(function () {
            paymentsUrlSyncTimer = null;
            try {
                var u = new URL(window.location.href);
                var ps = cfg.paramSearch || 'zerti_payments_search';
                var pc = cfg.paramOrderCol || 'zerti_payments_order_col';
                var pd = cfg.paramOrderDir || 'zerti_payments_order_dir';
                var q = searchInput && searchInput.value ? zertiPersianToLatinDigits(searchInput.value).trim() : '';
                if (q) {
                    u.searchParams.set(ps, q);
                } else {
                    u.searchParams.delete(ps);
                }
                var state = api.getColumnState ? api.getColumnState() : [];
                var sorted = state.filter(function (col) {
                    return col.sort;
                })[0];
                if (sorted && typeof sorted.colId === 'string' && /^c[0-9]+$/.test(sorted.colId)) {
                    u.searchParams.set(pc, sorted.colId.slice(1));
                    u.searchParams.set(pd, sorted.sort === 'asc' ? 'asc' : 'desc');
                }
                var next = u.pathname + u.search + window.location.hash;
                var cur = window.location.pathname + window.location.search + window.location.hash;
                if (next !== cur) {
                    window.history.replaceState(null, '', next);
                }
            } catch (e2) {}
        }, 280);
    }

    function htmlRenderer(params) {
        return params.value || '';
    }

    function numericComparator(key) {
        return function (a, b, nodeA, nodeB) {
            var av = nodeA && nodeA.data ? Number(nodeA.data[key] || 0) : 0;
            var bv = nodeB && nodeB.data ? Number(nodeB.data[key] || 0) : 0;
            return av - bv;
        };
    }

    function textComparator(a, b) {
        return String(a || '').localeCompare(String(b || ''), 'fa');
    }

    function zertiEffectivePaymentsSearchTerm(input) {
        var value = input && input.value ? zertiPersianToLatinDigits(input.value).trim() : '';
        var length = typeof Array.from === 'function' ? Array.from(value).length : value.length;
        return length >= 3 ? value : '';
    }

    function shopStatusLabelFromSlug(cfg, slug) {
        if (!slug || !cfg.statusLabels || typeof cfg.statusLabels !== 'object') {
            return '';
        }
        var label = cfg.statusLabels[slug];
        return label !== undefined && label !== null ? String(label) : '';
    }

    function shopStatusSlugFromLabel(cfg, label) {
        if (!label || !cfg.statusLabels || typeof cfg.statusLabels !== 'object') {
            return '';
        }
        var needle = String(label);
        var slugs = Object.keys(cfg.statusLabels);
        for (var i = 0; i < slugs.length; i += 1) {
            var slug = slugs[i];
            if (String(cfg.statusLabels[slug]) === needle) {
                return slug;
            }
        }
        return '';
    }

    function createFilterOptionCache() {
        return window.zertiAgGridCreateFilterOptionCache({
            gateway: [],
            statusText: [],
        });
    }

    function seedStatusFilterOptions(filterOptionCache, cfg) {
        if (!cfg.statusLabels || typeof cfg.statusLabels !== 'object') {
            return;
        }
        var labels = [];
        Object.keys(cfg.statusLabels).forEach(function (slug) {
            var label = String(cfg.statusLabels[slug]);
            if (label !== '' && labels.indexOf(label) === -1) {
                labels.push(label);
            }
        });
        labels.sort(textComparator);
        filterOptionCache.statusText = labels;
    }

    function seedGatewayFilterOptions(filterOptionCache, cfg) {
        var labels = [];
        if (Array.isArray(cfg.gatewayLabels)) {
            cfg.gatewayLabels.forEach(function (label) {
                var value = label !== undefined && label !== null ? String(label) : '';
                if (value !== '' && value !== '—' && labels.indexOf(value) === -1) {
                    labels.push(value);
                }
            });
        }
        labels.sort(textComparator);
        filterOptionCache.gateway = labels;
    }

    function appendPaymentsFilterOptions(filterOptionCache, rows) {
        ['gateway', 'statusText'].forEach(function (field) {
            var existing = {};
            filterOptionCache[field].forEach(function (value) {
                existing[value] = true;
            });
            rows.forEach(function (row) {
                var value = row && row[field] !== undefined && row[field] !== null ? String(row[field]) : '';
                if (value === '' || value === '—' || existing[value]) {
                    return;
                }
                existing[value] = true;
                filterOptionCache[field].push(value);
            });
            filterOptionCache[field].sort(textComparator);
        });
        if (typeof filterOptionCache.notifyFilterOptionsChanged === 'function') {
            filterOptionCache.notifyFilterOptionsChanged();
        }
    }

    function dropdownFilter(filterOptionCache, field) {
        return window.zertiAgGridInlineDropdownFilterColumn({
            cache: filterOptionCache,
            field: field,
            selectClass: 'zerti-payments-grid-filter-select',
            filterAllLabel: gridI18n().filterAll || '',
        });
    }

    function applyPaymentsStatusFilter(api, cfg, statusSlug) {
        if (!api || !api.setFilterModel || !statusSlug) {
            return;
        }
        var label = shopStatusLabelFromSlug(cfg, statusSlug);
        if (!label) {
            return;
        }
        api.setFilterModel({
            c6: { value: label },
        });
    }

    function installSearchToolbar(wrap, cfg, initialSearch) {
        if (!wrap) {
            return null;
        }

        var toolbar = wrap.querySelector('.zerti-payments-grid-toolbar');
        if (!toolbar) {
            toolbar = document.createElement('div');
            toolbar.className = 'zerti-payments-grid-toolbar';
            toolbar.setAttribute('role', 'toolbar');
            var searchSlot = document.createElement('div');
            searchSlot.className = 'zerti-payments-grid-toolbar-search';
            toolbar.appendChild(searchSlot);
            wrap.insertBefore(toolbar, wrap.firstChild);
        }

        var searchSlot = toolbar.querySelector('.zerti-payments-grid-toolbar-search');
        if (!searchSlot) {
            searchSlot = document.createElement('div');
            searchSlot.className = 'zerti-payments-grid-toolbar-search';
            toolbar.insertBefore(searchSlot, toolbar.firstChild);
        }
        searchSlot.innerHTML = '';

        var label = document.createElement('label');
        label.className = 'zerti-payments-grid-search-label form-label mb-0';
        label.setAttribute('for', 'zertiPaymentsGridSearch');

        var icon = document.createElement('i');
        icon.className = 'fa-solid fa-magnifying-glass zerti-payments-grid-search-icon';
        icon.setAttribute('aria-hidden', 'true');

        var input = document.createElement('input');
        input.type = 'search';
        input.id = 'zertiPaymentsGridSearch';
        input.className = 'form-control form-control-sm zerti-payments-grid-search-input';
        input.setAttribute('autocomplete', 'off');
        input.setAttribute('dir', window.zertiAdminTextDirection ? window.zertiAdminTextDirection() : 'rtl');
        input.setAttribute(
            'aria-label',
            cfg.searchAriaLabel || ''
        );
        input.placeholder = cfg.searchPlaceholder || '';
        input.value = initialSearch ? zertiLatinToPersianDigits(initialSearch) : '';

        label.appendChild(icon);
        label.appendChild(input);
        searchSlot.appendChild(label);

        return input;
    }

    function getZertiAdminRoot() {
        return document.getElementById('zertiAdmin');
    }

    function getPaymentsAlertOverlay() {
        var root = getZertiAdminRoot();
        if (!root) {
            return null;
        }
        var ov = root.querySelector('.zerti-payments-grid-alert-overlay');
        if (!ov) {
            ov = document.createElement('div');
            ov.className = 'zerti-products-grid-alert-overlay zerti-payments-grid-alert-overlay';
            ov.setAttribute('role', 'dialog');
            ov.setAttribute('aria-modal', 'true');
            ov.setAttribute('aria-labelledby', 'zertiPaymentsGridAlertMessage');
            ov.hidden = true;
            ov.innerHTML =
                '<div class="zerti-products-grid-alert-dialog alert alert-danger">' +
                '<p id="zertiPaymentsGridAlertMessage" class="zerti-products-grid-alert-message mb-0"></p>' +
                '<button type="button" class="btn btn-light zerti-products-grid-alert-ok"></button>' +
                '</div>';
            root.appendChild(ov);
            var okBtn = ov.querySelector('.zerti-products-grid-alert-ok');
            if (okBtn) {
                okBtn.addEventListener('click', function () {
                    ov.hidden = true;
                });
            }
        }
        return ov;
    }

    function showPaymentsGridAlert(message, cfg) {
        if (!message) {
            return;
        }
        var ov = getPaymentsAlertOverlay();
        if (!ov) {
            window.alert(message);
            return;
        }
        var i18n = (cfg && cfg.i18n) || {};
        var msgEl = ov.querySelector('#zertiPaymentsGridAlertMessage');
        var okBtn = ov.querySelector('.zerti-products-grid-alert-ok');
        if (msgEl) {
            msgEl.textContent = message;
        }
        if (okBtn) {
            okBtn.textContent = i18n.alertOk || '';
        }
        ov.hidden = false;
        if (okBtn && typeof okBtn.focus === 'function') {
            okBtn.focus();
        }
    }

    function fetchPaymentsTotal(cfg, callback) {
        var ajaxUrl = cfg.ajaxUrl || window.ajaxurl || '';
        if (!ajaxUrl || typeof callback !== 'function') {
            callback(-1);
            return;
        }
        var body = new URLSearchParams({
            action: cfg.action || 'zerti_payments_grid',
            nonce: cfg.nonce || '',
            start: '0',
            limit: '1',
            search: '',
            sort_model: '[]',
            filter_model: '{}',
            payments_scope: readPaymentsScope(cfg),
        });
        fetch(ajaxUrl, {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
            body: body.toString(),
        })
            .then(function (res) {
                return res.json();
            })
            .then(function (json) {
                if (!json || !json.success || !json.data) {
                    callback(-1);
                    return;
                }
                var total = Number(json.data.total);
                callback(Number.isFinite(total) && total >= 0 ? total : -1);
            })
            .catch(function () {
                callback(-1);
            });
    }

    function submitPaymentsExport(cfg) {
        var ajaxUrl = cfg.ajaxUrl || window.ajaxurl || '';
        if (!ajaxUrl) {
            return;
        }

        var form = document.createElement('form');
        form.method = 'POST';
        form.action = ajaxUrl;
        form.target = '_self';
        form.style.display = 'none';

        var fields = {
            action: cfg.exportAction || 'zerti_payments_export',
            nonce: cfg.exportNonce || '',
        };

        Object.keys(fields).forEach(function (name) {
            var input = document.createElement('input');
            input.type = 'hidden';
            input.name = name;
            input.value = fields[name];
            form.appendChild(input);
        });

        document.body.appendChild(form);
        form.submit();
        window.setTimeout(function () {
            if (form.parentNode) {
                form.parentNode.removeChild(form);
            }
        }, 0);
    }

    function resetPaymentsExportButton(btn, defaultLabelEl, defaultLabel) {
        btn.disabled = false;
        btn.removeAttribute('aria-busy');
        if (defaultLabelEl) {
            defaultLabelEl.textContent = defaultLabel;
        }
    }

    function runPaymentsExport(cfg, gridEl, searchInput, btn, defaultLabelEl, defaultLabel) {
        var i18n = (cfg && cfg.i18n) || {};
        var search = zertiEffectivePaymentsSearchTerm(searchInput);

        function startDownload() {
            if (defaultLabelEl && i18n.exportWorking) {
                defaultLabelEl.textContent = i18n.exportWorking;
            }
            try {
                submitPaymentsExport(cfg);
            } catch (e) {}
            window.setTimeout(function () {
                resetPaymentsExportButton(btn, defaultLabelEl, defaultLabel);
            }, 1500);
        }

        function onTotalKnown(total) {
            if (total === 0) {
                showPaymentsGridAlert(i18n.exportEmpty || '', cfg);
                resetPaymentsExportButton(btn, defaultLabelEl, defaultLabel);
                return;
            }
            startDownload();
        }

        if (search !== '') {
            startDownload();
            return;
        }

        if (gridEl && typeof gridEl.__zertiPaymentsTotal === 'number') {
            onTotalKnown(gridEl.__zertiPaymentsTotal);
            return;
        }

        fetchPaymentsTotal(cfg, onTotalKnown);
    }

    function installPaymentsExportButton(wrap, cfg, gridEl, searchInput) {
        if (!wrap) {
            return null;
        }
        var btn = wrap.querySelector('.zerti-payments-export-btn');
        if (!btn) {
            return null;
        }
        var defaultLabelEl = btn.querySelector('.zerti-payments-export-label');
        var defaultLabel = defaultLabelEl ? defaultLabelEl.textContent : '';

        var onClick = function (event) {
            event.preventDefault();
            if (btn.disabled) {
                return;
            }
            btn.disabled = true;
            btn.setAttribute('aria-busy', 'true');
            runPaymentsExport(cfg, gridEl, searchInput, btn, defaultLabelEl, defaultLabel);
        };

        btn.addEventListener('click', onClick);
        return function () {
            btn.removeEventListener('click', onClick);
        };
    }

    function paymentsSortFromApi(api, fallbackCol, fallbackDir) {
        var orderCol = fallbackCol;
        var orderDir = fallbackDir === 'asc' ? 'asc' : 'desc';
        if (api && api.getColumnState) {
            var sorted = (api.getColumnState() || []).filter(function (col) {
                return col && col.sort;
            })[0];
            if (sorted && sorted.colId) {
                var match = /^c(\d+)$/.exec(String(sorted.colId));
                if (match) {
                    orderCol = parseInt(match[1], 10);
                    orderDir = sorted.sort === 'asc' ? 'asc' : 'desc';
                }
            }
        }
        return { orderCol: orderCol, orderDir: orderDir };
    }

    function paymentsGridInnerWidth(gridEl) {
        if (!gridEl) {
            return 0;
        }
        var wrap = gridEl.closest('.zerti-payments-wrap');
        return Math.max(
            wrap && wrap.clientWidth ? wrap.clientWidth : 0,
            gridEl.clientWidth || 0,
            gridEl.offsetWidth || 0
        );
    }

    function stabilizePaymentsLayout(api, gridEl) {
        if (!api || !gridEl) {
            return;
        }
        if (api.setGridOption) {
            api.setGridOption('getRowHeight', undefined);
            api.setGridOption('suppressHorizontalScroll', isPaymentsGridCompact(paymentsGridInnerWidth(gridEl)));
        }
        if (api.resetRowHeights) {
            api.resetRowHeights();
        }
        if (api.sizeColumnsToFit) {
            window.requestAnimationFrame(function () {
                try {
                    api.sizeColumnsToFit();
                } catch (errFit) {}
            });
        }
    }

    function buildColumnDefs(orderCol, orderDir, filterOptionCache, viewport, api) {
        var i18n = gridI18n();
        var isCompact = viewport && viewport.isCompact;
        var sortPrefs = paymentsSortFromApi(api, orderCol, orderDir);
        orderCol = sortPrefs.orderCol;
        orderDir = sortPrefs.orderDir;
        var defs = [
            {
                colId: 'c0',
                headerName: i18n.colOrderId || '',
                field: 'id',
                comparator: numericComparator('idRaw'),
                cellClass: 'text-center',
                minWidth: 100,
                filter: false,
            },
            {
                colId: 'c1',
                headerName: isCompact ? i18n.colDateShort || '' : i18n.colDate || '',
                field: 'paidDate',
                comparator: numericComparator('paidDateSort'),
                cellClass: 'text-center',
                minWidth: isCompact ? 88 : 150,
                flex: isCompact ? 1 : undefined,
                filter: false,
            },
            {
                colId: 'c2',
                headerName: i18n.colCustomer || '',
                field: 'customer',
                comparator: textComparator,
                minWidth: 140,
                filter: false,
            },
            {
                colId: 'c3',
                headerName: i18n.colAmount || '',
                field: 'totalHtml',
                cellRenderer: htmlRenderer,
                comparator: numericComparator('totalSort'),
                minWidth: isCompact ? 96 : 120,
                flex: isCompact ? 1 : undefined,
                filter: false,
            },
            {
                colId: 'c4',
                headerName: i18n.colGateway || '',
                field: 'gateway',
                comparator: textComparator,
                minWidth: 130,
                ...dropdownFilter(filterOptionCache, 'gateway'),
            },
            {
                colId: 'c5',
                headerName: i18n.colTransactionId || '',
                field: 'transactionId',
                comparator: textComparator,
                cellClass: 'zerti-ltr-nums',
                minWidth: 140,
                filter: false,
            },
            {
                colId: 'c6',
                headerName: i18n.colStatus || '',
                field: 'statusHtml',
                filterValueGetter: function (params) {
                    return params.data ? params.data.statusText : '';
                },
                cellRenderer: htmlRenderer,
                comparator: function (a, b, nodeA, nodeB) {
                    return textComparator(
                        nodeA && nodeA.data ? nodeA.data.statusSort : '',
                        nodeB && nodeB.data ? nodeB.data.statusSort : ''
                    );
                },
                minWidth: isCompact ? 72 : 120,
                flex: isCompact ? 0.9 : undefined,
                ...dropdownFilter(filterOptionCache, 'statusText'),
            },
            {
                colId: 'searchText',
                field: 'searchText',
                filter: false,
                hide: true,
                suppressColumnsToolPanel: true,
            },
        ];
        var sortableIndex = !isNaN(orderCol) && orderCol >= 0 && orderCol <= 5 ? orderCol : 1;
        defs[sortableIndex].sort = orderDir === 'asc' ? 'asc' : 'desc';
        return defs;
    }

    function createPaymentsLoadingState(gridEl) {
        var activeRequests = 0;
        var el = document.createElement('div');
        el.className = 'zerti-payments-grid-loading';
        el.setAttribute('role', 'status');
        el.setAttribute('aria-live', 'polite');
        el.hidden = true;
        el.textContent = gridI18n().loadingData || '';
        gridEl.appendChild(el);

        return {
            show: function () {
                activeRequests += 1;
                el.hidden = false;
            },
            hide: function () {
                activeRequests = Math.max(0, activeRequests - 1);
                if (activeRequests === 0) {
                    el.hidden = true;
                }
            },
            destroy: function () {
                activeRequests = 0;
                if (el.parentNode) {
                    el.parentNode.removeChild(el);
                }
            },
        };
    }

    function refreshPaymentsInfiniteCache(api, resetPage, dataSourceFactory) {
        if (resetPage && api && api.paginationGoToFirstPage) {
            api.paginationGoToFirstPage();
        }
        if (dataSourceFactory && api) {
            if (api.setGridOption) {
                api.setGridOption('datasource', dataSourceFactory());
                return;
            }
            if (api.setDatasource) {
                api.setDatasource(dataSourceFactory());
                return;
            }
        }
        if (api && api.purgeInfiniteCache) {
            api.purgeInfiniteCache();
        } else if (api && api.refreshInfiniteCache) {
            api.refreshInfiniteCache();
        }
    }

    function zertiGridFetchRows(cfg, query, ajaxBody) {
        if (cfg.restUrl) {
            var restQuery = new URLSearchParams(query);
            var restUrl = cfg.restUrl + (restQuery.toString() ? '?' + restQuery.toString() : '');
            return window
                .fetch(restUrl, {
                    method: 'GET',
                    credentials: 'same-origin',
                    headers: {
                        'X-WP-Nonce': cfg.restNonce || '',
                    },
                })
                .then(function (response) {
                    return response.json();
                })
                .then(function (payload) {
                    if (!payload || !Array.isArray(payload.rows)) {
                        throw new Error('invalid_grid_response');
                    }
                    return {
                        rows: payload.rows,
                        total: payload.total,
                    };
                });
        }

        var body = new URLSearchParams(ajaxBody);
        return window
            .fetch(cfg.ajaxUrl || window.ajaxurl || '', {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                },
                body: body.toString(),
            })
            .then(function (response) {
                return response.json();
            })
            .then(function (payload) {
                if (!payload || !payload.success || !payload.data) {
                    throw new Error('invalid_grid_response');
                }
                return {
                    rows: Array.isArray(payload.data.rows) ? payload.data.rows : [],
                    total: payload.data.total,
                };
            });
    }

    function createPaymentsDataSource(cfg, searchInput, filterOptionCache, loadingState, api, gridEl) {
        return {
            getRows: function (params) {
                var pageSize = Number(cfg.pageSize || 50);
                var filterModel =
                    typeof window.zertiAgGridEffectiveFilterModel === 'function'
                        ? window.zertiAgGridEffectiveFilterModel(api, gridEl)
                        : api && api.getFilterModel
                          ? api.getFilterModel()
                          : params.filterModel || {};
                var sortModel = params.sortModel || [];
                if (loadingState && loadingState.show) {
                    loadingState.show();
                }
                var gridQuery = {
                    start: String(params.startRow || 0),
                    limit: String(pageSize),
                    search: zertiEffectivePaymentsSearchTerm(searchInput),
                    sort_model: JSON.stringify(sortModel),
                    filter_model: JSON.stringify(filterModel),
                    payments_scope: readPaymentsScope(cfg),
                };
                var ajaxBody = Object.assign({}, gridQuery, {
                    action: cfg.action || 'zerti_payments_grid',
                    nonce: cfg.nonce || '',
                });

                zertiGridFetchRows(cfg, gridQuery, ajaxBody)
                    .then(function (data) {
                        var rows = data.rows;
                        var startRow = Number(params.startRow || 0);
                        var totalRaw = Number(data.total);
                        var serverTotalKnown = Number.isFinite(totalRaw) && totalRaw >= 0;
                        var isLastBlock = rows.length < pageSize;
                        var rowCount;
                        if (Number.isFinite(totalRaw) && totalRaw >= 0) {
                            if (gridEl) {
                                gridEl.__zertiPaymentsTotal = totalRaw;
                            }
                            rowCount = totalRaw;
                        } else if (gridEl && gridEl.__zertiPaymentsTotal > 0) {
                            rowCount = gridEl.__zertiPaymentsTotal;
                        } else if (isLastBlock) {
                            rowCount = startRow + rows.length;
                        } else {
                            rowCount = -1;
                        }
                        appendPaymentsFilterOptions(filterOptionCache, rows);
                        if (typeof window.zertiAgGridRefreshInlineFilterHeaders === 'function') {
                            window.zertiAgGridRefreshInlineFilterHeaders(api, filterOptionCache);
                        }
                        if (params.success) {
                            params.success({
                                rowData: rows,
                                rowCount: rowCount >= 0 ? rowCount : undefined,
                            });
                        } else {
                            params.successCallback(rows, rowCount);
                        }
                        if (loadingState && loadingState.hide) {
                            loadingState.hide();
                        }
                        window.requestAnimationFrame(function () {
                            stabilizePaymentsLayout(api, gridEl);
                        });
                    })
                    .catch(function () {
                        if (params.fail) {
                            params.fail();
                        } else if (params.failCallback) {
                            params.failCallback();
                        }
                        if (loadingState && loadingState.hide) {
                            loadingState.hide();
                        }
                    });
            },
        };
    }

    function isPaymentsGridCompact(width) {
        return width < 992;
    }

    function handlePaymentsRowClicked(event) {
        if (!event || !event.data) {
            return;
        }
        var domEvent = event.event;
        var target = domEvent && domEvent.target ? domEvent.target : null;
        if (target) {
            if (
                target.closest(
                    'a, button, select, input, textarea, label, .ag-header, .ag-filter, .ag-paging-panel, .zerti-payments-grid-toolbar'
                )
            ) {
                return;
            }
        }
        var orderId = Number(event.data.idRaw);
        if (!(orderId > 0)) {
            return;
        }
        if (typeof window.zertiOpenShopOrderDetail === 'function') {
            window.zertiOpenShopOrderDetail(orderId, 'detail');
        } else if (typeof window.zertiAdminRouteUrl === 'function') {
            var url = window.zertiAdminRouteUrl({ tab: 'shop', order: orderId });
            if (url) {
                window.location.href = url;
            }
        }
    }

    function applyPaymentsResponsiveColumns(api, gridEl) {
        if (!api || !gridEl) {
            return;
        }
        var width = paymentsGridInnerWidth(gridEl);
        var isCompact = isPaymentsGridCompact(width);
        var viewport = { isCompact: isCompact };
        var filterOptionCache = gridEl.__zertiFilterOptionCache || createFilterOptionCache();
        var urlP = readUrlParams(readGridCfg());
        var nextMode = isCompact ? 'compact' : 'desktop';

        if (gridEl.__zertiPaymentsViewportMode !== nextMode) {
            gridEl.__zertiPaymentsViewportMode = nextMode;
            var columnDefs = buildColumnDefs(urlP.orderCol, urlP.orderDir, filterOptionCache, viewport, api);
            if (api.setGridOption) {
                api.setGridOption('columnDefs', columnDefs);
            } else if (api.setColumnDefs) {
                api.setColumnDefs(columnDefs);
            }
        }

        var visibility = {
            c0: !isCompact,
            c1: true,
            c2: !isCompact,
            c3: true,
            c4: !isCompact,
            c5: !isCompact,
            c6: true,
            searchText: false,
        };
        var state = Object.keys(visibility).map(function (colId) {
            return {
                colId: colId,
                hide: !visibility[colId],
            };
        });

        if (api.applyColumnState) {
            api.applyColumnState({ state: state, applyOrder: false });
        } else if (api.setColumnsVisible) {
            Object.keys(visibility).forEach(function (colId) {
                api.setColumnsVisible([colId], visibility[colId]);
            });
        }
        gridEl.classList.toggle('zerti-payments-grid--compact', isCompact);
        stabilizePaymentsLayout(api, gridEl);
    }

    function installPaymentsScopeFilterBar(wrap, cfg, gridEl, api, dataSourceFactory) {
        if (!wrap) {
            return null;
        }
        var host = wrap.querySelector('.zerti-payments-grid-toolbar');
        if (!host) {
            return null;
        }
        var existing = host.querySelector('.zerti-payments-scope-filter-bar');
        if (existing) {
            existing.remove();
        }
        var paymentsScope = readPaymentsScope(cfg);
        if (!paymentsScope || !isValidPaymentsScope(cfg, paymentsScope)) {
            return null;
        }
        var i18n = (cfg && cfg.i18n) || {};
        var bar = document.createElement('div');
        bar.className =
            'zerti-payments-scope-filter-bar alert alert-secondary py-2 px-3 mb-0 small d-flex flex-wrap align-items-center justify-content-center gap-2';
        bar.setAttribute('role', 'status');
        var label = document.createElement('span');
        label.className = 'zerti-grid-list-filter-label';
        label.textContent = paymentsScopeFilterLabel(cfg, paymentsScope);
        var clearBtn = document.createElement('button');
        clearBtn.type = 'button';
        clearBtn.className =
            'btn btn-outline-secondary d-inline-flex align-items-center zerti-grid-list-filter-clear-btn';
        clearBtn.textContent = i18n.scopeFilterClear || '';
        clearBtn.addEventListener('click', function () {
            try {
                var u = new URL(window.location.href);
                u.searchParams.delete(cfg.paramPaymentsScope || 'zerti_payments_scope');
                var next = u.pathname + u.search + window.location.hash;
                window.history.replaceState(null, '', next);
            } catch (eClear) {}
            bar.remove();
            gridEl.__zertiPaymentsTotal = undefined;
            refreshPaymentsInfiniteCache(api, true, dataSourceFactory);
        });
        bar.appendChild(clearBtn);
        bar.appendChild(label);
        host.insertBefore(bar, host.firstChild);
        return function () {
            if (bar.parentNode) {
                bar.parentNode.removeChild(bar);
            }
        };
    }

    function zertiInitPaymentsTable(root) {
        if (!root || !window.agGrid || typeof window.agGrid.createGrid !== 'function') {
            return;
        }
        var gridEl = root.querySelector('#zertiPaymentsGrid');
        if (!gridEl) {
            return;
        }
        if (typeof gridEl.__zertiAgGridCleanup === 'function') {
            gridEl.__zertiAgGridCleanup();
            gridEl.__zertiAgGridCleanup = null;
        }
        if (gridEl.__zertiAgGridApi && typeof gridEl.__zertiAgGridApi.destroy === 'function') {
            gridEl.__zertiAgGridApi.destroy();
            gridEl.__zertiAgGridApi = null;
        }

        var wrap = gridEl.closest('.zerti-payments-wrap');
        var cfg = readGridCfg();
        var urlP = readUrlParams(cfg);
        var initialSearch = zertiPersianToLatinDigits(urlP.search).trim();
        var searchInput = installSearchToolbar(wrap, cfg, initialSearch);
        var exportCleanup = installPaymentsExportButton(wrap, cfg, gridEl, searchInput);
        var scopeFilterCleanup = null;
        var pageSize = Number(cfg.pageSize || 50);
        var filterOptionCache = createFilterOptionCache();
        gridEl.__zertiFilterOptionCache = filterOptionCache;
        seedStatusFilterOptions(filterOptionCache, cfg);
        seedGatewayFilterOptions(filterOptionCache, cfg);
        if (typeof filterOptionCache.notifyFilterOptionsChanged === 'function') {
            filterOptionCache.notifyFilterOptionsChanged();
        }
        var gridWidth = paymentsGridInnerWidth(gridEl);
        var initialViewport = {
            isCompact: isPaymentsGridCompact(gridWidth),
        };
        gridEl.__zertiPaymentsViewportMode = initialViewport.isCompact ? 'compact' : 'desktop';

        var gridOptions = {
            theme: 'legacy',
            rowModelType: 'infinite',
            components: typeof window.zertiAgGridComponents === 'function' ? window.zertiAgGridComponents() : {},
            columnDefs: buildColumnDefs(urlP.orderCol, urlP.orderDir, filterOptionCache, initialViewport, null),
            defaultColDef: {
                flex: 1,
                sortable: true,
                resizable: true,
                filter: false,
                floatingFilter: false,
                cellClass: 'zerti-payments-grid-cell',
            },
            enableRtl: window.zertiIsAdminRtl ? window.zertiIsAdminRtl() : true,
            animateRows: true,
            pagination: true,
            paginationPageSize: pageSize,
            paginationPageSizeSelector: false,
            paginationPanels: ['pageSummary', 'rowSummary'],
            cacheBlockSize: pageSize,
            maxBlocksInCache: 4,
            paginationNumberFormatter: function (params) {
                return zertiLatinToPersianDigits(params.value);
            },
            localeText: window.zertiAgGridLocaleText(gridI18n(), 'noRowsToShow'),
            getRowId: function (params) {
                return String(params.data.idRaw);
            },
            suppressRowClickSelection: true,
            onRowClicked: handlePaymentsRowClicked,
            onFilterChanged: function (event) {
                if (typeof window.zertiAgGridSyncInlineFilterHeaders === 'function') {
                    window.zertiAgGridSyncInlineFilterHeaders(event.api, gridEl.__zertiFilterOptionCache);
                }
                if (gridEl) {
                    gridEl.__zertiPaymentsTotal = 0;
                }
                refreshPaymentsInfiniteCache(event.api, true, gridEl.__zertiAgGridDataSourceFactory);
            },
            onSortChanged: function (event) {
                replacePaymentsGridUrlParams(event.api, cfg, searchInput);
                if (gridEl) {
                    gridEl.__zertiPaymentsTotal = 0;
                }
                refreshPaymentsInfiniteCache(event.api, true, gridEl.__zertiAgGridDataSourceFactory);
                window.requestAnimationFrame(function () {
                    stabilizePaymentsLayout(event.api, gridEl);
                });
            },
        };

        gridEl.__zertiPaymentsTotal = 0;
        var api = window.agGrid.createGrid(gridEl, gridOptions);
        var loadingState = createPaymentsLoadingState(gridEl);
        var dataSourceFactory = function () {
            return createPaymentsDataSource(cfg, searchInput, filterOptionCache, loadingState, api, gridEl);
        };
        gridEl.__zertiAgGridDataSourceFactory = dataSourceFactory;
        gridEl.__zertiAgGridApi = api;
        gridEl.classList.add('zerti-payments-grid--row-nav');
        if (typeof window.zertiConsumePendingListGridRestore === 'function') {
            window.zertiConsumePendingListGridRestore('financial', api);
        }
        var dataSource = dataSourceFactory();
        if (api.setGridOption) {
            api.setGridOption('datasource', dataSource);
        } else if (api.setDatasource) {
            api.setDatasource(dataSource);
        }
        scopeFilterCleanup = installPaymentsScopeFilterBar(wrap, cfg, gridEl, api, dataSourceFactory);
        applyPaymentsResponsiveColumns(api, gridEl);

        var resizeTimer = null;
        var onResize = function () {
            if (resizeTimer) {
                window.clearTimeout(resizeTimer);
            }
            resizeTimer = window.setTimeout(function () {
                resizeTimer = null;
                applyPaymentsResponsiveColumns(api, gridEl);
            }, 120);
        };
        window.addEventListener('resize', onResize);
        gridEl.__zertiAgGridCleanup = function () {
            if (resizeTimer) {
                window.clearTimeout(resizeTimer);
                resizeTimer = null;
            }
            if (typeof exportCleanup === 'function') {
                exportCleanup();
            }
            if (typeof scopeFilterCleanup === 'function') {
                scopeFilterCleanup();
            }
            window.removeEventListener('resize', onResize);
            gridEl.__zertiAgGridDataSourceFactory = null;
            gridEl.__zertiFilterOptionCache = null;
            gridEl.__zertiPaymentsViewportMode = null;
            gridEl.__zertiPaymentsTotal = undefined;
            loadingState.destroy();
        };

        if (searchInput) {
            var lastEffectiveSearch = zertiEffectivePaymentsSearchTerm(searchInput);
            searchInput.oninput = function () {
                var displayValue = zertiLatinToPersianDigits(this.value);
                if (this.value !== displayValue) {
                    this.value = displayValue;
                }
                var nextEffectiveSearch = zertiEffectivePaymentsSearchTerm(searchInput);
                if (nextEffectiveSearch !== lastEffectiveSearch) {
                    lastEffectiveSearch = nextEffectiveSearch;
                    refreshPaymentsInfiniteCache(api, true, dataSourceFactory);
                }
                replacePaymentsGridUrlParams(api, cfg, searchInput);
            };
        }
    }

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