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

    var salesReportUrlSyncTimer = null;

    function gridI18n() {
        var cfg =
            typeof window.zertiSalesReportGrid === 'object' && window.zertiSalesReportGrid
                ? window.zertiSalesReportGrid
                : {};
        return cfg.i18n || {};
    }

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

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

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

    function isValidSalesScope(cfg, scope) {
        if (!scope) {
            return false;
        }
        var slugs = Array.isArray(cfg.salesScopeSlugs) ? cfg.salesScopeSlugs : ['period'];
        return slugs.indexOf(scope) !== -1;
    }

    function readSalesScope(cfg) {
        try {
            var sp = new URLSearchParams(window.location.search);
            var pScope = cfg.paramSalesScope || 'zerti_sales_scope';
            var raw = sp.get(pScope);
            if (raw && isValidSalesScope(cfg, String(raw))) {
                return String(raw);
            }
        } catch (eScope) {}
        return '';
    }

    function salesScopeFilterLabel(cfg, scope) {
        var i18n = (cfg && cfg.i18n) || {};
        if (scope === 'period') {
            return i18n.scopeFilterPeriod || '';
        }
        return '';
    }

    function readUrlParams(cfg) {
        var out = { search: '', orderCol: NaN, orderDir: 'desc', salesScope: readSalesScope(cfg) };
        try {
            var sp = new URLSearchParams(window.location.search);
            var ps = cfg.paramSearch || 'zerti_sales_report_search';
            var pc = cfg.paramOrderCol || 'zerti_sales_report_order_col';
            var pd = cfg.paramOrderDir || 'zerti_sales_report_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';
        } catch (e1) {
            return out;
        }
        return out;
    }

    function replaceSalesReportGridUrlParams(api, cfg, searchInput) {
        if (salesReportUrlSyncTimer) {
            window.clearTimeout(salesReportUrlSyncTimer);
        }
        salesReportUrlSyncTimer = window.setTimeout(function () {
            salesReportUrlSyncTimer = null;
            try {
                var u = new URL(window.location.href);
                var ps = cfg.paramSearch || 'zerti_sales_report_search';
                var pc = cfg.paramOrderCol || 'zerti_sales_report_order_col';
                var pd = cfg.paramOrderDir || 'zerti_sales_report_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 zertiEffectiveSalesReportSearchTerm(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 installSearchToolbar(wrap, cfg, initialSearch) {
        if (!wrap) {
            return null;
        }
        var toolbar = wrap.querySelector('.zerti-sales-report-grid-toolbar');
        if (!toolbar) {
            return null;
        }
        var searchSlot = toolbar.querySelector('.zerti-sales-report-grid-toolbar-search');
        if (!searchSlot) {
            return null;
        }
        searchSlot.innerHTML = '';

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

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

        var input = document.createElement('input');
        input.type = 'search';
        input.id = 'zertiSalesReportGridSearch';
        input.className = 'form-control form-control-sm zerti-sales-report-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 installSalesScopeFilterBar(wrap, cfg, gridEl, api, dataSourceFactory) {
        if (!wrap) {
            return null;
        }
        var host = wrap.querySelector('.zerti-sales-report-grid-toolbar');
        if (!host) {
            return null;
        }
        var existing = host.querySelector('.zerti-sales-scope-filter-bar');
        if (existing) {
            existing.remove();
        }
        var salesScope = readSalesScope(cfg);
        var scopeInUrl = false;
        try {
            scopeInUrl = !!new URLSearchParams(window.location.search).get(cfg.paramSalesScope || 'zerti_sales_scope');
        } catch (eUrl) {}
        if (!scopeInUrl || !salesScope || !isValidSalesScope(cfg, salesScope)) {
            return null;
        }
        var i18n = (cfg && cfg.i18n) || {};
        var bar = document.createElement('div');
        bar.className =
            'zerti-sales-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 = salesScopeFilterLabel(cfg, salesScope);
        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.paramSalesScope || 'zerti_sales_scope');
                var next = u.pathname + u.search + window.location.hash;
                window.history.replaceState(null, '', next);
            } catch (eClear) {}
            bar.remove();
            gridEl.__zertiSalesReportTotal = undefined;
            refreshSalesReportInfiniteCache(api, true, dataSourceFactory);
        });
        bar.appendChild(clearBtn);
        bar.appendChild(label);
        host.insertBefore(bar, host.firstChild);
        return function () {
            if (bar.parentNode) {
                bar.parentNode.removeChild(bar);
            }
        };
    }

    function zertiGridFetchRows(cfg, query, ajaxBody) {
        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 createSalesReportLoadingState(gridEl) {
        var activeRequests = 0;
        var el = document.createElement('div');
        el.className = 'zerti-sales-report-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 refreshSalesReportInfiniteCache(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 buildColumnDefs(orderCol, orderDir, viewport) {
        var i18n = gridI18n();
        var isCompact = viewport && viewport.isCompact;
        function sortState(colIndex) {
            if (orderCol === colIndex) {
                return orderDir;
            }
            return null;
        }
        return [
            {
                colId: 'c0',
                headerName: i18n.colRow || '',
                field: 'rowNum',
                comparator: numericComparator('rowNumRaw'),
                cellClass: 'text-center',
                flex: 0,
                minWidth: 44,
                maxWidth: 72,
                suppressSizeToFit: true,
                resizable: false,
                sort: sortState(0),
                filter: false,
            },
            {
                colId: 'c1',
                headerName: i18n.colProductId || '',
                field: 'productId',
                comparator: numericComparator('productIdRaw'),
                cellClass: 'text-center',
                flex: 0,
                minWidth: 56,
                maxWidth: 96,
                suppressSizeToFit: true,
                resizable: false,
                sort: sortState(1),
                filter: false,
            },
            {
                colId: 'c2',
                headerName: i18n.colName || '',
                field: 'name',
                comparator: function (a, b, nodeA, nodeB) {
                    return textComparator(
                        nodeA && nodeA.data ? nodeA.data.nameSort : '',
                        nodeB && nodeB.data ? nodeB.data.nameSort : ''
                    );
                },
                minWidth: isCompact ? 100 : 140,
                flex: isCompact ? 1 : 2.75,
                suppressSizeToFit: false,
                sort: sortState(2),
                filter: false,
            },
            {
                colId: 'c3',
                headerName: i18n.colSku || '',
                field: 'sku',
                comparator: function (a, b, nodeA, nodeB) {
                    return textComparator(
                        nodeA && nodeA.data ? nodeA.data.skuSort : '',
                        nodeB && nodeB.data ? nodeB.data.skuSort : ''
                    );
                },
                cellClass: 'zerti-ltr-nums text-center',
                flex: 0,
                minWidth: 72,
                maxWidth: 132,
                suppressSizeToFit: true,
                sort: sortState(3),
                filter: false,
            },
            {
                colId: 'c4',
                headerName: isCompact ? i18n.colDate || i18n.colSaleDate || '' : i18n.colSaleDate || '',
                field: 'soldDate',
                comparator: numericComparator('soldDateSort'),
                cellClass: 'text-center',
                flex: isCompact ? 1 : 0,
                minWidth: isCompact ? 88 : 120,
                maxWidth: isCompact ? undefined : 148,
                suppressSizeToFit: !isCompact,
                sort: sortState(4),
                filter: false,
            },
            {
                colId: 'c5',
                headerName: i18n.colSaleAmount || '',
                field: 'priceHtml',
                cellRenderer: htmlRenderer,
                comparator: numericComparator('priceSort'),
                flex: isCompact ? 1 : 0,
                minWidth: isCompact ? 96 : 112,
                maxWidth: isCompact ? undefined : 140,
                suppressSizeToFit: !isCompact,
                sort: sortState(5),
                filter: false,
            },
            {
                colId: 'c6',
                headerName: i18n.colOrderId || '',
                field: 'orderId',
                comparator: numericComparator('orderIdRaw'),
                cellClass: 'text-center',
                flex: 0,
                minWidth: 56,
                maxWidth: 96,
                suppressSizeToFit: true,
                resizable: false,
                sort: sortState(6),
                filter: false,
            },
            {
                colId: 'searchText',
                field: 'searchText',
                hide: true,
                filter: false,
            },
        ];
    }

    function createSalesReportDataSource(cfg, searchInput, loadingState, api, gridEl) {
        return {
            getRows: function (params) {
                var pageSize = Number(cfg.pageSize || 50);
                var sortModel = params.sortModel || [];
                if (loadingState && loadingState.show) {
                    loadingState.show();
                }
                var gridQuery = {
                    start: String(params.startRow || 0),
                    limit: String(pageSize),
                    search: zertiEffectiveSalesReportSearchTerm(searchInput),
                    sort_model: JSON.stringify(sortModel),
                    sales_scope: readSalesScope(cfg),
                };
                var ajaxBody = Object.assign({}, gridQuery, {
                    action: cfg.action || 'zerti_sales_report_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 isLastBlock = rows.length < pageSize;
                        var rowCount;
                        if (Number.isFinite(totalRaw) && totalRaw >= 0) {
                            gridEl.__zertiSalesReportTotal = totalRaw;
                            rowCount = totalRaw;
                        } else if (gridEl && gridEl.__zertiSalesReportTotal > 0) {
                            rowCount = gridEl.__zertiSalesReportTotal;
                        } else if (isLastBlock) {
                            rowCount = startRow + rows.length;
                        } else {
                            rowCount = -1;
                        }
                        if (params.success) {
                            params.success({
                                rowData: rows,
                                rowCount: rowCount >= 0 ? rowCount : undefined,
                            });
                        } else {
                            params.successCallback(rows, rowCount);
                        }
                        if (loadingState && loadingState.hide) {
                            loadingState.hide();
                        }
                    })
                    .catch(function () {
                        if (params.fail) {
                            params.fail();
                        } else if (params.failCallback) {
                            params.failCallback();
                        }
                        if (loadingState && loadingState.hide) {
                            loadingState.hide();
                        }
                    });
            },
        };
    }

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

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

    function stabilizeSalesReportLayout(api, gridEl) {
        if (!api || !gridEl) {
            return;
        }
        if (api.setGridOption) {
            api.setGridOption('suppressHorizontalScroll', isSalesReportGridCompact(salesReportGridInnerWidth(gridEl)));
        }
        if (api.sizeColumnsToFit) {
            window.requestAnimationFrame(function () {
                try {
                    api.sizeColumnsToFit();
                } catch (errFit) {}
            });
        }
    }

    function applySalesReportResponsiveColumns(api, gridEl) {
        if (!api || !gridEl) {
            return;
        }
        var width = salesReportGridInnerWidth(gridEl);
        var isCompact = isSalesReportGridCompact(width);
        var nextMode = isCompact ? 'compact' : 'desktop';
        var urlP = readUrlParams(readGridCfg());

        if (gridEl.__zertiSalesReportViewportMode !== nextMode) {
            gridEl.__zertiSalesReportViewportMode = nextMode;
            var columnDefs = buildColumnDefs(urlP.orderCol, urlP.orderDir, { isCompact: isCompact });
            if (api.setGridOption) {
                api.setGridOption('columnDefs', columnDefs);
            } else if (api.setColumnDefs) {
                api.setColumnDefs(columnDefs);
            }
        }

        var visibility = {
            c0: !isCompact,
            c1: !isCompact,
            c2: true,
            c3: !isCompact,
            c4: true,
            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 });
        }
        gridEl.classList.toggle('zerti-sales-report-grid--compact', isCompact);
        stabilizeSalesReportLayout(api, gridEl);
    }

    function buildSalesReportExportFields(cfg, searchInput, gridEl) {
        var urlP = readUrlParams(cfg);
        var sortModel = [];
        if (gridEl && gridEl.__zertiAgGridApi && gridEl.__zertiAgGridApi.getColumnState) {
            (gridEl.__zertiAgGridApi.getColumnState() || []).forEach(function (col) {
                if (col && col.sort) {
                    sortModel.push({ colId: col.colId, sort: col.sort });
                }
            });
        }
        if (!sortModel.length && !isNaN(urlP.orderCol)) {
            sortModel.push({ colId: 'c' + urlP.orderCol, sort: urlP.orderDir || 'desc' });
        }

        return {
            action: cfg.exportAction || 'zerti_sales_report_export',
            nonce: cfg.exportNonce || '',
            sales_scope: readSalesScope(cfg),
            search: zertiEffectiveSalesReportSearchTerm(searchInput),
            sort_model: JSON.stringify(sortModel),
        };
    }

    function submitSalesReportExport(cfg, searchInput, gridEl) {
        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 = buildSalesReportExportFields(cfg, searchInput, gridEl);

        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 resetSalesReportExportButton(btn, defaultLabelEl, defaultLabel) {
        btn.disabled = false;
        btn.removeAttribute('aria-busy');
        if (defaultLabelEl) {
            defaultLabelEl.textContent = defaultLabel;
        }
    }

    function fetchSalesReportExportCount(cfg, searchInput, gridEl, callback) {
        var ajaxUrl = cfg.ajaxUrl || window.ajaxurl || '';
        if (!ajaxUrl || typeof callback !== 'function') {
            callback(-1);
            return;
        }

        var fields = buildSalesReportExportFields(cfg, searchInput, gridEl);
        var body = new URLSearchParams(fields);
        body.set('export_check', '1');

        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 runSalesReportExport(cfg, gridEl, searchInput, btn, defaultLabelEl, defaultLabel) {
        var i18n = (cfg && cfg.i18n) || {};

        function startDownload() {
            if (defaultLabelEl && i18n.exportWorking) {
                defaultLabelEl.textContent = i18n.exportWorking;
            }
            try {
                submitSalesReportExport(cfg, searchInput, gridEl);
            } catch (eExport) {}
            window.setTimeout(function () {
                resetSalesReportExportButton(btn, defaultLabelEl, defaultLabel);
            }, 1500);
        }

        function onTotalKnown(total) {
            if (total === 0) {
                window.alert(i18n.exportEmpty || '');
                resetSalesReportExportButton(btn, defaultLabelEl, defaultLabel);
                return;
            }
            startDownload();
        }

        fetchSalesReportExportCount(cfg, searchInput, gridEl, onTotalKnown);
    }

    function installSalesReportExportButton(wrap, cfg, gridEl, searchInput) {
        if (!wrap) {
            return null;
        }
        var btn = wrap.querySelector('.zerti-sales-report-export-btn');
        if (!btn) {
            return null;
        }
        var defaultLabelEl = btn.querySelector('.zerti-sales-report-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');
            runSalesReportExport(cfg, gridEl, searchInput, btn, defaultLabelEl, defaultLabel);
        };

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

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

    function zertiInitSalesReportTable(root) {
        if (!root || !window.agGrid || typeof window.agGrid.createGrid !== 'function') {
            return;
        }
        var gridEl = root.querySelector('#zertiSalesReportGrid');
        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-sales-report-wrap');
        var cfg = readGridCfg();
        var urlP = readUrlParams(cfg);
        var initialSearch = zertiPersianToLatinDigits(urlP.search).trim();
        var searchInput = installSearchToolbar(wrap, cfg, initialSearch);
        var exportCleanup = installSalesReportExportButton(wrap, cfg, gridEl, searchInput);
        var scopeFilterCleanup = null;
        var pageSize = Number(cfg.pageSize || 50);
        var gridWidth = salesReportGridInnerWidth(gridEl);
        gridEl.__zertiSalesReportViewportMode = isSalesReportGridCompact(gridWidth) ? 'compact' : 'desktop';

        var gridOptions = {
            theme: 'legacy',
            rowModelType: 'infinite',
            columnDefs: buildColumnDefs(urlP.orderCol, urlP.orderDir, {
                isCompact: isSalesReportGridCompact(gridWidth),
            }),
            defaultColDef: {
                flex: 1,
                sortable: true,
                resizable: true,
                filter: false,
                floatingFilter: false,
                cellClass: 'zerti-sales-report-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
                ? window.zertiAgGridLocaleText(gridI18n(), 'noRowsToShow')
                : {
                      page: '',
                      loadingOoo: gridI18n().loadingOoo || '',
                      noRowsToShow: gridI18n().noRowsToShow || '',
                  },
            getRowId: function (params) {
                return String(params.data.rowKeyRaw || params.data.lineIdRaw);
            },
            suppressRowClickSelection: true,
            onRowClicked: handleSalesReportRowClicked,
            onSortChanged: function (event) {
                replaceSalesReportGridUrlParams(event.api, cfg, searchInput);
                gridEl.__zertiSalesReportTotal = 0;
                refreshSalesReportInfiniteCache(event.api, true, gridEl.__zertiAgGridDataSourceFactory);
            },
        };

        gridEl.__zertiSalesReportTotal = 0;
        var api = window.agGrid.createGrid(gridEl, gridOptions);
        var loadingState = createSalesReportLoadingState(gridEl);
        var dataSourceFactory = function () {
            return createSalesReportDataSource(cfg, searchInput, loadingState, api, gridEl);
        };
        gridEl.__zertiAgGridDataSourceFactory = dataSourceFactory;
        gridEl.__zertiAgGridApi = api;
        gridEl.classList.add('zerti-sales-report-grid--row-nav');

        var dataSource = dataSourceFactory();
        if (api.setGridOption) {
            api.setGridOption('datasource', dataSource);
        } else if (api.setDatasource) {
            api.setDatasource(dataSource);
        }

        scopeFilterCleanup = installSalesScopeFilterBar(wrap, cfg, gridEl, api, dataSourceFactory);
        applySalesReportResponsiveColumns(api, gridEl);

        var resizeTimer = null;
        var onResize = function () {
            if (resizeTimer) {
                window.clearTimeout(resizeTimer);
            }
            resizeTimer = window.setTimeout(function () {
                resizeTimer = null;
                applySalesReportResponsiveColumns(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.__zertiSalesReportTotal = undefined;
            loadingState.destroy();
        };

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

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