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

    var customersUrlSyncTimer = null;

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

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

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

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

    function readUrlParams(cfg) {
        var out = { search: '', orderCol: NaN, orderDir: 'desc' };
        try {
            var sp = new URLSearchParams(window.location.search);
            var ps = cfg.paramSearch || 'zerti_customers_search';
            var pc = cfg.paramOrderCol || 'zerti_customers_order_col';
            var pd = cfg.paramOrderDir || 'zerti_customers_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 replaceCustomersGridUrlParams(api, cfg, searchInput) {
        if (customersUrlSyncTimer) {
            window.clearTimeout(customersUrlSyncTimer);
        }
        customersUrlSyncTimer = window.setTimeout(function () {
            customersUrlSyncTimer = null;
            try {
                var u = new URL(window.location.href);
                var ps = cfg.paramSearch || 'zerti_customers_search';
                var pc = cfg.paramOrderCol || 'zerti_customers_order_col';
                var pd = cfg.paramOrderDir || 'zerti_customers_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 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 scrollCustomersPageToTop() {
        if (typeof window.scrollTo === 'function') {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    }

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

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

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

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

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

        var input = document.createElement('input');
        input.type = 'search';
        input.id = 'zertiCustomersGridSearch';
        input.className = 'form-control form-control-sm zerti-customers-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 getCustomersAlertOverlay() {
        var root = getZertiAdminRoot();
        if (!root) {
            return null;
        }
        var ov = root.querySelector('.zerti-customers-grid-alert-overlay');
        if (!ov) {
            ov = document.createElement('div');
            ov.className = 'zerti-products-grid-alert-overlay zerti-customers-grid-alert-overlay';
            ov.setAttribute('role', 'dialog');
            ov.setAttribute('aria-modal', 'true');
            ov.setAttribute('aria-labelledby', 'zertiCustomersGridAlertMessage');
            ov.hidden = true;
            ov.innerHTML =
                '<div class="zerti-products-grid-alert-dialog alert alert-danger">' +
                '<p id="zertiCustomersGridAlertMessage" 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 showCustomersGridAlert(message, cfg) {
        if (!message) {
            return;
        }
        var ov = getCustomersAlertOverlay();
        if (!ov) {
            window.alert(message);
            return;
        }
        var i18n = (cfg && cfg.i18n) || {};
        var msgEl = ov.querySelector('#zertiCustomersGridAlertMessage');
        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 fetchCustomersTotal(cfg, callback) {
        var ajaxUrl = cfg.ajaxUrl || window.ajaxurl || '';
        if (!ajaxUrl || typeof callback !== 'function') {
            callback(-1);
            return;
        }
        var body = new URLSearchParams({
            action: cfg.action || 'zerti_customers_grid',
            nonce: cfg.nonce || '',
            start: '0',
            limit: '1',
            search: '',
            sort_model: '[]',
        });
        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 submitCustomersExport(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_customers_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 resetCustomersExportButton(btn, defaultLabelEl, defaultLabel) {
        btn.disabled = false;
        btn.removeAttribute('aria-busy');
        if (defaultLabelEl) {
            defaultLabelEl.textContent = defaultLabel;
        }
    }

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

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

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

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

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

        fetchCustomersTotal(cfg, onTotalKnown);
    }

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

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

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

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

    function buildColumnDefs(orderCol, orderDir, viewport, api) {
        var i18n = gridI18n();
        var isCompact = viewport && viewport.isCompact;
        var sortPrefs = customersSortFromApi(api, orderCol, orderDir);
        orderCol = sortPrefs.orderCol;
        orderDir = sortPrefs.orderDir;
        var defs = [
            {
                colId: 'c0',
                headerName: i18n.colId || '',
                field: 'id',
                comparator: numericComparator('idRaw'),
                cellClass: 'text-center',
                minWidth: 95,
                filter: false,
            },
            {
                colId: 'c1',
                headerName: i18n.colName || '',
                field: 'name',
                comparator: textComparator,
                minWidth: isCompact ? 88 : 140,
                flex: isCompact ? 1.1 : undefined,
                filter: false,
            },
            {
                colId: 'c2',
                headerName: i18n.colEmail || '',
                field: 'email',
                comparator: textComparator,
                minWidth: isCompact ? 96 : 170,
                flex: isCompact ? 1.15 : undefined,
                filter: false,
            },
            {
                colId: 'c3',
                headerName: i18n.colPhone || '',
                field: 'phone',
                comparator: textComparator,
                minWidth: isCompact ? 80 : 120,
                flex: isCompact ? 0.85 : undefined,
                filter: false,
            },
            {
                colId: 'c4',
                headerName: i18n.colUsername || '',
                field: 'username',
                comparator: textComparator,
                cellClass: 'text-center zerti-customers-grid-username-cell',
                minWidth: 130,
                filter: false,
            },
            {
                colId: 'c5',
                headerName: i18n.colRegistered || '',
                field: 'registered',
                comparator: numericComparator('registeredSort'),
                minWidth: 155,
                filter: false,
            },
            {
                colId: 'searchText',
                field: 'searchText',
                filter: false,
                hide: true,
                suppressColumnsToolPanel: true,
            },
        ];
        var sortableIndex = !isNaN(orderCol) && orderCol >= 0 && orderCol <= 5 ? orderCol : 5;
        defs[sortableIndex].sort = orderDir === 'asc' ? 'asc' : 'desc';
        return defs;
    }

    function createCustomersLoadingState(gridEl) {
        var activeRequests = 0;
        var el = document.createElement('div');
        el.className = 'zerti-customers-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 refreshCustomersInfiniteCache(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 createCustomersDataSource(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: zertiEffectiveCustomerSearchTerm(searchInput),
                    sort_model: JSON.stringify(sortModel),
                };
                var ajaxBody = Object.assign({}, gridQuery, {
                    action: cfg.action || 'zerti_customers_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 (isLastBlock) {
                            rowCount = startRow + rows.length;
                        } else if (serverTotalKnown) {
                            rowCount = totalRaw;
                        } else {
                            rowCount = -1;
                        }
                        if (serverTotalKnown) {
                            gridEl.__zertiCustomersTotal = totalRaw;
                        } else if (isLastBlock) {
                            gridEl.__zertiCustomersTotal = startRow + rows.length;
                        }
                        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 () {
                            stabilizeCustomersLayout(api, gridEl);
                        });
                        scrollCustomersPageToTop();
                    })
                    .catch(function () {
                        params.failCallback();
                        if (loadingState && loadingState.hide) {
                            loadingState.hide();
                        }
                    });
            },
        };
    }

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

    function handleCustomersRowClicked(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-customers-grid-toolbar'
                )
            ) {
                return;
            }
        }
        var customerId = Number(event.data.idRaw);
        if (!(customerId > 0)) {
            return;
        }
        if (typeof window.zertiOpenCustomerDetail === 'function') {
            window.zertiOpenCustomerDetail(customerId);
        } else if (typeof window.zertiAdminRouteUrl === 'function') {
            var url = window.zertiAdminRouteUrl({ tab: 'customers', customer: customerId });
            if (url) {
                window.location.href = url;
            }
        }
    }

    function applyCustomersResponsiveColumns(api, gridEl) {
        if (!api || !gridEl) {
            return;
        }
        var width = customersGridInnerWidth(gridEl);
        var isCompact = isCustomersGridCompact(width);
        var viewport = { isCompact: isCompact };
        var urlP = readUrlParams(readGridCfg());
        var nextMode = isCompact ? 'compact' : 'desktop';

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

        var visibility = {
            c0: !isCompact,
            c1: true,
            c2: true,
            c3: true,
            c4: !isCompact,
            c5: !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-customers-grid--compact', isCompact);
        stabilizeCustomersLayout(api, gridEl);
    }

    function zertiInitCustomersTable(root) {
        if (!root || !window.agGrid || typeof window.agGrid.createGrid !== 'function') {
            return;
        }
        var gridEl = root.querySelector('#zertiCustomersGrid');
        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-customers-wrap');
        var cfg = readGridCfg();
        var urlP = readUrlParams(cfg);
        var initialSearch = zertiPersianToLatinDigits(urlP.search).trim();
        var searchInput = installSearchToolbar(wrap, cfg, initialSearch);
        var exportCleanup = installCustomersExportButton(wrap, cfg, gridEl, searchInput);
        var pageSize = Number(cfg.pageSize || 50);
        var gridWidth = customersGridInnerWidth(gridEl);
        var initialViewport = {
            isCompact: isCustomersGridCompact(gridWidth),
        };
        gridEl.__zertiCustomersViewportMode = initialViewport.isCompact ? 'compact' : 'desktop';

        var gridOptions = {
            theme: 'legacy',
            rowModelType: 'infinite',
            columnDefs: buildColumnDefs(urlP.orderCol, urlP.orderDir, initialViewport, null),
            defaultColDef: {
                flex: 1,
                sortable: true,
                resizable: true,
                filter: false,
                floatingFilter: false,
                cellClass: 'zerti-customers-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: handleCustomersRowClicked,
            onSortChanged: function (event) {
                replaceCustomersGridUrlParams(event.api, cfg, searchInput);
                refreshCustomersInfiniteCache(event.api, true, gridEl.__zertiAgGridDataSourceFactory);
                window.requestAnimationFrame(function () {
                    stabilizeCustomersLayout(event.api, gridEl);
                });
            },
        };

        var api = window.agGrid.createGrid(gridEl, gridOptions);
        var loadingState = createCustomersLoadingState(gridEl);
        var dataSourceFactory = function () {
            return createCustomersDataSource(cfg, searchInput, loadingState, api, gridEl);
        };
        gridEl.__zertiAgGridDataSourceFactory = dataSourceFactory;
        var dataSource = dataSourceFactory();
        if (api.setGridOption) {
            api.setGridOption('datasource', dataSource);
        } else if (api.setDatasource) {
            api.setDatasource(dataSource);
        }
        gridEl.__zertiAgGridApi = api;
        gridEl.classList.add('zerti-customers-grid--row-nav');
        applyCustomersResponsiveColumns(api, gridEl);

        var resizeTimer = null;
        var onResize = function () {
            if (resizeTimer) {
                window.clearTimeout(resizeTimer);
            }
            resizeTimer = window.setTimeout(function () {
                resizeTimer = null;
                applyCustomersResponsiveColumns(api, gridEl);
            }, 120);
        };
        window.addEventListener('resize', onResize);
        gridEl.__zertiAgGridCleanup = function () {
            if (resizeTimer) {
                window.clearTimeout(resizeTimer);
                resizeTimer = null;
            }
            if (typeof exportCleanup === 'function') {
                exportCleanup();
            }
            window.removeEventListener('resize', onResize);
            gridEl.__zertiAgGridDataSourceFactory = null;
            gridEl.__zertiCustomersViewportMode = null;
            gridEl.__zertiCustomersTotal = undefined;
            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;
                    refreshCustomersInfiniteCache(api, true, dataSourceFactory);
                }
                replaceCustomersGridUrlParams(api, cfg, searchInput);
            };
        }
    }

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