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

    var shopUrlSyncTimer = null;

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

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

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

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

    function readUrlParams(cfg) {
        var out = { search: '', orderCol: NaN, orderDir: 'desc', statusSlug: '' };
        try {
            var sp = new URLSearchParams(window.location.search);
            var ps = cfg.paramSearch || 'zerti_shop_search';
            var pc = cfg.paramOrderCol || 'zerti_shop_order_col';
            var pd = cfg.paramOrderDir || 'zerti_shop_order_dir';
            var pStatus = cfg.paramShopStatus || 'zerti_shop_status';
            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';
            var statusRaw = sp.get(pStatus);
            if (statusRaw) {
                out.statusSlug = String(statusRaw);
            }
        } catch (e1) {
            return out;
        }
        return out;
    }

    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 replaceShopStatusUrlParam(cfg, statusSlug) {
        try {
            var u = new URL(window.location.href);
            var pStatus = cfg.paramShopStatus || 'zerti_shop_status';
            if (statusSlug) {
                u.searchParams.set(pStatus, statusSlug);
            } else {
                u.searchParams.delete(pStatus);
            }
            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 (eStatus) {}
    }

    function applyShopOrdersStatusFilter(api, cfg, statusSlug, filterOptionCache) {
        if (!api || !api.setFilterModel || !statusSlug) {
            return;
        }
        var label = shopStatusLabelFromSlug(cfg, statusSlug);
        if (!label) {
            return;
        }
        api.setFilterModel({
            c5: { value: label },
        });
        var gridEl = typeof api.getGridElement === 'function' ? api.getGridElement() : null;
        if (gridEl) {
            gridEl.__zertiAgGridFilterModel = { c5: { value: label } };
        }
        if (typeof api.onFilterChanged === 'function') {
            api.onFilterChanged();
        }
        if (typeof window.zertiAgGridSyncInlineFilterHeaders === 'function') {
            window.zertiAgGridSyncInlineFilterHeaders(api, filterOptionCache);
        }
    }

    function replaceShopGridUrlParams(api, cfg, searchInput) {
        if (shopUrlSyncTimer) {
            window.clearTimeout(shopUrlSyncTimer);
        }
        shopUrlSyncTimer = window.setTimeout(function () {
            shopUrlSyncTimer = null;
            try {
                var u = new URL(window.location.href);
                var ps = cfg.paramSearch || 'zerti_shop_search';
                var pc = cfg.paramOrderCol || 'zerti_shop_order_col';
                var pd = cfg.paramOrderDir || 'zerti_shop_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 zertiEffectiveCustomerSearchTerm(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 scrollShopOrdersPageToTop() {
        if (typeof window.scrollTo === 'function') {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    }

    function uniqueOptions(rows, field, numericSort) {
        var seen = {};
        var out = [];
        rows.forEach(function (row) {
            var raw = row && row[field] !== undefined && row[field] !== null ? String(row[field]) : '';
            if (raw === '' || seen[raw]) {
                return;
            }
            seen[raw] = true;
            out.push(raw);
        });
        out.sort(
            numericSort
                ? function (a, b) {
                      return Number(zertiPersianToLatinDigits(a).replace(/[^\d.-]/g, '')) - Number(zertiPersianToLatinDigits(b).replace(/[^\d.-]/g, ''));
                  }
                : textComparator
        );
        return out;
    }

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

    function seedStatusFilterOptions(filterOptionCache, cfg) {
        if (!filterOptionCache || !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) {
        if (!filterOptionCache) {
            return;
        }
        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 appendFilterOptions(cache, rows) {
        var fields = {
            dateFilter: false,
            gateway: false,
            statusText: false,
        };
        Object.keys(fields).forEach(function (field) {
            var existing = {};
            cache[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 === '' || existing[value]) {
                    return;
                }
                existing[value] = true;
                cache[field].push(value);
            });
            cache[field].sort(
                fields[field]
                    ? function (a, b) {
                          return Number(zertiPersianToLatinDigits(a).replace(/[^\d.-]/g, '')) - Number(zertiPersianToLatinDigits(b).replace(/[^\d.-]/g, ''));
                      }
                    : textComparator
            );
        });
        if (typeof cache.notifyFilterOptionsChanged === 'function') {
            cache.notifyFilterOptionsChanged();
        }
    }

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

    function isValidShopStatusSlug(cfg, slug) {
        return !!(slug && cfg.statusLabels && Object.prototype.hasOwnProperty.call(cfg.statusLabels, slug));
    }

    function readShopStatusFromUrl(cfg) {
        var slug = readUrlParams(cfg).statusSlug || '';
        return isValidShopStatusSlug(cfg, slug) ? slug : '';
    }

    function shopOrdersStatusFilterLabel(cfg, statusSlug) {
        var i18n = (cfg && cfg.i18n) || {};
        if (statusSlug === 'processing') {
            return i18n.statusFilterProcessing || '';
        }
        var label = shopStatusLabelFromSlug(cfg, statusSlug);
        return label ? (i18n.statusFilterOnly || '').replace('%s', label) : '';
    }

    function installShopOrdersStatusFilterBar(wrap, cfg, gridEl, api, dataSourceFactory) {
        if (!wrap) {
            return null;
        }
        var host = wrap.querySelector('.zerti-shop-grid-toolbar');
        if (!host) {
            return null;
        }
        var existing = host.querySelector('.zerti-shop-orders-status-filter-bar');
        if (existing) {
            existing.remove();
        }
        var statusSlug = readShopStatusFromUrl(cfg);
        if (!statusSlug) {
            return null;
        }
        var filterLabel = shopOrdersStatusFilterLabel(cfg, statusSlug);
        if (!filterLabel) {
            return null;
        }
        var i18n = (cfg && cfg.i18n) || {};
        var bar = document.createElement('div');
        bar.className =
            'zerti-shop-orders-status-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 = filterLabel;
        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.statusFilterClear || '';
        clearBtn.addEventListener('click', function () {
            replaceShopStatusUrlParam(cfg, '');
            if (api && api.setFilterModel) {
                api.setFilterModel(null);
            }
            if (gridEl) {
                gridEl.__zertiShopOrdersTotal = 0;
            }
            bar.remove();
            refreshShopOrdersInfiniteCache(api, true, dataSourceFactory, gridEl);
        });
        bar.appendChild(clearBtn);
        bar.appendChild(label);
        host.insertBefore(bar, host.firstChild);
        return function () {
            if (bar.parentNode) {
                bar.parentNode.removeChild(bar);
            }
        };
    }

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

    function shopOrdersSortFromApi(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 shopOrdersGridInnerWidth(gridEl) {
        if (!gridEl) {
            return 0;
        }
        var wrap = gridEl.closest('.zerti-shop-orders-wrap');
        return Math.max(
            wrap && wrap.clientWidth ? wrap.clientWidth : 0,
            gridEl.clientWidth || 0,
            gridEl.offsetWidth || 0
        );
    }

    function stabilizeShopOrdersLayout(api, gridEl) {
        if (!api || !gridEl) {
            return;
        }
        if (api.setGridOption) {
            api.setGridOption('getRowHeight', undefined);
            api.setGridOption('suppressHorizontalScroll', isShopOrdersGridCompact(shopOrdersGridInnerWidth(gridEl)));
        }
        if (api.resetRowHeights) {
            api.resetRowHeights();
        }
        try {
            if (api.onGridSizeChanged) {
                api.onGridSizeChanged();
            }
        } catch (errSize) {}
        window.requestAnimationFrame(function () {
            try {
                if (api.autoSizeColumns) {
                    api.autoSizeColumns({
                        columns: ['c0'],
                        skipHeader: false,
                    });
                }
            } catch (errAuto) {}
            try {
                if (api.sizeColumnsToFit) {
                    api.sizeColumnsToFit();
                }
            } catch (errFit) {}
        });
    }

    function buildColumnDefs(orderCol, orderDir, filterOptionCache, viewport, api) {
        var i18n = gridI18n();
        var isCompact = viewport && viewport.isCompact;
        var sortPrefs = shopOrdersSortFromApi(api, orderCol, orderDir);
        orderCol = sortPrefs.orderCol;
        orderDir = sortPrefs.orderDir;
        var defs = [
            {
                colId: 'c0',
                headerName: i18n.colId || '',
                field: 'id',
                filterValueGetter: function (params) {
                    return params.data ? params.data.id : '';
                },
                comparator: numericComparator('idRaw'),
                cellClass: 'text-center zerti-shop-orders-grid-id-cell',
                flex: 0,
                minWidth: 48,
                maxWidth: 110,
                suppressSizeToFit: true,
                resizable: false,
                filter: false,
            },
            {
                colId: 'c1',
                headerName: i18n.colDate || '',
                field: 'date',
                comparator: numericComparator('dateSort'),
                cellClass: 'text-center',
                minWidth: isCompact ? 88 : 160,
                flex: isCompact ? 1 : undefined,
                ...dropdownFilter(filterOptionCache, 'dateFilter'),
            },
            {
                colId: 'c2',
                headerName: i18n.colCustomer || '',
                field: 'customer',
                comparator: textComparator,
                minWidth: 150,
                flex: isCompact ? 1.5 : 2.75,
                suppressSizeToFit: false,
                filter: false,
            },
            {
                colId: 'c3',
                headerName: i18n.colTotal || '',
                field: 'totalHtml',
                filterValueGetter: function (params) {
                    return params.data ? params.data.totalText : '';
                },
                cellRenderer: htmlRenderer,
                comparator: numericComparator('totalSort'),
                cellClass: 'zerti-shop-orders-total',
                minWidth: isCompact ? 96 : 140,
                flex: isCompact ? 1 : undefined,
                filter: false,
            },
            {
                colId: 'c4',
                headerName: i18n.colGateway || '',
                field: 'gateway',
                comparator: textComparator,
                minWidth: 150,
                ...dropdownFilter(filterOptionCache, 'gateway'),
            },
            {
                colId: 'c5',
                headerName: isCompact ? i18n.colStatusShort || '' : i18n.colStatus || '',
                field: 'statusHtml',
                filterValueGetter: function (params) {
                    return params.data ? params.data.statusText : '';
                },
                cellRenderer: htmlRenderer,
                comparator: function (a, b, nodeA, nodeB) {
                    return textComparator(nodeA.data.statusSort, nodeB.data.statusSort);
                },
                minWidth: isCompact ? 72 : 130,
                flex: isCompact ? 0.9 : undefined,
                ...dropdownFilter(filterOptionCache, 'statusText'),
            },
            {
                colId: 'c6',
                headerName: i18n.colDownloadTitle || 'Print',
                field: 'downloadHtml',
                cellRenderer: htmlRenderer,
                cellClass: 'text-center zerti-shop-orders-grid-download-cell',
                flex: 0,
                minWidth: isCompact ? 96 : 118,
                maxWidth: isCompact ? 108 : 132,
                suppressSizeToFit: true,
                resizable: false,
                sortable: false,
                filter: false,
                hide: isCompact,
            },
            {
                colId: 'searchText',
                field: 'searchText',
                filter: false,
                hide: true,
                suppressColumnsToolPanel: true,
            },
        ];
        var sortableIndex = !isNaN(orderCol) && orderCol >= 0 && orderCol <= 4 ? orderCol : 1;
        defs[sortableIndex].sort = orderDir === 'asc' ? 'asc' : 'desc';
        return defs;
    }

    function createShopOrdersLoadingState(gridEl) {
        var activeRequests = 0;
        var el = document.createElement('div');
        el.className = 'zerti-shop-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 purgeShopOrdersGridCache(api, gridEl) {
        if (gridEl) {
            gridEl.__zertiShopOrdersTotal = 0;
        }
        if (api && api.purgeInfiniteCache) {
            api.purgeInfiniteCache();
        } else if (api && api.refreshInfiniteCache) {
            api.refreshInfiniteCache();
        }
    }

    function refreshShopOrdersInfiniteCache(api, resetPage, dataSourceFactory, gridEl) {
        if (resetPage && api && api.paginationGoToFirstPage) {
            api.paginationGoToFirstPage();
        }
        purgeShopOrdersGridCache(api, gridEl);
        if (dataSourceFactory && api) {
            if (api.setGridOption) {
                api.setGridOption('datasource', dataSourceFactory());
                return;
            }
            if (api.setDatasource) {
                api.setDatasource(dataSourceFactory());
            }
        }
    }

    function zertiRefreshShopOrdersGrid(resetPage) {
        var gridEl = document.getElementById('zertiShopOrdersGrid');
        if (!gridEl || !gridEl.__zertiAgGridApi) {
            return;
        }
        refreshShopOrdersInfiniteCache(
            gridEl.__zertiAgGridApi,
            resetPage !== false,
            gridEl.__zertiAgGridDataSourceFactory,
            gridEl
        );
    }

    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 createShopOrdersDataSource(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: zertiEffectiveCustomerSearchTerm(searchInput),
                    sort_model: JSON.stringify(sortModel),
                    filter_model: JSON.stringify(filterModel),
                    _: String(Date.now()),
                };
                var ajaxBody = Object.assign({}, gridQuery, {
                    action: cfg.action || 'zerti_shop_orders_grid',
                    nonce: cfg.nonce || '',
                });

                zertiGridFetchRows(cfg, gridQuery, ajaxBody)
                    .then(function (data) {
                        var rows = data.rows;
                        var totalRaw = Number(data.total);
                        var rowCount;
                        if (Number.isFinite(totalRaw) && totalRaw > 0) {
                            if (gridEl) {
                                gridEl.__zertiShopOrdersTotal = totalRaw;
                            }
                            rowCount = totalRaw;
                        } else if (gridEl && gridEl.__zertiShopOrdersTotal > 0) {
                            rowCount = gridEl.__zertiShopOrdersTotal;
                        } else {
                            var startRow = Number(params.startRow || 0);
                            rowCount =
                                rows.length < pageSize ? startRow + rows.length : -1;
                        }
                        appendFilterOptions(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 () {
                            stabilizeShopOrdersLayout(api, gridEl);
                        });
                        scrollShopOrdersPageToTop();
                    })
                    .catch(function () {
                        if (params.fail) {
                            params.fail();
                        }
                        params.failCallback();
                        if (loadingState && loadingState.hide) {
                            loadingState.hide();
                        }
                    });
            },
        };
    }

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

    function handleShopOrdersRowClicked(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-shop-grid-toolbar, .zerti-shop-orders-export-sql-btn, .zerti-shop-orders-export-sql-unpaid-btn'
                )
            ) {
                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 applyShopOrdersResponsiveColumns(api, gridEl) {
        if (!api || !gridEl) {
            return;
        }
        var width = shopOrdersGridInnerWidth(gridEl);
        var isCompact = isShopOrdersGridCompact(width);
        var viewport = { isCompact: isCompact };
        var filterOptionCache = gridEl.__zertiFilterOptionCache || createFilterOptionCache();
        var urlP = readUrlParams(readGridCfg());
        var nextMode = isCompact ? 'compact' : 'desktop';

        if (gridEl.__zertiShopOrdersViewportMode !== nextMode) {
            gridEl.__zertiShopOrdersViewportMode = 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: true,
            c6: !isCompact,
            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-shop-orders-grid--compact', isCompact);
        gridEl.classList.remove('zerti-shop-orders-grid--phone');
        stabilizeShopOrdersLayout(api, gridEl);
    }

    function submitShopOrdersExport(cfg, api, searchInput, gridEl, exportOpts) {
        var ajaxUrl = cfg.ajaxUrl || window.ajaxurl || '';
        if (!ajaxUrl) {
            return;
        }
        exportOpts = exportOpts && typeof exportOpts === 'object' ? exportOpts : {};
        var form = document.createElement('form');
        form.method = 'POST';
        form.action = ajaxUrl;
        form.target = '_self';
        form.style.display = 'none';

        var filterModel =
            typeof window.zertiAgGridEffectiveFilterModel === 'function'
                ? window.zertiAgGridEffectiveFilterModel(api, gridEl)
                : api && api.getFilterModel
                  ? api.getFilterModel()
                  : {};
        var sortModel = [];
        if (api && api.getColumnState) {
            (api.getColumnState() || []).forEach(function (col) {
                if (col && col.sort) {
                    sortModel.push({ colId: col.colId, sort: col.sort });
                }
            });
        }

        var gridTotal = 0;
        if (gridEl && gridEl.__zertiShopOrdersTotal > 0) {
            gridTotal = Math.floor(Number(gridEl.__zertiShopOrdersTotal));
        }

        var fields = {
            action: exportOpts.action || '',
            nonce: exportOpts.nonce || '',
            search: zertiEffectiveCustomerSearchTerm(searchInput),
            sort_model: JSON.stringify(sortModel),
            filter_model: JSON.stringify(filterModel || {}),
            grid_total: String(gridTotal > 0 ? gridTotal : ''),
        };

        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 getZertiAdminRoot() {
        return document.getElementById('zertiAdmin');
    }

    function getShopOrdersAlertOverlay() {
        var root = getZertiAdminRoot();
        if (!root) {
            return null;
        }
        var ov = root.querySelector('.zerti-shop-orders-grid-alert-overlay');
        if (!ov) {
            ov = document.createElement('div');
            ov.className = 'zerti-products-grid-alert-overlay zerti-shop-orders-grid-alert-overlay';
            ov.setAttribute('role', 'dialog');
            ov.setAttribute('aria-modal', 'true');
            ov.setAttribute('aria-labelledby', 'zertiShopOrdersGridAlertMessage');
            ov.hidden = true;
            ov.innerHTML =
                '<div class="zerti-products-grid-alert-dialog alert alert-danger">' +
                '<p id="zertiShopOrdersGridAlertMessage" 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 showShopOrdersGridAlert(message, cfg) {
        if (!message) {
            return;
        }
        var ov = getShopOrdersAlertOverlay();
        if (!ov) {
            window.alert(message);
            return;
        }
        var i18n = (cfg && cfg.i18n) || {};
        var msgEl = ov.querySelector('#zertiShopOrdersGridAlertMessage');
        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 fetchShopOrdersExportCount(cfg, api, searchInput, gridEl, exportOpts, callback) {
        var ajaxUrl = cfg.ajaxUrl || window.ajaxurl || '';
        if (!ajaxUrl || typeof callback !== 'function') {
            callback({ total: -1 });
            return;
        }

        var search = zertiEffectiveCustomerSearchTerm(searchInput);
        if (search !== '') {
            callback({ needs_scan: true });
            return;
        }

        var filterModel =
            typeof window.zertiAgGridEffectiveFilterModel === 'function'
                ? window.zertiAgGridEffectiveFilterModel(api, gridEl)
                : api && api.getFilterModel
                  ? api.getFilterModel()
                  : {};
        var sortModel = [];
        if (api && api.getColumnState) {
            (api.getColumnState() || []).forEach(function (col) {
                if (col && col.sort) {
                    sortModel.push({ colId: col.colId, sort: col.sort });
                }
            });
        }

        var body = new URLSearchParams({
            action: exportOpts.action || '',
            nonce: exportOpts.nonce || '',
            export_check: '1',
            search: search,
            sort_model: JSON.stringify(sortModel),
            filter_model: JSON.stringify(filterModel || {}),
        });

        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) {
                    var total = Number(json.data.total);
                    callback({
                        total: Number.isFinite(total) && total >= 0 ? total : -1,
                    });
                    return;
                }
                if (json && json.data && json.data.code === 'needs_scan') {
                    callback({ needs_scan: true });
                    return;
                }
                callback({ total: -1 });
            })
            .catch(function () {
                callback({ total: -1 });
            });
    }

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

    function runShopOrdersExport(cfg, api, searchInput, gridEl, exportOpts, btn, defaultLabelEl, defaultLabel, workingText) {
        var i18n = (cfg && cfg.i18n) || {};

        function startDownload() {
            if (defaultLabelEl && workingText) {
                defaultLabelEl.textContent = workingText;
            }
            try {
                submitShopOrdersExport(cfg, api, searchInput, gridEl, exportOpts);
            } catch (e) {}
            window.setTimeout(function () {
                resetShopOrdersExportButton(btn, defaultLabelEl, defaultLabel);
            }, 1500);
        }

        function onCountResult(result) {
            result = result && typeof result === 'object' ? result : {};
            if (result.needs_scan) {
                showShopOrdersGridAlert(i18n.exportSqlSearchBlocked || '', cfg);
                resetShopOrdersExportButton(btn, defaultLabelEl, defaultLabel);
                return;
            }
            if (result.total === 0) {
                var emptyMsg =
                    exportOpts.scope === 'unpaid'
                        ? i18n.exportSqlEmptyUnpaid || ''
                        : i18n.exportSqlEmptyPaid || '';
                showShopOrdersGridAlert(emptyMsg, cfg);
                resetShopOrdersExportButton(btn, defaultLabelEl, defaultLabel);
                return;
            }
            startDownload();
        }

        fetchShopOrdersExportCount(cfg, api, searchInput, gridEl, exportOpts, onCountResult);
    }

    function installShopOrdersExportButton(wrap, cfg, api, searchInput, gridEl, btnSelector, exportOpts, labelSelector, workingText) {
        if (!wrap) {
            return null;
        }
        var btn = wrap.querySelector(btnSelector);
        if (!btn) {
            return null;
        }
        var defaultLabelEl = labelSelector ? btn.querySelector(labelSelector) : null;
        var defaultLabel = defaultLabelEl ? defaultLabelEl.textContent : '';

        var onClick = function (event) {
            event.preventDefault();
            if (btn.disabled) {
                return;
            }
            btn.disabled = true;
            btn.setAttribute('aria-busy', 'true');
            runShopOrdersExport(
                cfg,
                api,
                searchInput,
                gridEl,
                exportOpts,
                btn,
                defaultLabelEl,
                defaultLabel,
                workingText
            );
        };
        btn.addEventListener('click', onClick);
        return function () {
            btn.removeEventListener('click', onClick);
        };
    }

    function installShopOrdersExportButtons(wrap, cfg, api, searchInput, gridEl) {
        var i18n = (cfg && cfg.i18n) || {};
        var cleanups = [];
        cleanups.push(
            installShopOrdersExportButton(
                wrap,
                cfg,
                api,
                searchInput,
                gridEl,
                '.zerti-shop-orders-export-sql-btn',
                {
                    action: cfg.exportSqlAction || 'zerti_shop_orders_export_sql',
                    nonce: cfg.exportSqlNonce || '',
                    scope: 'paid',
                },
                '.zerti-shop-orders-export-sql-label',
                i18n.exportSqlWorking
            )
        );
        cleanups.push(
            installShopOrdersExportButton(
                wrap,
                cfg,
                api,
                searchInput,
                gridEl,
                '.zerti-shop-orders-export-sql-unpaid-btn',
                {
                    action: cfg.exportSqlUnpaidAction || 'zerti_shop_orders_export_sql_unpaid',
                    nonce: cfg.exportSqlUnpaidNonce || '',
                    scope: 'unpaid',
                },
                '.zerti-shop-orders-export-sql-unpaid-label',
                i18n.exportSqlUnpaidWorking
            )
        );
        return function () {
            cleanups.forEach(function (fn) {
                if (typeof fn === 'function') {
                    fn();
                }
            });
        };
    }

    function zertiInitShopOrdersTable(root) {
        if (!root || !window.agGrid || typeof window.agGrid.createGrid !== 'function') {
            return;
        }
        var gridEl = root.querySelector('#zertiShopOrdersGrid');
        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-shop-orders-wrap');
        var cfg = readGridCfg();
        var urlP = readUrlParams(cfg);
        var initialSearch = zertiPersianToLatinDigits(urlP.search).trim();
        var searchInput = installSearchToolbar(wrap, cfg, initialSearch);
        var statusFilterCleanup = null;
        var pageSize = Number(cfg.pageSize || 50);
        var filterOptionCache = createFilterOptionCache();
        seedStatusFilterOptions(filterOptionCache, cfg);
        seedGatewayFilterOptions(filterOptionCache, cfg);
        if (typeof filterOptionCache.notifyFilterOptionsChanged === 'function') {
            filterOptionCache.notifyFilterOptionsChanged();
        }
        gridEl.__zertiFilterOptionCache = filterOptionCache;
        var gridWidth = shopOrdersGridInnerWidth(gridEl);
        var initialViewport = {
            isCompact: isShopOrdersGridCompact(gridWidth),
        };
        gridEl.__zertiShopOrdersViewportMode = 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-shop-grid-cell',
            },
            enableRtl: window.zertiIsAdminRtl ? window.zertiIsAdminRtl() : true,
            animateRows: true,
            pagination: true,
            paginationPageSize: pageSize,
            paginationPageSizeSelector: false,
            paginationPanels: ['pageSummary', 'rowSummary'],
            cacheBlockSize: pageSize,
            maxBlocksInCache: 0,
            paginationNumberFormatter: function (params) {
                return zertiLatinToPersianDigits(params.value);
            },
            localeText: window.zertiAgGridLocaleText(gridI18n(), 'noRowsToShow'),
            getRowId: function (params) {
                return String(params.data.idRaw);
            },
            suppressRowClickSelection: true,
            onRowClicked: handleShopOrdersRowClicked,
            onFilterChanged: function (event) {
                if (typeof window.zertiAgGridSyncInlineFilterHeaders === 'function') {
                    window.zertiAgGridSyncInlineFilterHeaders(event.api, gridEl.__zertiFilterOptionCache);
                }
                var filterModel =
                    typeof window.zertiAgGridEffectiveFilterModel === 'function'
                        ? window.zertiAgGridEffectiveFilterModel(event.api, gridEl)
                        : event.api.getFilterModel
                          ? event.api.getFilterModel()
                          : {};
                var statusLabel =
                    filterModel.c5 && filterModel.c5.value !== undefined && filterModel.c5.value !== null
                        ? String(filterModel.c5.value)
                        : '';
                replaceShopStatusUrlParam(cfg, shopStatusSlugFromLabel(cfg, statusLabel));
                gridEl.__zertiShopOrdersLastPage = -1;
                refreshShopOrdersInfiniteCache(event.api, true, gridEl.__zertiAgGridDataSourceFactory, gridEl);
            },
            onSortChanged: function (event) {
                replaceShopGridUrlParams(event.api, cfg, searchInput);
                gridEl.__zertiShopOrdersLastPage = -1;
                purgeShopOrdersGridCache(event.api, gridEl);
                window.requestAnimationFrame(function () {
                    stabilizeShopOrdersLayout(event.api, gridEl);
                });
            },
            onPaginationChanged: function (event) {
                var pageApi = event.api;
                if (!pageApi || !pageApi.paginationGetCurrentPage) {
                    return;
                }
                var currentPage = pageApi.paginationGetCurrentPage();
                if (gridEl.__zertiShopOrdersLastPage === currentPage) {
                    return;
                }
                gridEl.__zertiShopOrdersLastPage = currentPage;
                purgeShopOrdersGridCache(pageApi, gridEl);
            },
        };

        gridEl.__zertiShopOrdersTotal = 0;
        gridEl.__zertiShopOrdersLastPage = -1;
        var api = window.agGrid.createGrid(gridEl, gridOptions);
        var loadingState = createShopOrdersLoadingState(gridEl);
        var dataSourceFactory = function () {
            return createShopOrdersDataSource(cfg, searchInput, filterOptionCache, loadingState, api, gridEl);
        };
        gridEl.__zertiAgGridDataSourceFactory = dataSourceFactory;
        gridEl.__zertiAgGridApi = api;
        gridEl.classList.add('zerti-shop-orders-grid--row-nav');
        if (typeof window.zertiConsumePendingListGridRestore === 'function') {
            window.zertiConsumePendingListGridRestore('shop', api);
        }
        if (urlP.statusSlug && isValidShopStatusSlug(cfg, urlP.statusSlug)) {
            applyShopOrdersStatusFilter(api, cfg, urlP.statusSlug, filterOptionCache);
        }
        var dataSource = dataSourceFactory();
        if (api.setGridOption) {
            api.setGridOption('datasource', dataSource);
        } else if (api.setDatasource) {
            api.setDatasource(dataSource);
        }
        applyShopOrdersResponsiveColumns(api, gridEl);
        statusFilterCleanup = installShopOrdersStatusFilterBar(wrap, cfg, gridEl, api, dataSourceFactory);

        var exportCleanup = installShopOrdersExportButtons(wrap, cfg, api, searchInput, gridEl);

        var resizeTimer = null;
        var onResize = function () {
            if (resizeTimer) {
                window.clearTimeout(resizeTimer);
            }
            resizeTimer = window.setTimeout(function () {
                resizeTimer = null;
                applyShopOrdersResponsiveColumns(api, gridEl);
            }, 120);
        };
        window.addEventListener('resize', onResize);
        gridEl.__zertiAgGridCleanup = function () {
            if (resizeTimer) {
                window.clearTimeout(resizeTimer);
                resizeTimer = null;
            }
            window.removeEventListener('resize', onResize);
            if (typeof exportCleanup === 'function') {
                exportCleanup();
            }
            if (typeof statusFilterCleanup === 'function') {
                statusFilterCleanup();
            }
            gridEl.__zertiAgGridDataSourceFactory = null;
            gridEl.__zertiFilterOptionCache = null;
            gridEl.__zertiShopOrdersViewportMode = null;
            loadingState.destroy();
        };

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

    window.zertiInitShopOrdersTable = zertiInitShopOrdersTable;
    window.zertiRefreshShopOrdersGrid = zertiRefreshShopOrdersGrid;
})(window, document);
