(function () {
    'use strict';

    var cfg = typeof window.zertiComponents === 'object' && window.zertiComponents !== null ? window.zertiComponents : {};
    var ajaxUrl = cfg.ajaxUrl || '';
    var nonce = cfg.nonce || '';
    var action = cfg.action || 'zerti_load_component';
    var base = cfg.adminBaseUrl || '';
    var routesCfg = cfg.routes && typeof cfg.routes === 'object' ? cfg.routes : {};
    var PARAMS = routesCfg.params || {
        tab: 'zerti_tab',
        inv: 'zerti_inv',
        fin: 'zerti_fin',
        order: 'zerti_order',
        shop_view: 'zerti_shop_view',
        shop_status: 'zerti_shop_status',
        customer: 'zerti_customer',
        product: 'zerti_product',
        products_stock: 'zerti_products_stock',
        payments_scope: 'zerti_payments_scope',
        sales_scope: 'zerti_sales_scope',
    };
    var allowed = Array.isArray(routesCfg.tabs)
        ? routesCfg.tabs
        : Array.isArray(cfg.allowedTabs)
          ? cfg.allowedTabs
          : ['home', 'shop', 'inventory', 'financial', 'customers', 'settings'];
    var invDefault =
        routesCfg.inventory && typeof routesCfg.inventory.default === 'string'
            ? routesCfg.inventory.default
            : 'warehouse';
    var finDefault =
        routesCfg.financial && typeof routesCfg.financial.default === 'string'
            ? routesCfg.financial.default
            : 'payments';
    var shopViewDefault =
        typeof routesCfg.shopViewDefault === 'string' ? routesCfg.shopViewDefault : 'detail';
    var VALID_SHOP_STATUS = {};
    (Array.isArray(routesCfg.shopStatusSlugs) ? routesCfg.shopStatusSlugs : []).forEach(function (slug) {
        VALID_SHOP_STATUS[slug] = 1;
    });
    var LIST_CTX_STORAGE_PREFIX = 'zertiListCtx:';
    var DETAIL_SKIP_QUERY_PARAMS = {};

    function buildDetailSkipQueryParams() {
        return {
            page: true,
            [PARAMS.order]: true,
            [PARAMS.product]: true,
            [PARAMS.customer]: true,
            [PARAMS.shop_view]: true,
        };
    }

    DETAIL_SKIP_QUERY_PARAMS = buildDetailSkipQueryParams();

    function captureGridFilterModel(scope) {
        var gridEl = null;
        if (scope === 'shop') {
            gridEl = document.getElementById('zertiShopOrdersGrid');
        } else if (scope === 'inventory') {
            gridEl = document.getElementById('zertiProductsGrid');
        } else if (scope === 'financial') {
            gridEl = document.getElementById('zertiPaymentsGrid');
        }
        if (!gridEl || !gridEl.__zertiAgGridApi || typeof gridEl.__zertiAgGridApi.getFilterModel !== 'function') {
            return null;
        }
        var model = gridEl.__zertiAgGridApi.getFilterModel();
        if (!model || typeof model !== 'object') {
            return null;
        }
        return Object.keys(model).length > 0 ? model : null;
    }

    function captureListContext(scope) {
        if (!scope) {
            return;
        }
        var data = { params: {}, filterModel: null };
        try {
            var u = new URL(window.location.href);
            u.searchParams.forEach(function (value, key) {
                if (DETAIL_SKIP_QUERY_PARAMS[key]) {
                    return;
                }
                data.params[key] = value;
            });
        } catch (eCaptureUrl) {}
        data.filterModel = captureGridFilterModel(scope);
        try {
            sessionStorage.setItem(LIST_CTX_STORAGE_PREFIX + scope, JSON.stringify(data));
        } catch (eStore) {}
    }

    function readListContext(scope) {
        if (!scope) {
            return null;
        }
        try {
            var raw = sessionStorage.getItem(LIST_CTX_STORAGE_PREFIX + scope);
            if (!raw) {
                return null;
            }
            var data = JSON.parse(raw);
            return data && typeof data === 'object' ? data : null;
        } catch (eRead) {
            return null;
        }
    }

    function applyListContextToUrl(u, scope) {
        var data = readListContext(scope);
        if (!data || !u) {
            return;
        }
        var params = data.params && typeof data.params === 'object' ? data.params : {};
        Object.keys(params).forEach(function (key) {
            if (DETAIL_SKIP_QUERY_PARAMS[key]) {
                return;
            }
            u.searchParams.set(key, params[key]);
        });
    }

    function queuePendingListGridRestore(scope) {
        var data = readListContext(scope);
        if (!data || !data.filterModel) {
            return;
        }
        window.__zertiPendingListGridRestore = window.__zertiPendingListGridRestore || {};
        window.__zertiPendingListGridRestore[scope] = { filterModel: data.filterModel };
    }

    function consumePendingListGridRestore(scope, api) {
        if (!scope || !api || typeof api.setFilterModel !== 'function') {
            return;
        }
        var pending =
            window.__zertiPendingListGridRestore && window.__zertiPendingListGridRestore[scope]
                ? window.__zertiPendingListGridRestore[scope]
                : null;
        if (!pending || !pending.filterModel) {
            return;
        }
        api.setFilterModel(pending.filterModel);
        delete window.__zertiPendingListGridRestore[scope];
    }

    window.zertiConsumePendingListGridRestore = consumePendingListGridRestore;
    var initialTab =
        cfg.initialRoute && typeof cfg.initialRoute.tab === 'string'
            ? cfg.initialRoute.tab
            : typeof cfg.initialTab === 'string'
              ? cfg.initialTab
              : 'home';
    var i18n = cfg.i18n || {};
    var settingsAction = cfg.settingsAction || 'zerti_save_settings';
    var settingsNonce = cfg.settingsNonce || '';
    var postalPdfSaveAction = cfg.postalPdfSaveAction || 'zerti_save_postal_pdf_settings';
    var postalPdfSaveNonce = cfg.postalPdfSaveNonce || '';
    var lastSettingsTabId = 'identity';
    var pendingSettingsFocusTab = '';
    var tabBundles = cfg.tabBundles && typeof cfg.tabBundles === 'object' ? cfg.tabBundles : {};
    var loadedBundles = { core: 1 };
    (Array.isArray(cfg.initialBundles) ? cfg.initialBundles : []).forEach(function (bundleId) {
        loadedBundles[bundleId] = 1;
    });
    var lazyBundleManifest =
        cfg.lazyBundleManifest && typeof cfg.lazyBundleManifest === 'object' ? cfg.lazyBundleManifest : {};
    var deferredScriptConfig =
        cfg.deferredScriptConfig && typeof cfg.deferredScriptConfig === 'object' ? cfg.deferredScriptConfig : {};
    var loadedLazyStyleHandles = {};
    var loadedLazyScriptHandles = {};
    var lazyBundleInflight = {};
    var VALID_INV_SUBS = {};
    var VALID_FIN_SUBS = {};
    (Array.isArray(routesCfg.inventory && routesCfg.inventory.subs) ? routesCfg.inventory.subs : ['categories', 'attributes', 'attribute-groups', 'warehouse', 'import-export']).forEach(
        function (s) {
            VALID_INV_SUBS[s] = 1;
        }
    );
    (Array.isArray(routesCfg.financial && routesCfg.financial.subs) ? routesCfg.financial.subs : ['payments']).forEach(function (s) {
        VALID_FIN_SUBS[s] = 1;
    });
    var FIN_REPORT_SUBS = {};
    (Array.isArray(routesCfg.reports && routesCfg.reports.subs)
        ? routesCfg.reports.subs
        : ['sales-report', 'reports', 'bi-reports']
    ).forEach(function (s) {
        FIN_REPORT_SUBS[s] = 1;
        VALID_FIN_SUBS[s] = 1;
    });
    var tabLabels = routesCfg.tabLabels && typeof routesCfg.tabLabels === 'object' ? routesCfg.tabLabels : {};
    var inventoryLabels =
        routesCfg.inventoryLabels && typeof routesCfg.inventoryLabels === 'object' ? routesCfg.inventoryLabels : {};
    var financialLabels =
        routesCfg.financialLabels && typeof routesCfg.financialLabels === 'object' ? routesCfg.financialLabels : {};

    function panelNavTitle(tab) {
        var route = parseRoute();
        if (tab !== route.tab) {
            return tabLabels[tab] || tab;
        }
        if (tab === 'inventory') {
            var inv = route.inv || invDefault;
            if (inv === 'warehouse' && typeof route.product === 'number' && !isNaN(route.product) && route.product === 0) {
                return inventoryLabels['product-new'] || tabLabels.inventory || tab;
            }
            return inventoryLabels[inv] || tabLabels.inventory || tab;
        }
        if (tab === 'financial') {
            var fin = route.fin || finDefault;
            return financialLabels[fin] || tabLabels.financial || tab;
        }
        if (tab === 'shop' && typeof route.order === 'number' && !isNaN(route.order) && route.order === 0) {
            return routesCfg.shopOrderCreateLabel || tabLabels.shop || tab;
        }
        return tabLabels[tab] || tab;
    }

    function updatePanelTitle(root, tab) {
        if (!root || !tab) {
            return;
        }
        var panel = root.querySelector('[data-zerti-panel="' + tab + '"]');
        if (!panel) {
            return;
        }
        var titleEl = panel.querySelector('.zerti-panel-title');
        if (titleEl) {
            titleEl.textContent = panelNavTitle(tab);
        }
    }

    function validTab(tab) {
        return allowed.indexOf(tab) !== -1;
    }

    function isValidInv(sub) {
        return !!(sub && VALID_INV_SUBS[sub]);
    }

    function isValidFin(sub) {
        return !!(sub && VALID_FIN_SUBS[sub]);
    }

    function isValidShopStatus(status) {
        return !!(status && VALID_SHOP_STATUS[status]);
    }

    function isValidProductsStockFilter(filter) {
        return filter === 'zero' || filter === 'one' || filter === 'available';
    }

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

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

    function parseRoute() {
        var route = { tab: 'home', inv: invDefault, fin: finDefault };
        try {
            var sp = new URLSearchParams(window.location.search);
            var tabRaw = sp.get(PARAMS.tab);
            if (tabRaw && validTab(tabRaw)) {
                route.tab = tabRaw;
            }
            if (route.tab === 'inventory') {
                var invRaw = sp.get(PARAMS.inv);
                route.inv = isValidInv(invRaw) ? invRaw : invDefault;
                if (route.inv === 'warehouse') {
                    var stockRawInv = sp.get(PARAMS.products_stock);
                    if (stockRawInv && isValidProductsStockFilter(stockRawInv)) {
                        route.products_stock = stockRawInv;
                    }
                    var prodRaw = sp.get(PARAMS.product);
                    if (prodRaw !== null && prodRaw !== '') {
                        var prodNum = parseInt(prodRaw, 10);
                        route.product = isNaN(prodNum) ? 0 : prodNum;
                    }
                }
            }
            if (route.tab === 'financial') {
                var finRaw = sp.get(PARAMS.fin);
                route.fin = isValidFin(finRaw) ? finRaw : finDefault;
                if (route.fin === 'payments') {
                    var scopeRawFin = sp.get(PARAMS.payments_scope);
                    if (scopeRawFin && isValidPaymentsScope(scopeRawFin)) {
                        route.payments_scope = scopeRawFin;
                    }
                }
                if (route.fin === 'sales-report') {
                    var scopeRawSales = sp.get(PARAMS.sales_scope);
                    if (scopeRawSales && isValidSalesScope(scopeRawSales)) {
                        route.sales_scope = scopeRawSales;
                    }
                }
            }
            if (route.tab === 'shop') {
                var statusRawShop = sp.get(PARAMS.shop_status);
                if (statusRawShop && isValidShopStatus(statusRawShop)) {
                    route.shop_status = statusRawShop;
                }
                var orderRaw = sp.get(PARAMS.order);
                if (orderRaw !== null && orderRaw !== '') {
                    var orderNum = parseInt(orderRaw, 10);
                    if (orderNum === 0) {
                        route.order = 0;
                    } else if (orderNum > 0) {
                        route.order = orderNum;
                        route.shop_view = sp.get(PARAMS.shop_view) === 'invoice' ? 'invoice' : shopViewDefault;
                    }
                }
            }
            if (route.tab === 'customers') {
                var custRaw = sp.get(PARAMS.customer);
                if (custRaw !== null && custRaw !== '') {
                    var custNum = parseInt(custRaw, 10);
                    if (custNum > 0) {
                        route.customer = custNum;
                    }
                }
            }
        } catch (errRoute) {}
        return route;
    }

    function routeToUrl(route, options) {
        if (!base) {
            return '';
        }
        options = options && typeof options === 'object' ? options : {};
        try {
            var u = new URL(base, window.location.origin);
            if (options.mergeCurrentQuery) {
                try {
                    var curMerge = new URL(window.location.href);
                    curMerge.searchParams.forEach(function (value, key) {
                        if (!DETAIL_SKIP_QUERY_PARAMS[key]) {
                            u.searchParams.set(key, value);
                        }
                    });
                } catch (eMerge) {}
            }
            Object.keys(PARAMS).forEach(function (key) {
                u.searchParams.delete(PARAMS[key]);
            });
            var tab = route && route.tab ? route.tab : 'home';
            if (tab && tab !== 'home' && validTab(tab)) {
                u.searchParams.set(PARAMS.tab, tab);
            }
            if (tab === 'inventory') {
                var inv = route.inv && isValidInv(route.inv) ? route.inv : invDefault;
                if (inv !== invDefault) {
                    u.searchParams.set(PARAMS.inv, inv);
                }
                if (
                    inv === 'warehouse' &&
                    route.products_stock &&
                    isValidProductsStockFilter(route.products_stock)
                ) {
                    u.searchParams.set(PARAMS.products_stock, route.products_stock);
                }
                if (inv === 'warehouse' && typeof route.product === 'number') {
                    u.searchParams.set(PARAMS.product, String(route.product));
                }
            }
            if (tab === 'financial') {
                var fin = route.fin && isValidFin(route.fin) ? route.fin : finDefault;
                if (fin !== finDefault) {
                    u.searchParams.set(PARAMS.fin, fin);
                }
                if (
                    fin === 'payments' &&
                    route.payments_scope &&
                    isValidPaymentsScope(route.payments_scope)
                ) {
                    u.searchParams.set(PARAMS.payments_scope, route.payments_scope);
                }
                if (
                    fin === 'sales-report' &&
                    route.sales_scope &&
                    isValidSalesScope(route.sales_scope)
                ) {
                    u.searchParams.set(PARAMS.sales_scope, route.sales_scope);
                }
            }
            if (tab === 'shop') {
                if (route.shop_status && isValidShopStatus(route.shop_status)) {
                    u.searchParams.set(PARAMS.shop_status, route.shop_status);
                }
                if (typeof route.order === 'number' && !isNaN(route.order)) {
                    if (route.order === 0) {
                        u.searchParams.set(PARAMS.order, '0');
                    } else if (route.order > 0) {
                        u.searchParams.set(PARAMS.order, String(route.order));
                        if (route.shop_view === 'invoice') {
                            u.searchParams.set(PARAMS.shop_view, 'invoice');
                        }
                    }
                }
            }
            if (tab === 'customers' && route.customer > 0) {
                u.searchParams.set(PARAMS.customer, String(route.customer));
            }
            if (options.listScope) {
                applyListContextToUrl(u, options.listScope);
            }
            return u.pathname + u.search + (window.location.hash || '');
        } catch (errUrl) {
            return base;
        }
    }

    function pushRoute(route, options) {
        var next = routeToUrl(route, options);
        if (!next) {
            return;
        }
        var cur = window.location.pathname + window.location.search + (window.location.hash || '');
        if (next !== cur) {
            history.pushState({ zerti: route }, '', next);
        }
    }

    function replaceRoute(route, options) {
        var next = routeToUrl(route, options);
        if (!next) {
            return;
        }
        var cur = window.location.pathname + window.location.search + (window.location.hash || '');
        if (next !== cur) {
            history.replaceState({ zerti: route }, '', next);
        }
    }

    function routeFromNavElement(el) {
        if (!el) {
            return null;
        }
        var tab = el.getAttribute('data-zerti-tab');
        if (tab && validTab(tab)) {
            var route = { tab: tab };
            var invSub = el.getAttribute('data-zerti-inv-sub');
            if (invSub && isValidInv(invSub)) {
                route.inv = invSub;
            }
            var finSub = el.getAttribute('data-zerti-fin-sub');
            if (finSub && isValidFin(finSub)) {
                route.fin = finSub;
            }
            var shopStatus = el.getAttribute('data-zerti-shop-status');
            if (shopStatus && isValidShopStatus(shopStatus)) {
                route.shop_status = shopStatus;
            }
            var productsStock = el.getAttribute('data-zerti-products-stock');
            if (productsStock && isValidProductsStockFilter(productsStock)) {
                route.products_stock = productsStock;
                route.inv = route.inv || 'warehouse';
            }
            var paymentsScope = el.getAttribute('data-zerti-payments-scope');
            if (paymentsScope && isValidPaymentsScope(paymentsScope)) {
                route.payments_scope = paymentsScope;
                route.fin = route.fin || 'payments';
            }
            var salesScope = el.getAttribute('data-zerti-sales-scope');
            if (salesScope && isValidSalesScope(salesScope)) {
                route.sales_scope = salesScope;
                route.fin = route.fin || 'sales-report';
            }
            return route;
        }
        return null;
    }

    function shouldInterceptAdminLink(e, el) {
        if (!el || !el.getAttribute || !el.getAttribute('href')) {
            return false;
        }
        if (el.classList && el.classList.contains('disabled')) {
            return false;
        }
        if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) {
            return false;
        }
        try {
            var linkUrl = new URL(el.href, window.location.origin);
            var baseUrl = new URL(base || window.location.href, window.location.origin);
            return linkUrl.origin === window.location.origin && linkUrl.pathname === baseUrl.pathname;
        } catch (errLink) {
            return false;
        }
    }

    /**
     * In-app navigation for links (href) and buttons (data-zerti-* controls without href).
     */
    function handleInAppControl(e, el) {
        if (!el) {
            return false;
        }
        if (el.classList && el.classList.contains('disabled')) {
            return false;
        }
        if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) {
            return false;
        }
        var href = el.getAttribute && el.getAttribute('href');
        if (href) {
            if (!shouldInterceptAdminLink(e, el)) {
                return false;
            }
            e.preventDefault();
            return true;
        }
        e.preventDefault();
        return true;
    }

    window.zertiAdminRouteUrl = routeToUrl;

    var processingOrdersAction = cfg.processingOrdersAction || 'zerti_shop_processing_orders_count';
    var processingBadgeTpl = i18n.processingOrdersBadge || '';
    var pendingReviewsAction = cfg.pendingReviewsAction || 'zerti_product_pending_reviews_count';
    var pendingReviewsBadgeTpl = i18n.pendingReviewsBadge || '';
    var pendingCommentsBadgeTpl = i18n.pendingCommentsBadge || '';
    var pendingCustomerRelationsBadgeTpl = i18n.pendingCustomerRelationsBadge || '';
    var pendingFeedbackCountsAction = cfg.pendingFeedbackCountsAction || 'zerti_product_pending_feedback_counts';
    var customerRelationsTabs =
        routesCfg.customerRelations && Array.isArray(routesCfg.customerRelations.tabs)
            ? routesCfg.customerRelations.tabs
            : ['reviews', 'comments'];

    function userCanRefreshProcessingOrdersBadge() {
        return allowed.indexOf('shop') !== -1;
    }

    function userCanRefreshPendingReviewsBadge() {
        for (var crmIdx = 0; crmIdx < customerRelationsTabs.length; crmIdx++) {
            if (allowed.indexOf(customerRelationsTabs[crmIdx]) !== -1) {
                return true;
            }
        }
        return false;
    }

    function processingCountToBadgeLabel(count) {
        var n = parseInt(count, 10);
        if (isNaN(n) || n < 1) {
            return '';
        }
        var display = n > 99 ? '99+' : String(n);
        return display.replace(/[0-9+]/g, function (ch) {
            if (ch === '+') {
                return '+';
            }
            if (typeof window.zertiLocalizeDigits === 'function') {
                return window.zertiLocalizeDigits(ch);
            }
            return '۰۱۲۳۴۵۶۷۸۹'[parseInt(ch, 10)];
        });
    }

    function applyProcessingOrdersBadge(count) {
        var n = parseInt(count, 10);
        if (isNaN(n) || n < 0) {
            n = 0;
        }
        var label = processingCountToBadgeLabel(n);
        document.querySelectorAll('[data-zerti-processing-badge]').forEach(function (el) {
            if (n > 0) {
                el.textContent = label;
                el.classList.remove('d-none');
                el.setAttribute('aria-hidden', 'false');
                el.setAttribute('role', 'status');
                if (processingBadgeTpl) {
                    el.setAttribute('aria-label', processingBadgeTpl.replace('%s', label));
                }
            } else {
                el.textContent = '';
                el.classList.add('d-none');
                el.setAttribute('aria-hidden', 'true');
                el.removeAttribute('role');
                el.removeAttribute('aria-label');
            }
        });
    }

    function refreshProcessingOrdersBadge() {
        if (!ajaxUrl || !nonce || !processingOrdersAction) {
            return;
        }
        if (!userCanRefreshProcessingOrdersBadge()) {
            return;
        }
        var body = new window.FormData();
        body.append('action', processingOrdersAction);
        body.append('nonce', nonce);
        window
            .fetch(ajaxUrl, {
                method: 'POST',
                credentials: 'same-origin',
                body: body,
            })
            .then(function (res) {
                if (!res.ok) {
                    throw new Error('http');
                }
                return res.json();
            })
            .then(function (data) {
                if (!data || !data.success || !data.data) {
                    return;
                }
                applyProcessingOrdersBadge(data.data.count);
            })
            .catch(function () {
                /* Keep SSR count on failure. */
            });
    }

    window.zertiRefreshProcessingOrdersBadge = refreshProcessingOrdersBadge;

    function applyNavCountBadge(selector, count, ariaTpl) {
        var n = parseInt(count, 10);
        if (isNaN(n) || n < 0) {
            n = 0;
        }
        var label = processingCountToBadgeLabel(n);
        document.querySelectorAll(selector).forEach(function (el) {
            if (n > 0) {
                el.textContent = label;
                el.classList.remove('d-none');
                el.setAttribute('aria-hidden', 'false');
                el.setAttribute('role', 'status');
                if (ariaTpl) {
                    el.setAttribute('aria-label', ariaTpl.replace('%s', label));
                }
            } else {
                el.textContent = '';
                el.classList.add('d-none');
                el.setAttribute('aria-hidden', 'true');
                el.removeAttribute('role');
                el.removeAttribute('aria-label');
            }
        });
    }

    function applyPendingReviewsBadge(count) {
        applyNavCountBadge('[data-zerti-pending-reviews-badge]', count, pendingReviewsBadgeTpl);
    }

    function applyPendingCommentsBadge(count) {
        applyNavCountBadge('[data-zerti-pending-comments-badge]', count, pendingCommentsBadgeTpl);
    }

    function applyPendingCustomerRelationsBadge(count) {
        applyNavCountBadge('[data-zerti-pending-customer-relations-badge]', count, pendingCustomerRelationsBadgeTpl);
    }

    function refreshPendingReviewsBadge() {
        if (!ajaxUrl || !nonce || !pendingReviewsAction) {
            return;
        }
        if (!userCanRefreshPendingReviewsBadge()) {
            return;
        }
        var body = new window.FormData();
        body.append('action', pendingReviewsAction);
        body.append('nonce', nonce);
        window
            .fetch(ajaxUrl, {
                method: 'POST',
                credentials: 'same-origin',
                body: body,
            })
            .then(function (res) {
                if (!res.ok) {
                    throw new Error('http');
                }
                return res.json();
            })
            .then(function (data) {
                if (!data || !data.success || !data.data) {
                    return;
                }
                applyPendingReviewsBadge(data.data.count);
            })
            .catch(function () {
                /* Keep SSR count on failure. */
            });
    }

    window.zertiRefreshPendingReviewsBadge = refreshPendingReviewsBadge;

    function refreshPendingFeedbackBadges() {
        if (!ajaxUrl || !nonce || !pendingFeedbackCountsAction) {
            refreshPendingReviewsBadge();
            return;
        }
        if (!userCanRefreshPendingReviewsBadge()) {
            return;
        }
        var body = new window.FormData();
        body.append('action', pendingFeedbackCountsAction);
        body.append('nonce', nonce);
        window
            .fetch(ajaxUrl, {
                method: 'POST',
                credentials: 'same-origin',
                body: body,
            })
            .then(function (res) {
                if (!res.ok) {
                    throw new Error('http');
                }
                return res.json();
            })
            .then(function (data) {
                if (!data || !data.success || !data.data) {
                    return;
                }
                applyPendingReviewsBadge(data.data.reviews);
                applyPendingCommentsBadge(data.data.comments);
                applyPendingCustomerRelationsBadge(data.data.total);
            })
            .catch(function () {
                /* Keep SSR count on failure. */
            });
    }

    window.zertiRefreshPendingFeedbackBadges = refreshPendingFeedbackBadges;

    function refreshNavBadges() {
        refreshProcessingOrdersBadge();
        refreshPendingFeedbackBadges();
    }

    window.zertiRefreshNavBadges = refreshNavBadges;

    var homeStatsAction = cfg.homeStatsAction || 'zerti_home_dashboard_stats';

    function usesWesternHomeDigits() {
        var admin = document.getElementById('zertiAdmin');
        if (admin) {
            var digitsFormat = admin.getAttribute('data-zerti-digits-format');
            if (digitsFormat === 'western') {
                return true;
            }
            if (digitsFormat && digitsFormat !== 'auto' && digitsFormat !== 'western') {
                return false;
            }
            if (admin.getAttribute('data-zerti-digit-script') === 'western') {
                return true;
            }
        }
        var digitCfg = window.zertiDigitLocale;
        if (digitCfg && (digitCfg.format === 'western' || digitCfg.script === 'western')) {
            return true;
        }
        if (typeof window.zertiShouldLocalizeDigits === 'function') {
            return !window.zertiShouldLocalizeDigits();
        }
        return false;
    }

    function formatHomeStatScalar(val) {
        if (typeof val === 'number' && isFinite(val)) {
            val = String(val);
        }
        if (typeof val !== 'string') {
            return val;
        }
        if (usesWesternHomeDigits()) {
            return typeof window.zertiToLatinDigits === 'function' ? window.zertiToLatinDigits(val) : val;
        }
        if (typeof window.zertiLocalizeDigits === 'function') {
            return window.zertiLocalizeDigits(typeof window.zertiToLatinDigits === 'function' ? window.zertiToLatinDigits(val) : val);
        }
        return val;
    }

    function formatHomeStatHtml(html) {
        if (typeof html !== 'string') {
            return html;
        }
        var normalized =
            typeof window.zertiToLatinDigits === 'function' ? window.zertiToLatinDigits(html) : html;
        if (usesWesternHomeDigits()) {
            return normalized;
        }
        if (typeof window.zertiLocalizeDigitsInHtml === 'function') {
            return window.zertiLocalizeDigitsInHtml(normalized);
        }
        if (typeof window.zertiLocalizeDigits === 'function') {
            return window.zertiLocalizeDigits(normalized);
        }
        return normalized;
    }

    function normalizeHomeStatsInSlot(slot) {
        if (!slot) {
            return;
        }
        slot.querySelectorAll('[data-zerti-home-stat]').forEach(function (el) {
            if (el.getAttribute('data-zerti-home-stat-format') === 'html') {
                el.innerHTML = formatHomeStatHtml(el.innerHTML);
                return;
            }
            var raw = el.getAttribute('data-zerti-stat-raw');
            if (raw !== null && raw !== '') {
                el.textContent = formatHomeStatScalar(raw);
                return;
            }
            el.textContent = formatHomeStatScalar(el.textContent);
        });
    }

    var HOME_DASHBOARD_SECTIONS = ['processing', 'inventory', 'sales', 'leaderboards'];

    function getHomeDashboardSections(slot) {
        var sections = ['processing', 'inventory', 'sales'];
        if (slot && slot.querySelector('[data-zerti-home-leaderboard]')) {
            sections.push('leaderboards');
        }
        return sections;
    }

    function renderHomeLeaderboardCard(cardEl, board) {
        if (!cardEl || !board) {
            return;
        }
        var body = cardEl.querySelector('[data-zerti-home-leaderboard-body]');
        if (!body) {
            return;
        }
        var titleEl = cardEl.querySelector('[data-zerti-home-leaderboard-title]');
        if (titleEl) {
            var leaderCfg = typeof window.zertiHomeLeaderboards === 'object' && window.zertiHomeLeaderboards !== null
                ? window.zertiHomeLeaderboards
                : {};
            var boardId = cardEl.getAttribute('data-zerti-home-leaderboard') || board.id || '';
            var titleById = {
                categories: leaderCfg.topCategories,
                products: leaderCfg.topProducts,
            };
            titleEl.textContent = titleById[boardId] || board.label || titleEl.textContent;
        }
        var skeleton = body.querySelector('.zerti-home-skeleton--leaderboard');
        if (skeleton) {
            skeleton.remove();
        }
        var rows = Array.isArray(board.rows) ? board.rows : [];
        if (rows.length === 0) {
            var nodata = (typeof window.zertiHomeLeaderboards === 'object' && zertiHomeLeaderboards.noData) || 'No data for this period.';
            body.innerHTML =
                '<p class="small text-body-secondary mb-0 py-2">' +
                nodata +
                '</p>';
            return;
        }
        var headers = Array.isArray(board.headers) && board.headers.length >= 3
            ? board.headers
            : ['', '', ''];
        var headHtml = headers
            .map(function (header) {
                return '<th scope="col">' + header + '</th>';
            })
            .join('');
        var bodyHtml = rows
            .map(function (row) {
                return (
                    '<tr>' +
                    '<td class="zerti-home-leaderboard-card__name">' +
                    escapeHtml(row.name || '—') +
                    '</td>' +
                    '<td class="zerti-home-leaderboard-card__num zerti-ltr-nums">' +
                    (row.items_sold || '—') +
                    '</td>' +
                    '<td class="zerti-home-leaderboard-card__price zerti-ltr-nums">' +
                    (row.net_sales || '—') +
                    '</td>' +
                    '</tr>'
                );
            })
            .join('');
        body.innerHTML =
            '<div class="table-responsive">' +
            '<table class="table table-sm align-middle mb-0 zerti-home-leaderboard-table">' +
            '<thead><tr>' +
            headHtml +
            '</tr></thead><tbody>' +
            bodyHtml +
            '</tbody></table></div>';
        body.querySelectorAll('.zerti-home-leaderboard-card__num').forEach(function (cell) {
            cell.textContent = formatHomeStatScalar(cell.textContent);
        });
        body.querySelectorAll('.zerti-home-leaderboard-card__price').forEach(function (cell) {
            cell.innerHTML = formatHomeStatHtml(cell.innerHTML);
        });
    }

    function renderHomeLeaderboards(slot, boards) {
        if (!slot || !Array.isArray(boards)) {
            return;
        }
        boards.forEach(function (board) {
            if (!board || !board.id) {
                return;
            }
            var card = slot.querySelector('[data-zerti-home-leaderboard="' + board.id + '"]');
            if (card) {
                renderHomeLeaderboardCard(card, board);
            }
        });
    }

    function applyHomeStatValue(el, val) {
        if (!el || typeof val === 'undefined') {
            return;
        }
        if (el.getAttribute('data-zerti-home-stat-format') === 'html') {
            el.innerHTML = formatHomeStatHtml(val);
        } else {
            if (typeof val === 'number' && isFinite(val)) {
                el.setAttribute('data-zerti-stat-raw', String(val));
            }
            el.textContent = formatHomeStatScalar(val);
        }
        var skeleton = el.querySelector('.zerti-home-skeleton--value');
        if (skeleton) {
            skeleton.remove();
        }
    }

    function syncHomeDashboardLoadingState(slot) {
        if (!slot) {
            return;
        }
        var homeRoot = slot.querySelector('.zerti-component-home');
        if (!homeRoot) {
            return;
        }
        var stillLoading = homeRoot.querySelector('.zerti-home-skeleton--value, .zerti-home-skeleton--chart, .zerti-home-skeleton--leaderboard');
        if (!stillLoading) {
            homeRoot.classList.remove('zerti-component-home--loading');
            homeRoot.removeAttribute('aria-busy');
        }
    }

    function finishHomeChartLoad(slot) {
        if (!slot) {
            return;
        }
        var chartInner = slot.querySelector('.zerti-home-revenue-chart__wrap');
        if (!chartInner) {
            syncHomeDashboardLoadingState(slot);
            return;
        }
        var chartSkeleton = chartInner.querySelector('.zerti-home-skeleton--chart');
        if (chartSkeleton) {
            chartSkeleton.remove();
        }
        var canvas = chartInner.querySelector('.zerti-home-revenue-chart__canvas');
        if (canvas) {
            canvas.hidden = false;
        }
        syncHomeDashboardLoadingState(slot);
    }

    function applyHomeDashboardSection(payload) {
        var adminRoot = document.getElementById('zertiAdmin');
        if (!adminRoot || !payload) {
            return;
        }
        var slot = adminRoot.querySelector('[data-zerti-slot="home"]');
        if (!slot) {
            return;
        }
        var stats = payload.stats;
        if (stats && typeof stats === 'object') {
            Object.keys(stats).forEach(function (key) {
                var el = slot.querySelector('[data-zerti-home-stat="' + key + '"]');
                if (el) {
                    applyHomeStatValue(el, stats[key]);
                }
            });
        }
        var trend = payload.revenue_trend;
        if (trend && Array.isArray(trend.labels) && Array.isArray(trend.totals)) {
            var chartWrap = slot.querySelector('[data-zerti-revenue-json]');
            if (chartWrap) {
                var nextChartJson = JSON.stringify({
                    labels: trend.labels,
                    totals: trend.totals,
                });
                var prevChartJson = chartWrap.getAttribute('data-zerti-revenue-json') || '';
                chartWrap.setAttribute('data-zerti-revenue-json', nextChartJson);
                if (prevChartJson !== nextChartJson) {
                    runHomeRevenueChart(adminRoot);
                }
                finishHomeChartLoad(slot);
            }
        }
        if (payload.leaderboards && Array.isArray(payload.leaderboards)) {
            renderHomeLeaderboards(slot, payload.leaderboards);
        }
        syncHomeDashboardLoadingState(slot);
    }

    function applyHomeDashboardStats(payload) {
        applyHomeDashboardSection(payload);
    }

    function fetchHomeDashboardSection(section, wantRefresh) {
        var body = new window.FormData();
        body.append('action', homeStatsAction);
        body.append('nonce', nonce);
        body.append('section', section);
        if (wantRefresh) {
            body.append('refresh', '1');
        }
        return window
            .fetch(ajaxUrl, {
                method: 'POST',
                credentials: 'same-origin',
                body: body,
            })
            .then(function (res) {
                if (!res.ok) {
                    throw new Error('http');
                }
                return res.json();
            })
            .then(function (data) {
                if (!data || !data.success || !data.data) {
                    return;
                }
                applyHomeDashboardSection(data.data);
            });
    }

    var homeStatsInflight = false;
    var homeStatsPendingRefresh = false;

    function isHomeDashboardVisible() {
        if (allowed.indexOf('home') === -1) {
            return false;
        }
        var adminRoot = document.getElementById('zertiAdmin');
        if (!adminRoot) {
            return false;
        }
        var homePanel = adminRoot.querySelector('[data-zerti-panel="home"]');
        if (!homePanel || homePanel.hasAttribute('hidden')) {
            return false;
        }
        var slot = adminRoot.querySelector('[data-zerti-slot="home"]');
        return !!(slot && slot.getAttribute('data-zerti-loaded') === '1');
    }

    function refreshHomeDashboardStats(options) {
        if (!ajaxUrl || !nonce || !homeStatsAction) {
            return;
        }
        if (allowed.indexOf('home') === -1) {
            return;
        }
        var adminRoot = document.getElementById('zertiAdmin');
        if (!adminRoot) {
            return;
        }
        var slot = adminRoot.querySelector('[data-zerti-slot="home"]');
        if (!slot || slot.getAttribute('data-zerti-loaded') !== '1') {
            return;
        }

        options = options && typeof options === 'object' ? options : {};
        if (options.refresh) {
            homeStatsPendingRefresh = true;
        }
        if (homeStatsInflight) {
            return;
        }
        homeStatsInflight = true;
        var wantRefresh = homeStatsPendingRefresh || !!options.refresh;
        homeStatsPendingRefresh = false;

        var sections = getHomeDashboardSections(slot);
        var warmup = Promise.resolve();

        if (wantRefresh) {
            warmup = fetchHomeDashboardSection('sales', true);
            if (sections.indexOf('leaderboards') !== -1) {
                warmup = warmup.then(function () {
                    return fetchHomeDashboardSection('leaderboards', true);
                });
            }
        }

        warmup
            .then(function () {
                var parallel = sections.filter(function (section) {
                    if (!wantRefresh) {
                        return true;
                    }
                    return section !== 'sales' && section !== 'leaderboards';
                });
                if (parallel.length === 0) {
                    return;
                }
                return Promise.all(
                    parallel.map(function (section) {
                        return fetchHomeDashboardSection(section, false).catch(function () {
                            /* Keep skeletons on failure. */
                        });
                    })
                );
            })
            .catch(function () {
                /* Keep skeletons on failure. */
            })
            .finally(function () {
                homeStatsInflight = false;
                if (homeStatsPendingRefresh) {
                    refreshHomeDashboardStats({ refresh: true });
                }
            });
    }

    window.zertiRefreshHomeDashboardStats = refreshHomeDashboardStats;

    function refreshDashboard(options) {
        refreshNavBadges();
        options = options && typeof options === 'object' ? options : {};
        if (options.forceHome || isHomeDashboardVisible()) {
            refreshHomeDashboardStats({ refresh: options.refresh !== false });
        }
    }

    window.zertiRefreshDashboard = refreshDashboard;

    function applyDeferredScriptConfig(bundleId) {
        var config = deferredScriptConfig[bundleId];
        if (!config || typeof config !== 'object') {
            return;
        }
        Object.keys(config).forEach(function (globalName) {
            window[globalName] = config[globalName];
        });
    }

    function isLazyScriptLoaded(handle) {
        if (!handle) {
            return true;
        }
        if (loadedLazyScriptHandles[handle]) {
            return true;
        }
        return !!document.querySelector('script[data-zerti-handle="' + handle + '"]');
    }

    function loadLazyStyle(entry) {
        return new Promise(function (resolve) {
            if (!entry || !entry.handle || !entry.src || loadedLazyStyleHandles[entry.handle]) {
                resolve();
                return;
            }
            if (document.querySelector('link[data-zerti-handle="' + entry.handle + '"]')) {
                loadedLazyStyleHandles[entry.handle] = 1;
                resolve();
                return;
            }
            var link = document.createElement('link');
            link.rel = 'stylesheet';
            link.href = entry.src;
            link.setAttribute('data-zerti-handle', entry.handle);
            link.onload = function () {
                loadedLazyStyleHandles[entry.handle] = 1;
                resolve();
            };
            link.onerror = function () {
                resolve();
            };
            document.head.appendChild(link);
        });
    }

    function loadLazyScript(entry) {
        return new Promise(function (resolve) {
            if (!entry || !entry.handle || !entry.src || isLazyScriptLoaded(entry.handle)) {
                loadedLazyScriptHandles[entry.handle] = 1;
                resolve();
                return;
            }
            var deps = Array.isArray(entry.deps) ? entry.deps : [];
            Promise.all(
                deps.map(function (dep) {
                    if (isLazyScriptLoaded(dep)) {
                        return Promise.resolve();
                    }
                    var depEntry = null;
                    Object.keys(lazyBundleManifest).some(function (bundleId) {
                        var scripts = lazyBundleManifest[bundleId] && lazyBundleManifest[bundleId].scripts;
                        if (!Array.isArray(scripts)) {
                            return false;
                        }
                        return scripts.some(function (candidate) {
                            if (candidate.handle === dep) {
                                depEntry = candidate;
                                return true;
                            }
                            return false;
                        });
                    });
                    if (depEntry) {
                        return loadLazyScript(depEntry);
                    }
                    return Promise.resolve();
                })
            ).then(function () {
                if (isLazyScriptLoaded(entry.handle)) {
                    resolve();
                    return;
                }
                var script = document.createElement('script');
                script.src = entry.src;
                script.async = false;
                script.setAttribute('data-zerti-handle', entry.handle);
                script.onload = function () {
                    loadedLazyScriptHandles[entry.handle] = 1;
                    resolve();
                };
                script.onerror = function () {
                    resolve();
                };
                document.body.appendChild(script);
            });
        });
    }

    function loadLazyBundle(bundleId) {
        if (!bundleId || bundleId === 'core' || loadedBundles[bundleId]) {
            return Promise.resolve();
        }
        if (lazyBundleInflight[bundleId]) {
            return lazyBundleInflight[bundleId];
        }
        var manifest = lazyBundleManifest[bundleId];
        if (!manifest) {
            loadedBundles[bundleId] = 1;
            return Promise.resolve();
        }
        lazyBundleInflight[bundleId] = Promise.resolve()
            .then(function () {
                var styles = Array.isArray(manifest.styles) ? manifest.styles : [];
                return styles.reduce(function (chain, styleEntry) {
                    return chain.then(function () {
                        return loadLazyStyle(styleEntry);
                    });
                }, Promise.resolve());
            })
            .then(function () {
                var scripts = Array.isArray(manifest.scripts) ? manifest.scripts : [];
                return scripts.reduce(function (chain, scriptEntry) {
                    return chain.then(function () {
                        return loadLazyScript(scriptEntry);
                    });
                }, Promise.resolve());
            })
            .then(function () {
                applyDeferredScriptConfig(bundleId);
                loadedBundles[bundleId] = 1;
                delete lazyBundleInflight[bundleId];
            })
            .catch(function () {
                delete lazyBundleInflight[bundleId];
            });
        return lazyBundleInflight[bundleId];
    }

    function ensureBundlesForTab(tab, callback) {
        var needed = tabBundles[tab] || ['core'];
        var pending = needed.filter(function (bundleId) {
            return bundleId && !loadedBundles[bundleId];
        });
        if (pending.length === 0) {
            needed.forEach(function (bundleId) {
                loadedBundles[bundleId] = 1;
            });
            if (typeof callback === 'function') {
                callback();
            }
            return;
        }
        Promise.all(
            pending.map(function (bundleId) {
                return loadLazyBundle(bundleId);
            })
        ).then(function () {
            needed.forEach(function (bundleId) {
                loadedBundles[bundleId] = 1;
            });
            if (typeof callback === 'function') {
                callback();
            }
        });
    }

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

    function parseAjaxJson(res) {
        if (!res.ok) {
            throw new Error('http ' + res.status);
        }
        return res.json();
    }

    /** Defer chart init so a heavy draw cannot block the home panel AJAX swap. */
    function runHomeRevenueChart(root) {
        window.requestAnimationFrame(function () {
            try {
                if (typeof window.zertiInitHomeRevenueChart === 'function') {
                    window.zertiInitHomeRevenueChart(root);
                }
            } catch (e) {
                /* Chart init must not break the home panel. */
            }
        });
    }

    function runInventoryTermsInit(root, sub, initName) {
        if (!root || !initName) {
            return;
        }

        function tryInit(attempt) {
            if (typeof window[initName] === 'function') {
                try {
                    window[initName](root);
                } catch (e) {
                    /* Term manager init must not break the inventory panel. */
                }
                return;
            }
            if (attempt < 50) {
                window.requestAnimationFrame(function () {
                    tryInit(attempt + 1);
                });
                return;
            }
            ensureBundlesForTab('inventory', function () {
                tryInit(0);
            });
        }

        tryInit(0);
    }

    function runInventoryCategories(root, sub) {
        if (sub !== 'categories') {
            return;
        }
        runInventoryTermsInit(root, sub, 'zertiInitInventoryCategories');
    }

    function runInventoryTags(root, sub) {
        if (sub !== 'tags') {
            return;
        }
        runInventoryTermsInit(root, sub, 'zertiInitInventoryTags');
    }

    function runInventoryBrands(root, sub) {
        if (sub !== 'brands') {
            return;
        }
        runInventoryTermsInit(root, sub, 'zertiInitInventoryBrands');
    }

    function feedbackKindFromTab(tab) {
        return tab === 'comments' ? 'comment' : 'review';
    }

    function runProductFeedbackTab(root, tab) {
        if (!root || (tab !== 'reviews' && tab !== 'comments')) {
            return;
        }
        var slot = root.querySelector('[data-zerti-slot="' + tab + '"]');
        if (!slot) {
            return;
        }
        var kind = feedbackKindFromTab(tab);

        function tryInit(attempt) {
            if (typeof window.zertiInitInventoryReviews === 'function') {
                try {
                    window.zertiInitInventoryReviews(slot, kind);
                } catch (e) {
                    /* Feedback init must not break the panel. */
                }
                return;
            }
            if (attempt < 50) {
                window.requestAnimationFrame(function () {
                    tryInit(attempt + 1);
                });
                return;
            }
            ensureBundlesForTab(tab, function () {
                tryInit(0);
            });
        }

        tryInit(0);
    }

    function runFinancialCoupons(root, sub) {
        if (sub !== 'coupons' || !root) {
            return;
        }

        function tryInit(attempt) {
            var panel = root.querySelector('[data-zerti-coupons-root="1"]');
            if (!panel) {
                if (attempt < 80) {
                    window.requestAnimationFrame(function () {
                        tryInit(attempt + 1);
                    });
                }
                return;
            }
            if (typeof window.zertiInitFinancialCoupons === 'function') {
                try {
                    window.zertiInitFinancialCoupons(root);
                } catch (eCoupons) {
                    /* Coupons init must not break the financial panel. */
                }
                return;
            }
            if (attempt < 120) {
                window.requestAnimationFrame(function () {
                    tryInit(attempt + 1);
                });
                return;
            }
            ensureBundlesForTab('financial', function () {
                tryInit(0);
            });
        }

        ensureBundlesForTab('financial', function () {
            tryInit(0);
        });
    }

    function runCommentsTab(root) {
        runProductFeedbackTab(root, 'comments');
    }

    function runInventoryAttributeGroups(root, sub) {
        if (sub !== 'attribute-groups' || !root) {
            return;
        }

        function tryInit(attempt) {
            if (typeof window.zertiInitInventoryAttributeGroups === 'function') {
                try {
                    window.zertiInitInventoryAttributeGroups(root);
                } catch (e) {
                    /* Attribute groups init must not break the inventory panel. */
                }
                return;
            }
            if (attempt < 50) {
                window.requestAnimationFrame(function () {
                    tryInit(attempt + 1);
                });
                return;
            }
            ensureBundlesForTab('inventory', function () {
                tryInit(0);
            });
        }

        tryInit(0);
    }

    function runInventoryImportExport(root, sub) {
        if (sub !== 'import-export' || !root) {
            return;
        }

        function tryInit(attempt) {
            if (typeof window.zertiInitInventoryImportExport === 'function') {
                try {
                    window.zertiInitInventoryImportExport(root);
                } catch (eIe) {
                    /* Import/export init must not break the inventory panel. */
                }
                return;
            }
            if (attempt < 50) {
                window.requestAnimationFrame(function () {
                    tryInit(attempt + 1);
                });
                return;
            }
            ensureBundlesForTab('inventory', function () {
                tryInit(0);
            });
        }

        tryInit(0);
    }

    function runInventoryAttributes(root, sub) {
        if (sub !== 'attributes' || !root) {
            return;
        }

        function tryInit(attempt) {
            if (typeof window.zertiInitInventoryAttributes === 'function') {
                try {
                    window.zertiInitInventoryAttributes(root);
                } catch (e) {
                    /* Attributes init must not break the inventory panel. */
                }
                return;
            }
            if (attempt < 50) {
                window.requestAnimationFrame(function () {
                    tryInit(attempt + 1);
                });
                return;
            }
            ensureBundlesForTab('inventory', function () {
                tryInit(0);
            });
        }

        tryInit(0);
    }

    function runInventoryProductEdit(root, sub) {
        if (sub !== 'warehouse' || !root) {
            return;
        }

        function tryInitEdit(attempt) {
            if (typeof window.zertiInitProductEdit === 'function') {
                try {
                    window.zertiInitProductEdit(root);
                } catch (eEdit) {
                    /* Product editor init must not break the inventory panel. */
                }
                return;
            }
            if (attempt < 50) {
                window.requestAnimationFrame(function () {
                    tryInitEdit(attempt + 1);
                });
                return;
            }
            ensureBundlesForTab('inventory', function () {
                tryInitEdit(0);
            });
        }

        tryInitEdit(0);
    }

    function runInventoryProducts(root, sub) {
        if (sub !== 'warehouse' || !root) {
            return;
        }

        function tryInit(attempt) {
            if (typeof window.zertiInitProductsTable === 'function') {
                try {
                    window.zertiInitProductsTable(root);
                } catch (e) {
                    /* Products grid init must not break the inventory panel. */
                }
                return;
            }
            if (attempt < 50) {
                window.requestAnimationFrame(function () {
                    tryInit(attempt + 1);
                });
                return;
            }
            ensureBundlesForTab('inventory', function () {
                tryInit(0);
            });
        }

        tryInit(0);
    }

    function inventorySubFromUrl() {
        return parseRoute().inv || invDefault;
    }

    function inventorySubFromDom(slot) {
        if (!slot) {
            return null;
        }
        var inner = slot.querySelector('.zerti-inventory-sub-slot');
        if (!inner) {
            return null;
        }
        var v = inner.getAttribute('data-zerti-inv-active');
        if (v && VALID_INV_SUBS[v]) {
            return v;
        }
        return invDefault;
    }

    function inventoryProductFromUrl() {
        var route = parseRoute();
        if (route.tab !== 'inventory' || route.inv !== 'warehouse') {
            return null;
        }
        if (typeof route.product !== 'number') {
            return null;
        }
        return route.product;
    }

    function inventoryProductStateFromDom(slot) {
        if (!slot) {
            return null;
        }
        var wrap = slot.querySelector('.zerti-inventory-product-edit[data-zerti-product-id]');
        if (!wrap) {
            return null;
        }
        var n = parseInt(wrap.getAttribute('data-zerti-product-id') || '', 10);
        if (isNaN(n)) {
            return null;
        }
        return { id: n };
    }

    function inventoryProductStatesEqual(a, b) {
        if (a === null && b === null) {
            return true;
        }
        if (a === null || b === null) {
            return false;
        }
        return a.id === b.id;
    }

    function setInventoryProductUrl(productId) {
        var route = { tab: 'inventory', inv: 'warehouse' };
        if (typeof productId === 'number') {
            captureListContext('inventory');
            route.product = productId;
            var stockFilter = productsStockFromUrl();
            if (stockFilter) {
                route.products_stock = stockFilter;
            }
            pushRoute(route, { mergeCurrentQuery: true });
            return;
        }
        queuePendingListGridRestore('inventory');
        var ctxInv = readListContext('inventory');
        if (
            ctxInv &&
            ctxInv.params &&
            ctxInv.params[PARAMS.products_stock] &&
            isValidProductsStockFilter(ctxInv.params[PARAMS.products_stock])
        ) {
            route.products_stock = ctxInv.params[PARAMS.products_stock];
        }
        pushRoute(route, { listScope: 'inventory' });
    }

    function setInventorySubnavActive(root, sub) {
        if (!root) {
            return;
        }
        var route = parseRoute();
        var onWarehouse = route.tab === 'inventory' && route.inv === 'warehouse';
        var warehouseProd =
            onWarehouse && typeof route.product === 'number' && !isNaN(route.product) ? route.product : null;
        var activeSub = sub && VALID_INV_SUBS[sub] ? sub : null;
        root.querySelectorAll('.zerti-inventory-subtab[data-zerti-inv-sub]').forEach(function (b) {
            var invSub = b.getAttribute('data-zerti-inv-sub') || '';
            var on = false;
            if (activeSub !== null && invSub === activeSub) {
                on = invSub !== 'warehouse' || warehouseProd === null;
            }
            b.classList.toggle('active', on);
            b.setAttribute('aria-selected', on ? 'true' : 'false');
        });
        root.querySelectorAll('.zerti-inventory-nav-action[data-zerti-inv-nav]').forEach(function (link) {
            var nav = link.getAttribute('data-zerti-inv-nav') || '';
            var on = nav === 'product-new' && onWarehouse && warehouseProd === 0;
            link.classList.toggle('active', on);
            link.setAttribute('aria-selected', on ? 'true' : 'false');
        });
        updatePanelTitle(root, 'inventory');
    }

    function setInventorySubmenuExpanded(root, expanded) {
        if (!root) {
            return;
        }
        root.querySelectorAll('.zerti-inv-submenu-wrap').forEach(function (w) {
            if (expanded) {
                w.removeAttribute('hidden');
            } else {
                w.setAttribute('hidden', '');
            }
        });
        root.querySelectorAll('.zerti-nav-tab[data-zerti-tab="inventory"]').forEach(function (b) {
            b.setAttribute('aria-expanded', expanded ? 'true' : 'false');
        });
    }

    function financialSubFromUrl() {
        return parseRoute().fin || finDefault;
    }

    function financialSubFromDom(slot) {
        if (!slot) {
            return null;
        }
        var inner = slot.querySelector('.zerti-financial-sub-slot');
        if (!inner) {
            return null;
        }
        var fv = inner.getAttribute('data-zerti-fin-active');
        if (fv && VALID_FIN_SUBS[fv]) {
            return fv;
        }
        return finDefault;
    }

    function customerDetailFromUrl() {
        var route = parseRoute();
        return route.customer > 0 ? route.customer : null;
    }

    function customerStateFromDom(slot) {
        if (!slot) {
            return null;
        }
        var wrap = slot.querySelector('.zerti-customer-detail[data-zerti-customer-id]');
        if (!wrap) {
            return null;
        }
        var n = parseInt(wrap.getAttribute('data-zerti-customer-id') || '', 10);
        if (!(n > 0)) {
            return null;
        }
        return { id: n };
    }

    function customerStatesEqual(a, b) {
        if (a === null && b === null) {
            return true;
        }
        if (a === null || b === null) {
            return false;
        }
        return a.id === b.id;
    }

    function setCustomerDetailUrl(customerId) {
        if (customerId > 0) {
            captureListContext('customers');
            pushRoute({ tab: 'customers', customer: customerId }, { mergeCurrentQuery: true });
        } else {
            queuePendingListGridRestore('customers');
            pushRoute({ tab: 'customers' }, { listScope: 'customers' });
        }
    }

    function shopOrderViewFromUrl() {
        var route = parseRoute();
        return route.shop_view === 'invoice' ? 'invoice' : shopViewDefault;
    }

    function shopOrderStateFromUrl() {
        var route = parseRoute();
        if (route.tab !== 'shop' || typeof route.order !== 'number' || isNaN(route.order)) {
            return null;
        }
        if (route.order === 0) {
            return { id: 0, view: 'create' };
        }
        if (route.order > 0) {
            return {
                id: route.order,
                view: route.shop_view === 'invoice' ? 'invoice' : shopViewDefault,
            };
        }
        return null;
    }

    function shopDetailFromUrl() {
        var state = shopOrderStateFromUrl();
        if (!state || state.view === 'create') {
            return null;
        }
        return state.id;
    }

    function shopStatusFromUrl() {
        var route = parseRoute();
        return route.shop_status && isValidShopStatus(route.shop_status) ? route.shop_status : null;
    }

    function productsStockFromUrl() {
        var route = parseRoute();
        return route.products_stock && isValidProductsStockFilter(route.products_stock)
            ? route.products_stock
            : null;
    }

    function shopOrderStateFromDom(slot) {
        if (!slot) {
            return null;
        }
        var createWrap = slot.querySelector('.zerti-shop-order-create[data-zerti-shop-create="1"]');
        if (createWrap) {
            return { id: 0, view: 'create' };
        }
        var wrap = slot.querySelector('.zerti-shop-order-detail[data-zerti-order-id]');
        if (!wrap) {
            return null;
        }
        var n = parseInt(wrap.getAttribute('data-zerti-order-id') || '', 10);
        if (!(n > 0)) {
            return null;
        }
        var view = wrap.getAttribute('data-zerti-shop-view') === 'invoice' ? 'invoice' : 'detail';
        return { id: n, view: view };
    }

    function shopOrderStatesEqual(a, b) {
        if (a === null && b === null) {
            return true;
        }
        if (a === null || b === null) {
            return false;
        }
        return a.id === b.id && a.view === b.view;
    }

    function setShopOrderUrl(orderId, view) {
        if (orderId === 0 && view === 'create') {
            captureListContext('shop');
            var createRoute = { tab: 'shop', order: 0 };
            var statusCreate = shopStatusFromUrl();
            if (statusCreate) {
                createRoute.shop_status = statusCreate;
            }
            pushRoute(createRoute, { mergeCurrentQuery: true });
        } else if (orderId > 0) {
            captureListContext('shop');
            var openRoute = {
                tab: 'shop',
                order: orderId,
                shop_view: view === 'invoice' ? 'invoice' : shopViewDefault,
            };
            var statusOpen = shopStatusFromUrl();
            if (statusOpen) {
                openRoute.shop_status = statusOpen;
            }
            pushRoute(openRoute, { mergeCurrentQuery: true });
        } else {
            queuePendingListGridRestore('shop');
            var backRoute = { tab: 'shop' };
            var statusBack = shopStatusFromUrl();
            if (statusBack) {
                backRoute.shop_status = statusBack;
            }
            if (window.__zertiShopOrderReturnScope === 'financial') {
                queuePendingListGridRestore('financial');
                pushRoute({ tab: 'financial', fin: finDefault }, { listScope: 'financial' });
            } else {
                pushRoute(backRoute, { listScope: 'shop' });
            }
        }
    }

    function buildRouteFromTabAndDom(tab, root) {
        var route = { tab: tab };
        if (tab === 'inventory' && root) {
            var invSlot = root.querySelector('[data-zerti-slot="inventory"]');
            var invDom = inventorySubFromDom(invSlot);
            route.inv = invDom || inventorySubFromUrl();
            if (route.inv === 'warehouse') {
                var prodDom = inventoryProductStateFromDom(invSlot);
                if (prodDom) {
                    route.product = prodDom.id;
                } else {
                    var stockFilter = productsStockFromUrl();
                    if (stockFilter) {
                        route.products_stock = stockFilter;
                    }
                }
            }
        }
        if (tab === 'financial' && root) {
            var finSlot = root.querySelector('[data-zerti-slot="financial"]');
            var finDom = financialSubFromDom(finSlot);
            route.fin = finDom || financialSubFromUrl();
            var finRoute = parseRoute();
            if (route.fin === 'payments' && finRoute.payments_scope && isValidPaymentsScope(finRoute.payments_scope)) {
                route.payments_scope = finRoute.payments_scope;
            }
            if (route.fin === 'sales-report' && finRoute.sales_scope && isValidSalesScope(finRoute.sales_scope)) {
                route.sales_scope = finRoute.sales_scope;
            }
        }
        if (tab === 'shop' && root) {
            var shopState = shopOrderStateFromDom(root.querySelector('[data-zerti-slot="shop"]'));
            if (shopState && shopState.view === 'create') {
                route.order = 0;
            } else if (shopState && shopState.id > 0) {
                route.order = shopState.id;
                route.shop_view = shopState.view;
            } else {
                var shopStatus = shopStatusFromUrl();
                if (shopStatus) {
                    route.shop_status = shopStatus;
                }
            }
        }
        if (tab === 'customers' && root) {
            var custState = customerStateFromDom(root.querySelector('[data-zerti-slot="customers"]'));
            if (custState && custState.id > 0) {
                route.customer = custState.id;
            }
        }
        return route;
    }

    function isReportsNavActive(tab, finSub) {
        return tab === 'financial' && !!(finSub && FIN_REPORT_SUBS[finSub]);
    }

    function setFinancialSubnavActive(root, sub) {
        if (!root) {
            return;
        }
        var activeSub = sub && VALID_FIN_SUBS[sub] && !FIN_REPORT_SUBS[sub] ? sub : null;
        root.querySelectorAll('.zerti-financial-subtab[data-zerti-fin-sub]').forEach(function (b) {
            var on = activeSub !== null && b.getAttribute('data-zerti-fin-sub') === activeSub;
            b.classList.toggle('active', on);
            b.setAttribute('aria-selected', on ? 'true' : 'false');
        });
        updatePanelTitle(root, 'financial');
    }

    function setReportsSubnavActive(root, sub) {
        if (!root) {
            return;
        }
        var activeSub = sub && FIN_REPORT_SUBS[sub] ? sub : null;
        root.querySelectorAll('.zerti-reports-subtab[data-zerti-fin-sub]').forEach(function (b) {
            var on = activeSub !== null && b.getAttribute('data-zerti-fin-sub') === activeSub;
            b.classList.toggle('active', on);
            b.setAttribute('aria-selected', on ? 'true' : 'false');
        });
        updatePanelTitle(root, 'financial');
    }

    function setReportsSubmenuExpanded(root, expanded) {
        if (!root) {
            return;
        }
        root.querySelectorAll('.zerti-reports-submenu-wrap').forEach(function (w) {
            if (expanded) {
                w.removeAttribute('hidden');
            } else {
                w.setAttribute('hidden', '');
            }
        });
        root.querySelectorAll('.zerti-nav-tab[data-zerti-tab="reports"]').forEach(function (b) {
            b.setAttribute('aria-expanded', expanded ? 'true' : 'false');
        });
    }

    function syncFinancialNavState(root, tab, finSub) {
        if (!root) {
            return;
        }
        var reportView = isReportsNavActive(tab, finSub);
        if (tab === 'financial') {
            if (reportView) {
                setFinancialSubmenuExpanded(root, false);
                setReportsSubmenuExpanded(root, true);
                setFinancialSubnavActive(root, null);
                setReportsSubnavActive(root, finSub);
            } else {
                setFinancialSubmenuExpanded(root, true);
                setReportsSubmenuExpanded(root, false);
                setFinancialSubnavActive(root, finSub);
                setReportsSubnavActive(root, null);
            }
        } else {
            setFinancialSubmenuExpanded(root, false);
            setReportsSubmenuExpanded(root, false);
            setFinancialSubnavActive(root, null);
            setReportsSubnavActive(root, null);
        }
    }

    function setFinancialSubmenuExpanded(root, expanded) {
        if (!root) {
            return;
        }
        root.querySelectorAll('.zerti-fin-submenu-wrap').forEach(function (w) {
            if (expanded) {
                w.removeAttribute('hidden');
            } else {
                w.setAttribute('hidden', '');
            }
        });
        root.querySelectorAll('.zerti-nav-tab[data-zerti-tab="financial"]').forEach(function (b) {
            b.setAttribute('aria-expanded', expanded ? 'true' : 'false');
        });
    }

    function setCustomerRelationsSubmenuExpanded(root, expanded) {
        if (!root) {
            return;
        }
        root.querySelectorAll('.zerti-crm-submenu-wrap').forEach(function (w) {
            if (expanded) {
                w.removeAttribute('hidden');
            } else {
                w.setAttribute('hidden', '');
            }
        });
        root.querySelectorAll('.zerti-nav-tab[data-zerti-tab="customer_relations"]').forEach(function (b) {
            b.setAttribute('aria-expanded', expanded ? 'true' : 'false');
        });
    }

    function isCustomerRelationsPanelTab(tab) {
        var crm =
            routesCfg.customerRelations && Array.isArray(routesCfg.customerRelations.tabs)
                ? routesCfg.customerRelations.tabs
                : ['customers', 'reviews', 'comments'];
        return crm.indexOf(tab) !== -1;
    }

    function setCustomerRelationsSubnavActive(root, tab) {
        if (!root) {
            return;
        }
        root.querySelectorAll('.zerti-crm-subtab[data-zerti-tab]').forEach(function (b) {
            var panelTab = b.getAttribute('data-zerti-tab') || '';
            var on = isCustomerRelationsPanelTab(tab) && panelTab === tab;
            b.classList.toggle('active', on);
            b.setAttribute('aria-selected', on ? 'true' : 'false');
        });
    }

    /** Close the mobile offcanvas menu after the user picks a tab. */
    function closeMobileSidebar() {
        var oc = document.getElementById('zertiSidebar');
        if (!oc) {
            return;
        }
        if (window.bootstrap && window.bootstrap.Offcanvas) {
            var Offcanvas = window.bootstrap.Offcanvas;
            var inst = Offcanvas.getInstance(oc);
            if (!inst && typeof Offcanvas.getOrCreateInstance === 'function') {
                inst = Offcanvas.getOrCreateInstance(oc);
            }
            if (inst) {
                inst.hide();
                return;
            }
        }
        if (!oc.classList.contains('show')) {
            return;
        }
        oc.classList.remove('show');
        oc.setAttribute('aria-hidden', 'true');
        oc.removeAttribute('aria-modal');
        var backdrop = document.querySelector('.offcanvas-backdrop');
        if (backdrop) {
            backdrop.remove();
        }
        document.body.classList.remove('offcanvas-open', 'modal-open');
        document.body.style.removeProperty('overflow');
        document.body.style.removeProperty('padding-right');
    }

    function syncUrl(tab, root, usePush) {
        var route = buildRouteFromTabAndDom(tab, root);
        if (usePush) {
            pushRoute(route);
        } else {
            replaceRoute(route);
        }
    }

    function errorMarkup() {
        var msg = escapeHtml(i18n.loadError || '');
        var retry = escapeHtml(i18n.retry || '');
        return (
            '<div class="alert alert-danger zerti-component-error mb-0" role="alert">' +
            '<p class="mb-2">' + msg + '</p>' +
            '<button type="button" class="btn btn-sm btn-outline-danger zerti-component-retry">' + retry + '</button>' +
            '</div>'
        );
    }

    function init() {
        var root = document.getElementById('zertiAdmin');
        if (!root) {
            return;
        }

        /** Skip one network round-trip when PHP already rendered the initial tab. */
        var allowInitialSsrSkip = true;
        /** Cancel in-flight component fetch when switching tabs again. */
        var tabFetchAbort = null;
        /** Monotonic id so stale responses never overwrite the DOM. */
        var fetchGenCounter = 0;

        function clearComponentLoadOverlays() {
            root.querySelectorAll('.zerti-component-load-overlay').forEach(function (el) {
                el.remove();
            });
        }

        function createComponentLoadOverlay(label, options) {
            options = options && typeof options === 'object' ? options : {};
            var overlay = document.createElement('div');
            overlay.className = 'zerti-component-load-overlay text-body-secondary';
            if (options.dataAttr) {
                overlay.setAttribute('data-zerti-' + options.dataAttr, '1');
            } else {
                overlay.setAttribute('data-zerti-component-load', '1');
            }
            overlay.setAttribute('role', 'status');
            overlay.setAttribute('aria-live', 'polite');
            var text = label || (cfg.i18n && cfg.i18n.loading) || 'Loading';
            overlay.innerHTML =
                '<span class="spinner-border spinner-border-sm" aria-hidden="true"></span>' +
                '<span>' + escapeHtml(text) + '</span>';
            return overlay;
        }

        function attachComponentCardLoadOverlay(slot) {
            if (!slot) {
                return null;
            }
            clearComponentLoadOverlays();
            slot.classList.add('zerti-panel-slot--loading');
            var overlay = createComponentLoadOverlay((cfg.i18n && cfg.i18n.loading) || 'Loading');
            slot.appendChild(overlay);
            return overlay;
        }

        function attachSettingsSaveOverlay(componentEl) {
            if (!componentEl) {
                return null;
            }
            clearComponentLoadOverlays();
            var existing = componentEl.querySelector('.zerti-component-load-overlay[data-zerti-settings-save]');
            if (existing) {
                return existing;
            }
            var overlay = createComponentLoadOverlay((cfg.i18n && cfg.i18n.saving) || 'Saving', {
                dataAttr: 'settings-save',
            });
            componentEl.classList.add('zerti-settings-saving');
            componentEl.setAttribute('aria-busy', 'true');
            componentEl.appendChild(overlay);
            return overlay;
        }

        function detachSettingsSaveOverlay(overlayEl, componentEl) {
            if (overlayEl && overlayEl.parentNode) {
                overlayEl.remove();
            }
            if (componentEl) {
                componentEl.classList.remove('zerti-settings-saving');
                componentEl.removeAttribute('aria-busy');
            }
        }

        function detachComponentCardLoadOverlay(overlayEl, slot) {
            if (overlayEl && overlayEl.parentNode) {
                overlayEl.remove();
            }
            if (slot) {
                slot.classList.remove('zerti-panel-slot--loading');
                slot.setAttribute('data-zerti-fetching', '0');
                slot.removeAttribute('aria-busy');
            }
        }

        function syncSettingsTabField(layout, tabId) {
            if (!layout || !tabId) {
                return;
            }
            lastSettingsTabId = tabId;
            var form = layout.closest('form.zerti-settings-form');
            if (!form) {
                return;
            }
            var tabField = form.querySelector('[name="zerti_settings_active_tab"]');
            if (tabField) {
                tabField.value = tabId;
            }
        }

        function activateSettingsTab(layout, tabId) {
            if (!layout || !tabId) {
                return;
            }
            var previousTabId = getActiveSettingsTabId(layout);
            layout.querySelectorAll('[data-zerti-settings-tab]').forEach(function (link) {
                var isActive = link.getAttribute('data-zerti-settings-tab') === tabId;
                link.classList.toggle('active', isActive);
                link.setAttribute('aria-selected', isActive ? 'true' : 'false');
                var item = link.closest('.zerti-wc-tabs__item');
                if (item) {
                    item.classList.toggle('active', isActive);
                }
            });
            layout.querySelectorAll('[data-zerti-settings-panel]').forEach(function (panel) {
                var isActive = panel.getAttribute('data-zerti-settings-panel') === tabId;
                panel.classList.toggle('active', isActive);
                if (isActive) {
                    panel.removeAttribute('hidden');
                } else {
                    panel.setAttribute('hidden', '');
                }
            });
            syncSettingsTabField(layout, tabId);
            toggleSettingsSaveRow(layout, tabId);
            if (tabId === 'license' && previousTabId !== 'license') {
                var licenseApi = proLicense();
                if (licenseApi && typeof licenseApi.onActivateSettingsTab === 'function') {
                    licenseApi.onActivateSettingsTab(layout, tabId);
                }
            }
        }

        function openLicenseSettingsTab(focusTabId) {
            pendingSettingsFocusTab = focusTabId || 'license';
            pushRoute({ tab: 'settings' });
            setTab('settings', true);
            var settingsSlot = root.querySelector('[data-zerti-slot="settings"]');
            if (
                settingsSlot &&
                settingsSlot.getAttribute('data-zerti-loaded') === '1' &&
                pendingSettingsFocusTab
            ) {
                var focusLayout = settingsSlot.querySelector('.zerti-settings-layout');
                if (focusLayout) {
                    var focusTabIdLocal = pendingSettingsFocusTab;
                    pendingSettingsFocusTab = '';
                    activateSettingsTab(focusLayout, focusTabIdLocal);
                }
            }
        }

        function toggleSettingsSaveRow(layout, tabId) {
            if (!layout) {
                return;
            }
            var form = layout.closest('form.zerti-settings-form');
            if (!form) {
                return;
            }
            var saveRow = form.querySelector('.zerti-settings-save-row');
            if (saveRow) {
                saveRow.hidden = tabId === 'license';
            }
        }

        function getActiveSettingsTabId(layout) {
            if (!layout) {
                return lastSettingsTabId || 'identity';
            }

            var activeItem = layout.querySelector('.zerti-wc-tabs__item.active [data-zerti-settings-tab]');
            if (activeItem) {
                return activeItem.getAttribute('data-zerti-settings-tab') || '';
            }

            var activeLink = layout.querySelector('[data-zerti-settings-tab].active');
            if (activeLink) {
                return activeLink.getAttribute('data-zerti-settings-tab') || '';
            }

            var panels = layout.querySelectorAll('[data-zerti-settings-panel]');
            for (var i = 0; i < panels.length; i++) {
                if (panels[i].classList.contains('active')) {
                    return panels[i].getAttribute('data-zerti-settings-panel') || '';
                }
            }

            return lastSettingsTabId || 'identity';
        }

        function initSettingsRegional(scope) {
            var root = scope || document;
            var form = root.querySelector('.zerti-settings-form');
            if (!form || form.getAttribute('data-zerti-settings-regional-bound') === '1') {
                return;
            }
            form.setAttribute('data-zerti-settings-regional-bound', '1');

            var localeDefaults = cfg.localeRegionalDefaults || {};
            var localeField = form.querySelector('[name="zerti_settings[general][admin_locale]"]');
            var directionField = form.querySelector('[name="zerti_settings[general][text_direction]"]');
            var calendarField = form.querySelector('[name="zerti_settings[general][calendar]"]');
            var directionManualField = form.querySelector('[name="zerti_settings[general][direction_manual]"]');
            var calendarManualField = form.querySelector('[name="zerti_settings[general][calendar_manual]"]');
            var digitsFormatField = form.querySelector('[name="zerti_settings[general][digits_format]"]');
            var digitsFormatManualField = form.querySelector('[name="zerti_settings[general][digits_format_manual]"]');

            function isDirectionManual() {
                return directionManualField && directionManualField.value === '1';
            }

            function isCalendarManual() {
                return calendarManualField && calendarManualField.value === '1';
            }

            function isDigitsFormatManual() {
                return digitsFormatManualField && digitsFormatManualField.value === '1';
            }

            function setDirectionManual(manual) {
                if (directionManualField) {
                    directionManualField.value = manual ? '1' : '0';
                }
            }

            function setCalendarManual(manual) {
                if (calendarManualField) {
                    calendarManualField.value = manual ? '1' : '0';
                }
            }

            function setDigitsFormatManual(manual) {
                if (digitsFormatManualField) {
                    digitsFormatManualField.value = manual ? '1' : '0';
                }
            }

            function applyLocaleDefaults(localeCode) {
                var pair = localeDefaults[localeCode];
                if (!pair) {
                    return;
                }
                if (!isDirectionManual() && pair.direction && directionField) {
                    directionField.value = pair.direction;
                }
                if (!isCalendarManual() && pair.calendar && calendarField) {
                    calendarField.value = pair.calendar;
                }
                if (!isDigitsFormatManual() && pair.digits && digitsFormatField) {
                    digitsFormatField.value = pair.digits;
                }
            }

            if (localeField) {
                localeField.addEventListener('change', function () {
                    applyLocaleDefaults(String(localeField.value || ''));
                });
            }

            if (directionField) {
                directionField.addEventListener('change', function () {
                    setDirectionManual(true);
                });
            }

            if (calendarField) {
                calendarField.addEventListener('change', function () {
                    setCalendarManual(true);
                });
            }

            if (digitsFormatField) {
                digitsFormatField.addEventListener('change', function () {
                    setDigitsFormatManual(true);
                });
            }
        }

        function syncVisualThemePostField(form) {
            if (!form) {
                return '';
            }
            var select = form.querySelector('[data-zerti-visual-theme-select]');
            var hidden = form.querySelector('#zertiVisualThemePostField');
            var value = select ? String(select.value || 'zerti') : 'zerti';
            if (hidden) {
                hidden.value = value;
            }

            return value;
        }

        function getCurrentVisualTheme(root) {
            if (root && root.getAttribute('data-zerti-visual-theme')) {
                return String(root.getAttribute('data-zerti-visual-theme'));
            }

            return cfg.visualTheme || 'zerti';
        }

        function initSettingsThemes(scope) {
            var root = scope || document;
            var form = root.querySelector('.zerti-settings-form');
            if (!form || form.getAttribute('data-zerti-settings-themes-bound') === '1') {
                return;
            }
            form.setAttribute('data-zerti-settings-themes-bound', '1');

            var themeField = form.querySelector('[data-zerti-visual-theme-select]');
            var rabbitmpCustomization = form.querySelector('[data-zerti-rabbitmp-customization]');
            var demerzelCustomization = form.querySelector('[data-zerti-demerzel-customization]');

            function toggleThemeCustomizations() {
                if (!themeField) {
                    return;
                }
                var theme = String(themeField.value || '');
                if (rabbitmpCustomization) {
                    rabbitmpCustomization.classList.toggle('d-none', theme !== 'rabbitmp');
                }
                if (demerzelCustomization) {
                    demerzelCustomization.classList.toggle('d-none', theme !== 'demerzel');
                }
            }

            if (themeField) {
                themeField.addEventListener('change', function () {
                    syncVisualThemePostField(form);
                    toggleThemeCustomizations();
                });
                syncVisualThemePostField(form);
                toggleThemeCustomizations();
            }

            form.querySelectorAll('[data-zerti-theme-color-picker-for]').forEach(function (picker) {
                var targetId = picker.getAttribute('data-zerti-theme-color-picker-for');
                var textField = targetId ? form.querySelector('#' + targetId) : null;
                if (!textField) {
                    return;
                }
                picker.addEventListener('input', function () {
                    textField.value = picker.value;
                });
                textField.addEventListener('input', function () {
                    if (/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(String(textField.value || ''))) {
                        picker.value = textField.value;
                    }
                });
            });

            form.querySelectorAll('[data-zerti-theme-radius-range]').forEach(function (range) {
                var field = range.closest('.zerti-settings-themes__field');
                if (!field) {
                    return;
                }
                var hidden = field.querySelector('[data-zerti-theme-radius-hidden]');
                var display = field.querySelector('[data-zerti-theme-radius-display]');

                function syncRadiusRange() {
                    var px = String(range.value || '0');
                    if (hidden) {
                        hidden.value = px + 'px';
                    }
                    if (display) {
                        display.textContent = px + 'px';
                    }
                    range.setAttribute('aria-valuenow', px);
                }

                range.addEventListener('input', syncRadiusRange);
                range.addEventListener('change', syncRadiusRange);
                syncRadiusRange();
            });

            form.querySelectorAll('[data-zerti-theme-radius-reset]').forEach(function (resetBtn) {
                resetBtn.addEventListener('click', function () {
                    var field = resetBtn.closest('.zerti-settings-themes__field');
                    if (!field) {
                        return;
                    }
                    var range = field.querySelector('[data-zerti-theme-radius-range]');
                    if (!range) {
                        return;
                    }
                    var defaultPx = resetBtn.getAttribute('data-zerti-theme-radius-default') || '0';
                    range.value = defaultPx;
                    range.setAttribute('aria-valuenow', defaultPx);
                    range.dispatchEvent(new Event('input', { bubbles: true }));
                });
            });
        }

        function collectPostalPdfPayload(form) {
            if (!form) {
                return null;
            }
            var panel = form.querySelector('[data-zerti-postal-pdf-settings="1"]');
            if (!panel) {
                return null;
            }
            var sellerSize = panel.querySelector('[data-zerti-postal-pdf-field="seller_font_size"]');
            var sellerWeight = panel.querySelector('[data-zerti-postal-pdf-field="seller_font_weight"]');
            var customerSize = panel.querySelector('[data-zerti-postal-pdf-field="customer_font_size"]');
            var customerWeight = panel.querySelector('[data-zerti-postal-pdf-field="customer_font_weight"]');
            var mapsToggle = panel.querySelector('[data-zerti-postal-pdf-field="show_google_maps"]');
            if (!sellerSize || !sellerWeight || !customerSize || !customerWeight) {
                return null;
            }
            return {
                seller_font_size: sellerSize.value || '',
                seller_font_weight: sellerWeight.value || '',
                customer_font_size: customerSize.value || '',
                customer_font_weight: customerWeight.value || '',
                show_google_maps: mapsToggle && mapsToggle.checked ? '1' : '0',
            };
        }

        /**
         * Copy postal tab UI into hidden fields at the top of the form (early in POST order).
         *
         * @param {HTMLFormElement} form
         */
        function syncPostalPdfPostFields(form) {
            var payload = collectPostalPdfPayload(form);
            if (!payload) {
                return;
            }
            var map = {
                seller_font_size: 'zertiPostalPdfFieldSellerFontSize',
                seller_font_weight: 'zertiPostalPdfFieldSellerFontWeight',
                customer_font_size: 'zertiPostalPdfFieldCustomerFontSize',
                customer_font_weight: 'zertiPostalPdfFieldCustomerFontWeight',
                show_google_maps: 'zertiPostalPdfFieldShowGoogleMaps',
            };
            Object.keys(map).forEach(function (key) {
                var field = form.querySelector('#' + map[key]);
                if (field) {
                    field.value = payload[key];
                }
            });
        }

        /**
         * Attach postal PDF tab values to the main settings FormData (same request as save).
         *
         * @param {HTMLFormElement} form
         * @param {FormData} body
         */
        function appendPostalPdfFieldsToFormData(form, body) {
            syncPostalPdfPostFields(form);
            var payload = collectPostalPdfPayload(form);
            if (!payload) {
                return;
            }
            body.set('seller_font_size', payload.seller_font_size);
            body.set('seller_font_weight', payload.seller_font_weight);
            body.set('customer_font_size', payload.customer_font_size);
            body.set('customer_font_weight', payload.customer_font_weight);
            body.set('show_google_maps', payload.show_google_maps);
        }

        function initSettingsTabs(scope) {
            var root = scope || document;
            var layout = root.querySelector('.zerti-component-settings .zerti-settings-layout');
            if (!layout) {
                return null;
            }

            if (layout.getAttribute('data-zerti-settings-tabs-bound') !== '1') {
                layout.setAttribute('data-zerti-settings-tabs-bound', '1');

                layout.querySelectorAll('[data-zerti-settings-tab]').forEach(function (link) {
                    link.addEventListener('click', function (event) {
                        event.preventDefault();
                        activateSettingsTab(layout, link.getAttribute('data-zerti-settings-tab'));
                    });
                });
            }

            var currentTabId = getActiveSettingsTabId(layout);
            if (currentTabId) {
                syncSettingsTabField(layout, currentTabId);
                toggleSettingsSaveRow(layout, currentTabId);
            }

            return layout;
        }

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

        function bindBulkActionSafetyGate(shell) {
            if (!shell) {
                return;
            }

            var gate = shell.querySelector('[data-zerti-bulk-action-gate]');
            var content = shell.querySelector('[data-zerti-bulk-action-content]');
            if (!gate || !content) {
                return;
            }

            if (content.closest('[data-zerti-pro-preview="1"]')) {
                gate.setAttribute('hidden', '');
                content.removeAttribute('hidden');
                return;
            }

            var i18n = cfg.i18n || {};
            var phrase = String(shell.getAttribute('data-zerti-bulk-action-phrase') || i18n.bulkActionSafetyPhrase || 'I understand').trim();
            var mismatchMsg = String(i18n.bulkActionSafetyMismatch || 'Please type the exact phrase to continue.').trim();
            var input = shell.querySelector('[data-zerti-bulk-action-gate-input]');
            var enterBtn = shell.querySelector('[data-zerti-bulk-action-gate-enter]');
            var errorEl = shell.querySelector('[data-zerti-bulk-action-gate-error]');

            function phraseMatches(value) {
                return String(value || '').trim() === phrase;
            }

            function updateEnterState() {
                if (!enterBtn || !input) {
                    return;
                }
                enterBtn.disabled = !phraseMatches(input.value);
            }

            function acknowledge() {
                if (!input || !phraseMatches(input.value)) {
                    if (errorEl) {
                        errorEl.textContent = mismatchMsg;
                        errorEl.removeAttribute('hidden');
                    }
                    if (input) {
                        input.setAttribute('aria-invalid', 'true');
                        input.focus();
                    }
                    return;
                }

                if (errorEl) {
                    errorEl.textContent = '';
                    errorEl.setAttribute('hidden', '');
                }
                if (input) {
                    input.removeAttribute('aria-invalid');
                }
                gate.setAttribute('hidden', '');
                content.removeAttribute('hidden');
            }

            gate.removeAttribute('hidden');
            content.setAttribute('hidden', '');
            if (input) {
                input.value = '';
                input.removeAttribute('aria-invalid');
            }
            if (errorEl) {
                errorEl.textContent = '';
                errorEl.setAttribute('hidden', '');
            }
            updateEnterState();

            if (shell.getAttribute('data-zerti-bulk-gate-bound') === '1') {
                return;
            }
            shell.setAttribute('data-zerti-bulk-gate-bound', '1');

            if (input) {
                input.addEventListener('input', function () {
                    if (errorEl) {
                        errorEl.setAttribute('hidden', '');
                        errorEl.textContent = '';
                    }
                    input.removeAttribute('aria-invalid');
                    updateEnterState();
                });
                input.addEventListener('keydown', function (event) {
                    if (event.key !== 'Enter') {
                        return;
                    }
                    event.preventDefault();
                    if (!enterBtn || !enterBtn.disabled) {
                        acknowledge();
                    }
                });
            }

            if (enterBtn) {
                enterBtn.addEventListener('click', function () {
                    acknowledge();
                });
            }
        }

        function initBulkActionSafetyGate(scope) {
            var root = scope || document;
            var shells = [];

            if (root.matches && root.matches('[data-zerti-bulk-action-shell]')) {
                shells.push(root);
            } else if (root.querySelectorAll) {
                root.querySelectorAll('[data-zerti-bulk-action-shell]').forEach(function (shell) {
                    shells.push(shell);
                });
            }

            shells.forEach(bindBulkActionSafetyGate);
        }

        function initBulkActionTabs(scope) {
            var root = scope || document;
            initBulkActionSafetyGate(root);
            var layout = root.querySelector('.zerti-component-bulk-action .zerti-settings-layout');
            if (!layout) {
                initProFeaturePreview(root);
                if (typeof window.zertiInitBulkPrice === 'function') {
                    window.zertiInitBulkPrice(root);
                }
                if (typeof window.zertiInitBulkStock === 'function') {
                    window.zertiInitBulkStock(root);
                }
                if (typeof window.zertiInitBulkDeleteProducts === 'function') {
                    window.zertiInitBulkDeleteProducts(root);
                }
                if (typeof window.zertiInitBulkDeleteCustomers === 'function') {
                    window.zertiInitBulkDeleteCustomers(root);
                }
                if (typeof window.zertiInitBulkDeleteOrders === 'function') {
                    window.zertiInitBulkDeleteOrders(root);
                }
                return null;
            }

            if (layout.getAttribute('data-zerti-bulk-tabs-bound') !== '1') {
                layout.setAttribute('data-zerti-bulk-tabs-bound', '1');
                layout.querySelectorAll('[data-zerti-bulk-tab]').forEach(function (link) {
                    link.addEventListener('click', function (event) {
                        event.preventDefault();
                        activateBulkActionTab(layout, link.getAttribute('data-zerti-bulk-tab'));
                    });
                });
            }

            initProFeaturePreview(root);

            if (typeof window.zertiInitBulkPrice === 'function') {
                window.zertiInitBulkPrice(root);
            }
            if (typeof window.zertiInitBulkStock === 'function') {
                window.zertiInitBulkStock(root);
            }
            if (typeof window.zertiInitBulkDeleteProducts === 'function') {
                window.zertiInitBulkDeleteProducts(root);
            }
            if (typeof window.zertiInitBulkDeleteCustomers === 'function') {
                window.zertiInitBulkDeleteCustomers(root);
            }
            if (typeof window.zertiInitBulkDeleteOrders === 'function') {
                window.zertiInitBulkDeleteOrders(root);
            }

            return layout;
        }

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

        function getLicenseComponentsCfg() {
            return typeof window.zertiComponents === 'object' && window.zertiComponents !== null
                ? window.zertiComponents
                : cfg;
        }

        function getLicenseProNavTargets() {
            var componentsCfg = getLicenseComponentsCfg();
            return {
                tabs: Array.isArray(componentsCfg.licenseProComponentSlugs)
                    ? componentsCfg.licenseProComponentSlugs.slice()
                    : ['bulk_action'],
                financialSubs: Array.isArray(componentsCfg.licenseProFinancialSubSlugs)
                    ? componentsCfg.licenseProFinancialSubSlugs.slice()
                    : ['reports', 'bi-reports'],
                shopFeatures: Array.isArray(componentsCfg.licenseProShopFeatureSlugs)
                    ? componentsCfg.licenseProShopFeatureSlugs.slice()
                    : ['shop_order_create'],
            };
        }

        function slotHasProGateMarkup(slot) {
            if (!slot) {
                return false;
            }
            return !!(
                slot.querySelector('[data-zerti-pro-preview="1"]') ||
                slot.querySelector('[data-zerti-pro-gate]') ||
                slot.querySelector('.zerti-pro-feature-gate-wrap')
            );
        }

        function proGatedSlotContentMismatch(slot, tabSlug, finSub) {
            if (!slot || slot.getAttribute('data-zerti-loaded') !== '1') {
                return false;
            }
            var isPro = !!getLicenseComponentsCfg().licenseIsPro;
            var gated = slotHasProGateMarkup(slot);
            var targets = getLicenseProNavTargets();

            if (tabSlug && targets.tabs.indexOf(tabSlug) !== -1) {
                if (isPro && gated) {
                    return true;
                }
                if (!isPro && !gated && slot.querySelector('.zerti-component')) {
                    return true;
                }
                return false;
            }

            if (finSub && targets.financialSubs.indexOf(finSub) !== -1) {
                if (isPro && gated) {
                    return true;
                }
                if (!isPro && !gated && slot.querySelector('.zerti-financial-sub-slot')) {
                    return true;
                }
            }

            return false;
        }

        function proGatedShopOrderCreateMismatch(slot) {
            if (!slot || slot.getAttribute('data-zerti-loaded') !== '1') {
                return false;
            }
            var wantShop = shopOrderStateFromUrl();
            if (!wantShop || wantShop.view !== 'create') {
                return false;
            }
            var targets = getLicenseProNavTargets();
            if (targets.shopFeatures.indexOf('shop_order_create') === -1) {
                return false;
            }
            var isPro = !!getLicenseComponentsCfg().licenseIsPro;
            var gated = slotHasProGateMarkup(slot);
            if (isPro && gated) {
                return true;
            }
            if (!isPro && !gated && slot.querySelector('.zerti-shop-order-create[data-zerti-shop-create="1"]')) {
                return true;
            }

            return false;
        }

        function runSequentialReloadJobs(jobs, onComplete) {
            var index = 0;

            function next() {
                if (index >= jobs.length) {
                    if (typeof onComplete === 'function') {
                        onComplete();
                    }
                    return;
                }

                var job = jobs[index];
                index += 1;
                job(next);
            }

            next();
        }

        function reloadLicensedProUi(scope) {
            var searchRoot = scope || root;
            if (!searchRoot || !getLicenseComponentsCfg().licenseIsPro) {
                return;
            }

            var targets = getLicenseProNavTargets();
            var jobs = [];

            targets.tabs.forEach(function (tabSlug) {
                var slot = searchRoot.querySelector('[data-zerti-slot="' + tabSlug + '"]');
                if (!slot || slot.getAttribute('data-zerti-loaded') !== '1') {
                    return;
                }
                jobs.push(function (done) {
                    fetchComponent(tabSlug, slot, searchRoot, done);
                });
            });

            var finSlot = searchRoot.querySelector('[data-zerti-slot="financial"]');
            if (finSlot && finSlot.getAttribute('data-zerti-loaded') === '1') {
                var activeFin = financialSubFromDom(finSlot) || financialSubFromUrl();
                if (activeFin && targets.financialSubs.indexOf(activeFin) !== -1) {
                    jobs.push(function (done) {
                        fetchFinancialPartial(searchRoot, activeFin, finSlot, done);
                    });
                }
            }

            var shopSlot = searchRoot.querySelector('[data-zerti-slot="shop"]');
            if (shopSlot && shopSlot.getAttribute('data-zerti-loaded') === '1') {
                var shopWant = shopOrderStateFromUrl();
                var shopNeedsReload =
                    slotHasProGateMarkup(shopSlot) ||
                    (shopWant && shopWant.view === 'create' && proGatedShopOrderCreateMismatch(shopSlot));
                if (shopNeedsReload) {
                    jobs.push(function (done) {
                        if (shopWant && shopWant.view === 'create') {
                            fetchShopOrderCreatePartial(searchRoot, shopSlot, done);
                            return;
                        }
                        fetchComponent('shop', shopSlot, searchRoot, done);
                    });
                }
            }

            if (!jobs.length) {
                return;
            }

            runSequentialReloadJobs(jobs, function () {
                initDataGridsForRoot(searchRoot);
            });
        }

        function refreshProGatedPanelSlots(isPro, scope) {
            var searchRoot = scope || root;
            if (!searchRoot) {
                return;
            }
            if (isPro) {
                reloadLicensedProUi(searchRoot);
                return;
            }

            var targets = getLicenseProNavTargets();

            targets.tabs.forEach(function (tabSlug) {
                var slot = searchRoot.querySelector('[data-zerti-slot="' + tabSlug + '"]');
                if (!slot || slot.getAttribute('data-zerti-loaded') !== '1') {
                    return;
                }
                if (!slotHasProGateMarkup(slot)) {
                    fetchComponent(tabSlug, slot, searchRoot);
                }
            });

            var finSlot = searchRoot.querySelector('[data-zerti-slot="financial"]');
            if (finSlot && finSlot.getAttribute('data-zerti-loaded') === '1') {
                var activeFin = financialSubFromDom(finSlot);
                if (activeFin && targets.financialSubs.indexOf(activeFin) !== -1 && !slotHasProGateMarkup(finSlot)) {
                    fetchFinancialPartial(searchRoot, activeFin, finSlot);
                }
            }

            var shopSlot = searchRoot.querySelector('[data-zerti-slot="shop"]');
            if (shopSlot && shopSlot.getAttribute('data-zerti-loaded') === '1') {
                var licenseApi = proLicense();
                if (licenseApi && typeof licenseApi.syncShopOrderNewButtonProState === 'function') {
                    licenseApi.syncShopOrderNewButtonProState(isPro, searchRoot);
                }
                var shopWant = shopOrderStateFromUrl();
                if (shopWant && shopWant.view === 'create' && !slotHasProGateMarkup(shopSlot)) {
                    fetchShopOrderCreatePartial(searchRoot, shopSlot);
                }
            }
        }

        function initProFeaturePreview(scope) {
            var api = proLicense();
            if (api && typeof api.initProFeaturePreview === 'function') {
                api.initProFeaturePreview(scope);
            }
        }

        function scheduleSettingsAlerts(container) {
            if (!container) {
                return;
            }

            initSettingsTabs(container);
            initSettingsRegional(container);
            initSettingsThemes(container);
            var licenseApi = proLicense();
            if (licenseApi && typeof licenseApi.scheduleSettingsLicense === 'function') {
                licenseApi.scheduleSettingsLicense(container);
            }

            if (pendingSettingsFocusTab) {
                var focusTabId = pendingSettingsFocusTab;
                pendingSettingsFocusTab = '';
                var focusLayout = container.querySelector('.zerti-settings-layout');
                if (focusLayout) {
                    activateSettingsTab(focusLayout, focusTabId);
                }
            }

            container.querySelectorAll('.zerti-component-settings .alert').forEach(function (alertEl) {
                if (alertEl.getAttribute('data-zerti-alert-dismiss-scheduled') === '1') {
                    return;
                }
                if (
                    alertEl.getAttribute('data-zerti-alert-persist') === '1' ||
                    alertEl.hasAttribute('data-zerti-license-verify-banner')
                ) {
                    return;
                }

                alertEl.setAttribute('data-zerti-alert-dismiss-scheduled', '1');
                window.setTimeout(function () {
                    alertEl.style.transition = 'opacity 0.2s ease';
                    alertEl.style.opacity = '0';
                    window.setTimeout(function () {
                        if (alertEl.parentNode) {
                            alertEl.remove();
                        }
                    }, 220);
                }, 5000);
            });
        }

        function fetchComponent(tab, slot, root, onDone) {
            if (!ajaxUrl || !nonce) {
                slot.innerHTML = errorMarkup();
                slot.setAttribute('data-zerti-fetching', '0');
                if (typeof onDone === 'function') {
                    onDone(false);
                }
                return;
            }

            if (tabFetchAbort) {
                tabFetchAbort.abort();
            }
            tabFetchAbort = new AbortController();
            var signal = tabFetchAbort.signal;

            clearSlotForReload(tab, slot);

            var myGen = String(++fetchGenCounter);
            slot.setAttribute('data-zerti-fetch-gen', myGen);
            slot.setAttribute('data-zerti-fetching', '1');
            slot.setAttribute('aria-busy', 'true');

            var overlay = attachComponentCardLoadOverlay(slot);

            var deferShopOnDone = false;

            var body = new window.FormData();
            body.append('action', action);
            body.append('nonce', nonce);
            body.append('slug', tab);
            if (tab === 'inventory') {
                var invSubFetch = inventorySubFromUrl();
                body.append('inventory_sub', invSubFetch);
                if (invSubFetch === 'warehouse') {
                    var prodFetch = inventoryProductFromUrl();
                    if (prodFetch !== null) {
                        body.append('inventory_product_id', String(prodFetch));
                    }
                }
            }
            if (tab === 'financial') {
                body.append('financial_sub', financialSubFromUrl());
            }

            function isStale() {
                return slot.getAttribute('data-zerti-fetch-gen') !== myGen;
            }

            window
                .fetch(ajaxUrl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: body,
                    signal: signal,
                })
                .then(parseAjaxJson)
                .then(function (data) {
                    if (signal.aborted || isStale()) {
                        return;
                    }
                    if (!data || !data.success || !data.data || typeof data.data.html !== 'string') {
                        throw new Error('bad response');
                    }
                    if (tab === 'shop') {
                        destroyShopOrdersGrid(slot);
                    }
                    if (tab === 'customers') {
                        destroyCustomersGrid(slot);
                    }
                    if (tab === 'financial') {
                        destroyPaymentsGrid(slot);
                        destroySalesReportGrid(slot);
                        destroyCouponsPanel(slot);
                    }
                    if (tab === 'inventory') {
                        destroyProductsGrid(slot);
                    }
                    if (tab === 'reviews' || tab === 'comments') {
                        destroyReviewsGrid(slot);
                    }
                    slot.innerHTML = data.data.html;
                    slot.setAttribute('data-zerti-loaded', '1');
                    slot.classList.remove('zerti-panel-slot--pending');
                    detachComponentCardLoadOverlay(overlay, slot);
                    overlay = null;
                    if (tab === 'settings') {
                        scheduleSettingsAlerts(slot);
                    }
                    if (tab === 'bulk_action') {
                        initBulkActionTabs(slot);
                    }
                    if (tab === 'shop') {
                        var wantShop = shopOrderStateFromUrl();
                        var haveShop = shopOrderStateFromDom(slot);
                        if (wantShop && !shopOrderStatesEqual(wantShop, haveShop)) {
                            deferShopOnDone = true;
                            if (wantShop.view === 'create') {
                                fetchShopOrderCreatePartial(root, slot, function () {
                                    initDataGridsForRoot(root);
                                    if (typeof onDone === 'function') {
                                        onDone(true);
                                    }
                                });
                            } else {
                                fetchShopOrderPartial(root, wantShop.id, wantShop.view, slot, function () {
                                    initDataGridsForRoot(root);
                                    if (typeof onDone === 'function') {
                                        onDone(true);
                                    }
                                });
                            }
                            return;
                        }
                    }
                    if (tab === 'customers') {
                        var pcust = customerDetailFromUrl();
                        var wantCust = pcust ? { id: pcust } : null;
                        var haveCust = customerStateFromDom(slot);
                        if (wantCust && !customerStatesEqual(wantCust, haveCust)) {
                            deferShopOnDone = true;
                            fetchCustomerDetailPartial(root, wantCust.id, slot, function () {
                                initDataGridsForRoot(root);
                                if (typeof onDone === 'function') {
                                    onDone(true);
                                }
                            });
                            return;
                        }
                    }
                    if (tab === 'home') {
                        refreshHomeDashboardStats();
                    }
                    initDataGridsForRoot(root);
                    if (tab === 'shop') {
                        refreshProcessingOrdersBadge();
                    }
                    if (tab === 'reviews' || tab === 'comments') {
                        refreshPendingFeedbackBadges();
                    }
                    if (tab === 'inventory') {
                        var invSubLoaded = inventorySubFromDom(slot) || inventorySubFromUrl();
                        setInventorySubnavActive(root, invSubLoaded);
                        runInventoryCategories(root, invSubLoaded);
                        runInventoryTags(root, invSubLoaded);
                        runInventoryBrands(root, invSubLoaded);
                        runInventoryAttributes(root, invSubLoaded);
                        runInventoryAttributeGroups(root, invSubLoaded);
                        runInventoryImportExport(root, invSubLoaded);
                        if (invSubLoaded === 'warehouse' && inventoryProductStateFromDom(slot)) {
                            runInventoryProductEdit(root, invSubLoaded);
                            if (typeof window.zertiInitDatepickers === 'function') {
                                window.zertiInitDatepickers(slot);
                            }
                        } else {
                            runInventoryProducts(root, invSubLoaded);
                        }
                    }
                    if (tab === 'financial') {
                        var finSubLoaded = financialSubFromDom(slot) || financialSubFromUrl();
                        setFinancialSubnavActive(root, finSubLoaded);
                        runFinancialCoupons(root, finSubLoaded);
                    }
                    if (tab === 'reviews' || tab === 'comments') {
                        runProductFeedbackTab(root, tab);
                    }
                })
                .catch(function (err) {
                    if (signal.aborted || (err && err.name === 'AbortError') || isStale()) {
                        return;
                    }
                    detachComponentCardLoadOverlay(overlay, slot);
                    overlay = null;
                    slot.innerHTML = errorMarkup();
                    slot.querySelectorAll('.zerti-component-retry').forEach(function (btn) {
                        btn.addEventListener('click', function () {
                            fetchComponent(tab, slot, root, onDone);
                        });
                    });
                })
                .finally(function () {
                    if (isStale()) {
                        return;
                    }
                    detachComponentCardLoadOverlay(overlay, slot);
                    overlay = null;
                    if (!deferShopOnDone && typeof onDone === 'function') {
                        onDone(true);
                    }
                });
        }

        function fetchInventoryPartial(root, sub, slot, onDone) {
            if (!ajaxUrl || !nonce) {
                if (typeof onDone === 'function') {
                    onDone(false);
                }
                return;
            }
            if (!slot) {
                if (typeof onDone === 'function') {
                    onDone(false);
                }
                return;
            }

            if (tabFetchAbort) {
                tabFetchAbort.abort();
            }
            tabFetchAbort = new AbortController();
            var signal = tabFetchAbort.signal;

            clearSlotForReload('inventory', slot);

            var myGen = String(++fetchGenCounter);
            slot.setAttribute('data-zerti-inv-fetch-gen', myGen);
            slot.setAttribute('aria-busy', 'true');

            var overlay = attachComponentCardLoadOverlay(slot);

            var body = new window.FormData();
            body.append('action', action);
            body.append('nonce', nonce);
            body.append('slug', 'inventory');
            body.append('partial', '1');
            body.append('inventory_sub', sub);
            if (sub === 'warehouse') {
                var wantProd = inventoryProductFromUrl();
                if (wantProd !== null) {
                    body.append('inventory_product_id', String(wantProd));
                }
            }

            function isStaleInv() {
                return slot.getAttribute('data-zerti-inv-fetch-gen') !== myGen;
            }

            window
                .fetch(ajaxUrl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: body,
                    signal: signal,
                })
                .then(parseAjaxJson)
                .then(function (data) {
                    if (signal.aborted || isStaleInv()) {
                        return;
                    }
                    if (!data || !data.success || !data.data || typeof data.data.html !== 'string') {
                        throw new Error('bad response');
                    }
                    destroyProductsGrid(slot);
                    destroyReviewsGrid(slot);
                    slot.innerHTML = data.data.html;
                    slot.setAttribute('data-zerti-loaded', '1');
                    detachComponentCardLoadOverlay(overlay, slot);
                    overlay = null;
                    setInventorySubnavActive(root, sub);
                    runInventoryCategories(root, sub);
                    runInventoryTags(root, sub);
                    runInventoryBrands(root, sub);
                    runInventoryAttributes(root, sub);
                    runInventoryAttributeGroups(root, sub);
                    runInventoryImportExport(root, sub);
                    if (sub === 'warehouse' && inventoryProductStateFromDom(slot)) {
                        runInventoryProductEdit(root, sub);
                        if (typeof window.zertiInitDatepickers === 'function') {
                            window.zertiInitDatepickers(slot);
                        }
                    } else {
                        runInventoryProducts(root, sub);
                    }
                })
                .catch(function (err) {
                    if (signal.aborted || (err && err.name === 'AbortError') || isStaleInv()) {
                        return;
                    }
                    detachComponentCardLoadOverlay(overlay, slot);
                    overlay = null;
                    slot.innerHTML = errorMarkup();
                    slot.querySelectorAll('.zerti-component-retry').forEach(function (btn) {
                        btn.addEventListener('click', function () {
                            fetchInventoryPartial(root, sub, slot, onDone);
                        });
                    });
                })
                .finally(function () {
                    if (isStaleInv()) {
                        return;
                    }
                    detachComponentCardLoadOverlay(overlay, slot);
                    overlay = null;
                    if (typeof onDone === 'function') {
                        onDone(true);
                    }
                });
        }

        function fetchInventoryProductPartial(root, productId, slot, onDone) {
            fetchInventoryPartial(root, 'warehouse', slot, onDone);
        }

        function fetchFinancialPartial(root, sub, slot, onDone) {
            if (!ajaxUrl || !nonce) {
                if (typeof onDone === 'function') {
                    onDone(false);
                }
                return;
            }
            if (!slot) {
                if (typeof onDone === 'function') {
                    onDone(false);
                }
                return;
            }

            if (tabFetchAbort) {
                tabFetchAbort.abort();
            }
            tabFetchAbort = new AbortController();
            var signal = tabFetchAbort.signal;

            clearSlotForReload('financial', slot);

            var myGenFin = String(++fetchGenCounter);
            slot.setAttribute('data-zerti-fin-fetch-gen', myGenFin);
            slot.setAttribute('aria-busy', 'true');

            var overlayFin = attachComponentCardLoadOverlay(slot);

            var bodyFin = new window.FormData();
            bodyFin.append('action', action);
            bodyFin.append('nonce', nonce);
            bodyFin.append('slug', 'financial');
            bodyFin.append('partial', '1');
            bodyFin.append('financial_sub', sub);

            function isStaleFin() {
                return slot.getAttribute('data-zerti-fin-fetch-gen') !== myGenFin;
            }

            window
                .fetch(ajaxUrl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: bodyFin,
                    signal: signal,
                })
                .then(parseAjaxJson)
                .then(function (data) {
                    if (signal.aborted || isStaleFin()) {
                        return;
                    }
                    if (!data || !data.success || !data.data || typeof data.data.html !== 'string') {
                        throw new Error('bad response');
                    }
                    destroyPaymentsGrid(slot);
                    destroySalesReportGrid(slot);
                    destroyCouponsPanel(slot);
                    slot.innerHTML = data.data.html;
                    slot.setAttribute('data-zerti-loaded', '1');
                    detachComponentCardLoadOverlay(overlayFin, slot);
                    overlayFin = null;
                    setFinancialSubnavActive(root, sub);
                    ensureBundlesForTab('financial', function () {
                        initDataGridsForRoot(root);
                        runFinancialCoupons(root, sub);
                    });
                })
                .catch(function (err) {
                    if (signal.aborted || (err && err.name === 'AbortError') || isStaleFin()) {
                        return;
                    }
                    slot.innerHTML = errorMarkup();
                    slot.querySelectorAll('.zerti-component-retry').forEach(function (btn) {
                        btn.addEventListener('click', function () {
                            fetchFinancialPartial(root, sub, slot, onDone);
                        });
                    });
                })
                .finally(function () {
                    if (isStaleFin()) {
                        return;
                    }
                    detachComponentCardLoadOverlay(overlayFin, slot);
                    overlayFin = null;
                    if (typeof onDone === 'function') {
                        onDone(true);
                    }
                });
        }

        function destroyShopOrdersGrid(slot) {
            if (!slot) {
                return;
            }
            var oldShopGrid = slot.querySelector('#zertiShopOrdersGrid');
            if (
                oldShopGrid &&
                oldShopGrid.__zertiAgGridApi &&
                typeof oldShopGrid.__zertiAgGridApi.destroy === 'function'
            ) {
                if (typeof oldShopGrid.__zertiAgGridCleanup === 'function') {
                    oldShopGrid.__zertiAgGridCleanup();
                    oldShopGrid.__zertiAgGridCleanup = null;
                }
                oldShopGrid.__zertiAgGridApi.destroy();
                oldShopGrid.__zertiAgGridApi = null;
            }
        }

        function fetchCustomerDetailPartial(root, customerId, slot, onDone) {
            if (!ajaxUrl || !nonce) {
                if (typeof onDone === 'function') {
                    onDone(false);
                }
                return;
            }
            if (!slot || !(customerId > 0)) {
                if (typeof onDone === 'function') {
                    onDone(false);
                }
                return;
            }

            if (tabFetchAbort) {
                tabFetchAbort.abort();
            }
            tabFetchAbort = new AbortController();
            var signalCust = tabFetchAbort.signal;

            var myGenCust = String(++fetchGenCounter);
            slot.setAttribute('data-zerti-customer-fetch-gen', myGenCust);
            slot.setAttribute('aria-busy', 'true');

            clearSlotForReload('customers', slot);

            var overlayCust = attachComponentCardLoadOverlay(slot);

            var bodyCust = new window.FormData();
            bodyCust.append('action', action);
            bodyCust.append('nonce', nonce);
            bodyCust.append('slug', 'customers');
            bodyCust.append('partial', '1');
            bodyCust.append('customer_id', String(customerId));

            function isStaleCust() {
                return slot.getAttribute('data-zerti-customer-fetch-gen') !== myGenCust;
            }

            window
                .fetch(ajaxUrl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: bodyCust,
                    signal: signalCust,
                })
                .then(parseAjaxJson)
                .then(function (data) {
                    if (signalCust.aborted || isStaleCust()) {
                        return;
                    }
                    if (!data || !data.success || !data.data || typeof data.data.html !== 'string') {
                        throw new Error('bad response');
                    }
                    slot.innerHTML = data.data.html;
                    slot.setAttribute('data-zerti-loaded', '1');
                    detachComponentCardLoadOverlay(overlayCust, slot);
                    overlayCust = null;
                })
                .catch(function (errCust) {
                    if (signalCust.aborted || (errCust && errCust.name === 'AbortError') || isStaleCust()) {
                        return;
                    }
                    slot.innerHTML = errorMarkup();
                    slot.querySelectorAll('.zerti-component-retry').forEach(function (btn) {
                        btn.addEventListener('click', function () {
                            fetchCustomerDetailPartial(root, customerId, slot, onDone);
                        });
                    });
                })
                .finally(function () {
                    if (isStaleCust()) {
                        return;
                    }
                    detachComponentCardLoadOverlay(overlayCust, slot);
                    overlayCust = null;
                    if (typeof onDone === 'function') {
                        onDone(true);
                    }
                });
        }

        function destroyCustomersGrid(slot) {
            if (!slot) {
                return;
            }
            var oldCustomersGrid = slot.querySelector('#zertiCustomersGrid');
            if (
                oldCustomersGrid &&
                oldCustomersGrid.__zertiAgGridApi &&
                typeof oldCustomersGrid.__zertiAgGridApi.destroy === 'function'
            ) {
                if (typeof oldCustomersGrid.__zertiAgGridCleanup === 'function') {
                    oldCustomersGrid.__zertiAgGridCleanup();
                    oldCustomersGrid.__zertiAgGridCleanup = null;
                }
                oldCustomersGrid.__zertiAgGridApi.destroy();
                oldCustomersGrid.__zertiAgGridApi = null;
            }
        }

        function destroyCouponsPanel(slot) {
            if (!slot) {
                return;
            }
            var couponsRoot = slot.querySelector('[data-zerti-coupons-root="1"]');
            if (couponsRoot && typeof couponsRoot.__zertiCouponsPanelCleanup === 'function') {
                couponsRoot.__zertiCouponsPanelCleanup();
                couponsRoot.__zertiCouponsPanelCleanup = null;
            }
            var oldCouponsGrid = slot.querySelector('#zertiCouponsGrid');
            if (
                oldCouponsGrid &&
                oldCouponsGrid.__zertiAgGridApi &&
                typeof oldCouponsGrid.__zertiAgGridApi.destroy === 'function'
            ) {
                if (typeof oldCouponsGrid.__zertiAgGridCleanup === 'function') {
                    oldCouponsGrid.__zertiAgGridCleanup();
                    oldCouponsGrid.__zertiAgGridCleanup = null;
                }
                oldCouponsGrid.__zertiAgGridApi.destroy();
                oldCouponsGrid.__zertiAgGridApi = null;
            }
        }

        function destroyPaymentsGrid(slot) {
            if (!slot) {
                return;
            }
            var oldPaymentsGrid = slot.querySelector('#zertiPaymentsGrid');
            if (
                oldPaymentsGrid &&
                oldPaymentsGrid.__zertiAgGridApi &&
                typeof oldPaymentsGrid.__zertiAgGridApi.destroy === 'function'
            ) {
                if (typeof oldPaymentsGrid.__zertiAgGridCleanup === 'function') {
                    oldPaymentsGrid.__zertiAgGridCleanup();
                    oldPaymentsGrid.__zertiAgGridCleanup = null;
                }
                oldPaymentsGrid.__zertiAgGridApi.destroy();
                oldPaymentsGrid.__zertiAgGridApi = null;
            }
        }

        function destroySalesReportGrid(slot) {
            if (!slot) {
                return;
            }
            var oldSalesGrid = slot.querySelector('#zertiSalesReportGrid');
            if (
                oldSalesGrid &&
                oldSalesGrid.__zertiAgGridApi &&
                typeof oldSalesGrid.__zertiAgGridApi.destroy === 'function'
            ) {
                if (typeof oldSalesGrid.__zertiAgGridCleanup === 'function') {
                    oldSalesGrid.__zertiAgGridCleanup();
                    oldSalesGrid.__zertiAgGridCleanup = null;
                }
                oldSalesGrid.__zertiAgGridApi.destroy();
                oldSalesGrid.__zertiAgGridApi = null;
            }
        }

        function destroyProductsGrid(slot) {
            if (!slot) {
                return;
            }
            var oldProductsGrid = slot.querySelector('#zertiProductsGrid');
            if (
                oldProductsGrid &&
                oldProductsGrid.__zertiAgGridApi &&
                typeof oldProductsGrid.__zertiAgGridApi.destroy === 'function'
            ) {
                if (typeof oldProductsGrid.__zertiAgGridCleanup === 'function') {
                    oldProductsGrid.__zertiAgGridCleanup();
                    oldProductsGrid.__zertiAgGridCleanup = null;
                }
                oldProductsGrid.__zertiAgGridApi.destroy();
                oldProductsGrid.__zertiAgGridApi = null;
            }
        }

        function destroyReviewsGrid(slot) {
            if (!slot) {
                return;
            }
            if (typeof window.zertiDestroyReviewsGrid === 'function') {
                window.zertiDestroyReviewsGrid(slot);
            }
        }

        /** True when cached slot HTML does not match the current URL route (menu always opens root). */
        function tabSlotNeedsReload(tab, slot) {
            if (!slot || slot.getAttribute('data-zerti-loaded') !== '1') {
                return false;
            }

            if (tab === 'inventory') {
                var wantInv = inventorySubFromUrl();
                var haveInv = inventorySubFromDom(slot);
                var wantProd = wantInv === 'warehouse' ? inventoryProductFromUrl() : null;
                var wantProdState = wantProd !== null ? { id: wantProd } : null;
                var haveProdState = wantInv === 'warehouse' ? inventoryProductStateFromDom(slot) : null;
                if (haveInv !== null && haveInv !== wantInv) {
                    return true;
                }
                if (wantInv === 'warehouse' && !inventoryProductStatesEqual(wantProdState, haveProdState)) {
                    return true;
                }
                return false;
            }

            if (tab === 'financial') {
                var wantFin = financialSubFromUrl();
                var haveFin = financialSubFromDom(slot);
                if (haveFin !== null && haveFin !== wantFin) {
                    return true;
                }
                var finSubCheck = haveFin !== null ? haveFin : wantFin;
                return proGatedSlotContentMismatch(slot, null, finSubCheck);
            }

            if (tab === 'shop') {
                if (proGatedShopOrderCreateMismatch(slot)) {
                    return true;
                }
                var wantShopState = shopOrderStateFromUrl();
                var haveShopState = shopOrderStateFromDom(slot);
                return !shopOrderStatesEqual(wantShopState, haveShopState);
            }

            if (tab === 'customers') {
                var wantCustId = customerDetailFromUrl();
                var wantCustState = wantCustId ? { id: wantCustId } : null;
                var haveCustState = customerStateFromDom(slot);
                return !customerStatesEqual(wantCustState, haveCustState);
            }

            if (tab === 'bulk_action') {
                return proGatedSlotContentMismatch(slot, 'bulk_action');
            }

            return false;
        }

        function clearSlotForReload(tab, slot) {
            if (!slot) {
                return;
            }
            if (tab === 'shop') {
                destroyShopOrdersGrid(slot);
            }
            if (tab === 'customers') {
                destroyCustomersGrid(slot);
            }
            if (tab === 'financial') {
                destroyPaymentsGrid(slot);
                destroySalesReportGrid(slot);
                destroyCouponsPanel(slot);
            }
            if (tab === 'inventory' || tab === 'reviews' || tab === 'comments') {
                destroyProductsGrid(slot);
                destroyReviewsGrid(slot);
            }
            slot.innerHTML = '';
            slot.removeAttribute('data-zerti-loaded');
            slot.removeAttribute('data-zerti-fetching');
            slot.removeAttribute('aria-busy');
        }

        function initDataGridsForRoot(root) {
            if (typeof window.zertiInitDatepickers === 'function') {
                window.zertiInitDatepickers(root);
            } else if (typeof window.zertiInitJalaliDatepickers === 'function') {
                window.zertiInitJalaliDatepickers(root);
            }
            if (typeof window.zertiInitShopOrdersTable === 'function') {
                window.zertiInitShopOrdersTable(root);
            }
            if (typeof window.zertiInitCustomersTable === 'function') {
                window.zertiInitCustomersTable(root);
            }
            if (typeof window.zertiInitPaymentsTable === 'function') {
                window.zertiInitPaymentsTable(root);
            }
            if (typeof window.zertiInitSalesReportTable === 'function') {
                window.zertiInitSalesReportTable(root);
            }
            if (typeof window.zertiInitStandardReportsTable === 'function') {
                window.zertiInitStandardReportsTable(root);
            }
            if (typeof window.zertiInitBiReportsTable === 'function') {
                window.zertiInitBiReportsTable(root);
            }
            runShopOrderCreate(root);
            initProFeaturePreview(root);
        }

        function runShopOrderCreate(root) {
            if (!root || !root.querySelector('.zerti-shop-order-create[data-zerti-shop-create="1"]')) {
                return;
            }

            function tryInitCreate(attempt) {
                if (typeof window.zertiInitShopOrderCreate === 'function') {
                    try {
                        window.zertiInitShopOrderCreate(root);
                    } catch (eCreate) {
                        /* Create form init must not break the shop panel. */
                    }
                    return;
                }
                if (attempt < 50) {
                    window.requestAnimationFrame(function () {
                        tryInitCreate(attempt + 1);
                    });
                    return;
                }
                ensureBundlesForTab('shop', function () {
                    tryInitCreate(0);
                });
            }

            tryInitCreate(0);
        }

        function fetchShopOrderCreatePartial(root, slot, onDone) {
            if (!ajaxUrl || !nonce) {
                if (typeof onDone === 'function') {
                    onDone(false);
                }
                return;
            }
            if (!slot) {
                if (typeof onDone === 'function') {
                    onDone(false);
                }
                return;
            }

            if (tabFetchAbort) {
                tabFetchAbort.abort();
            }
            tabFetchAbort = new AbortController();
            var signalCreate = tabFetchAbort.signal;

            var myGenCreate = String(++fetchGenCounter);
            slot.setAttribute('data-zerti-shop-fetch-gen', myGenCreate);
            slot.setAttribute('aria-busy', 'true');

            clearSlotForReload('shop', slot);

            var overlayCreate = attachComponentCardLoadOverlay(slot);

            var bodyCreate = new window.FormData();
            bodyCreate.append('action', action);
            bodyCreate.append('nonce', nonce);
            bodyCreate.append('slug', 'shop');
            bodyCreate.append('partial', '1');
            bodyCreate.append('shop_order_id', '0');
            bodyCreate.append('shop_order_create', '1');

            function isStaleCreate() {
                return slot.getAttribute('data-zerti-shop-fetch-gen') !== myGenCreate;
            }

            window
                .fetch(ajaxUrl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: bodyCreate,
                    signal: signalCreate,
                })
                .then(parseAjaxJson)
                .then(function (data) {
                    if (signalCreate.aborted || isStaleCreate()) {
                        return;
                    }
                    if (!data || !data.success || !data.data || typeof data.data.html !== 'string') {
                        throw new Error('bad response');
                    }
                    slot.innerHTML = data.data.html;
                    slot.setAttribute('data-zerti-loaded', '1');
                    detachComponentCardLoadOverlay(overlayCreate, slot);
                    overlayCreate = null;
                    runShopOrderCreate(root);
                    initProFeaturePreview(root);
                })
                .catch(function (errCreate) {
                    if (signalCreate.aborted || (errCreate && errCreate.name === 'AbortError') || isStaleCreate()) {
                        return;
                    }
                    slot.innerHTML = errorMarkup();
                    slot.querySelectorAll('.zerti-component-retry').forEach(function (btn) {
                        btn.addEventListener('click', function () {
                            fetchShopOrderCreatePartial(root, slot, onDone);
                        });
                    });
                })
                .finally(function () {
                    if (isStaleCreate()) {
                        return;
                    }
                    detachComponentCardLoadOverlay(overlayCreate, slot);
                    overlayCreate = null;
                    if (typeof onDone === 'function') {
                        onDone(true);
                    }
                });
        }

        function fetchShopOrderPartial(root, orderId, view, slot, onDone) {
            if (!ajaxUrl || !nonce) {
                if (typeof onDone === 'function') {
                    onDone(false);
                }
                return;
            }
            if (!slot || !(orderId > 0)) {
                if (typeof onDone === 'function') {
                    onDone(false);
                }
                return;
            }

            if (tabFetchAbort) {
                tabFetchAbort.abort();
            }
            tabFetchAbort = new AbortController();
            var signalShop = tabFetchAbort.signal;

            var myGenShop = String(++fetchGenCounter);
            slot.setAttribute('data-zerti-shop-fetch-gen', myGenShop);
            slot.setAttribute('aria-busy', 'true');

            clearSlotForReload('shop', slot);

            var overlayShop = attachComponentCardLoadOverlay(slot);

            var bodyShop = new window.FormData();
            bodyShop.append('action', action);
            bodyShop.append('nonce', nonce);
            bodyShop.append('slug', 'shop');
            bodyShop.append('partial', '1');
            bodyShop.append('shop_order_id', String(orderId));
            bodyShop.append('shop_order_view', view === 'invoice' ? 'invoice' : 'detail');

            function isStaleShop() {
                return slot.getAttribute('data-zerti-shop-fetch-gen') !== myGenShop;
            }

            window
                .fetch(ajaxUrl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: bodyShop,
                    signal: signalShop,
                })
                .then(parseAjaxJson)
                .then(function (data) {
                    if (signalShop.aborted || isStaleShop()) {
                        return;
                    }
                    if (!data || !data.success || !data.data || typeof data.data.html !== 'string') {
                        throw new Error('bad response');
                    }
                    slot.innerHTML = data.data.html;
                    slot.setAttribute('data-zerti-loaded', '1');
                    detachComponentCardLoadOverlay(overlayShop, slot);
                    overlayShop = null;
                })
                .catch(function (errShop) {
                    if (signalShop.aborted || (errShop && errShop.name === 'AbortError') || isStaleShop()) {
                        return;
                    }
                    slot.innerHTML = errorMarkup();
                    slot.querySelectorAll('.zerti-component-retry').forEach(function (btn) {
                        btn.addEventListener('click', function () {
                            fetchShopOrderPartial(root, orderId, view, slot, onDone);
                        });
                    });
                })
                .finally(function () {
                    if (isStaleShop()) {
                        return;
                    }
                    detachComponentCardLoadOverlay(overlayShop, slot);
                    overlayShop = null;
                    if (typeof onDone === 'function') {
                        onDone(true);
                    }
                });
        }

        function ensureTabContent(tab, root, onDone) {
            if (allowed.indexOf(tab) === -1) {
                tab = 'home';
            }
            var slot = root.querySelector('[data-zerti-slot="' + tab + '"]');
            if (!slot) {
                if (typeof onDone === 'function') {
                    onDone(true);
                }
                return;
            }

            if (tabSlotNeedsReload(tab, slot)) {
                allowInitialSsrSkip = false;
                if (tab === 'inventory') {
                    fetchInventoryPartial(root, inventorySubFromUrl(), slot, onDone);
                    return;
                }
                if (tab === 'financial') {
                    fetchFinancialPartial(root, financialSubFromUrl(), slot, onDone);
                    return;
                }
                if (tab === 'shop') {
                    var wantShopReload = shopOrderStateFromUrl();
                    if (wantShopReload && wantShopReload.view === 'create') {
                        fetchShopOrderCreatePartial(root, slot, onDone);
                    } else if (wantShopReload) {
                        fetchShopOrderPartial(root, wantShopReload.id, wantShopReload.view, slot, onDone);
                    } else {
                        fetchComponent('shop', slot, root, onDone);
                    }
                    return;
                }
                if (tab === 'customers') {
                    var wantCustReload = customerDetailFromUrl();
                    if (wantCustReload) {
                        fetchCustomerDetailPartial(root, wantCustReload, slot, onDone);
                    } else {
                        fetchComponent('customers', slot, root, onDone);
                    }
                    return;
                }
                if (tab === 'bulk_action') {
                    fetchComponent(tab, slot, root, onDone);
                    return;
                }
            }

            if (tab === 'settings' && slot.getAttribute('data-zerti-loaded') === '1') {
                scheduleSettingsAlerts(slot);
                if (typeof onDone === 'function') {
                    onDone(true);
                }
                return;
            }

            if (tab === 'bulk_action' && slot.getAttribute('data-zerti-loaded') === '1') {
                initBulkActionTabs(slot);
                if (typeof onDone === 'function') {
                    onDone(true);
                }
                return;
            }

            if (tab === 'home' && slot.getAttribute('data-zerti-loaded') === '1') {
                if (slot.querySelector('.zerti-component-home--loading')) {
                    refreshHomeDashboardStats();
                } else {
                    runHomeRevenueChart(root);
                }
                if (typeof onDone === 'function') {
                    onDone(true);
                }
                return;
            }

            if (allowInitialSsrSkip && slot.getAttribute('data-zerti-loaded') === '1') {
                allowInitialSsrSkip = false;
                if (initialTab === 'home') {
                    refreshHomeDashboardStats();
                }
                initDataGridsForRoot(root);
                if (initialTab === 'inventory') {
                    var invSubInitial = inventorySubFromUrl();
                    var invSlotInitial = root.querySelector('[data-zerti-slot="inventory"]');
                    runInventoryCategories(root, invSubInitial);
                    runInventoryTags(root, invSubInitial);
                    runInventoryBrands(root, invSubInitial);
                    runInventoryAttributes(root, invSubInitial);
                    runInventoryAttributeGroups(root, invSubInitial);
                    runInventoryImportExport(root, invSubInitial);
                    if (invSubInitial === 'warehouse' && inventoryProductStateFromDom(invSlotInitial)) {
                        runInventoryProductEdit(root, invSubInitial);
                        if (typeof window.zertiInitDatepickers === 'function') {
                            window.zertiInitDatepickers(invSlotInitial);
                        }
                    } else {
                        runInventoryProducts(root, invSubInitial);
                    }
                }
                if (initialTab === 'reviews' || initialTab === 'comments') {
                    runProductFeedbackTab(root, initialTab);
                }
                if (initialTab === 'financial') {
                    runFinancialCoupons(root, financialSubFromUrl());
                }
                if (initialTab === 'settings') {
                    scheduleSettingsAlerts(slot);
                }
                if (initialTab === 'bulk_action') {
                    initBulkActionTabs(slot);
                }
                if (typeof onDone === 'function') {
                    onDone(true);
                }
                return;
            }
            allowInitialSsrSkip = false;

            fetchComponent(tab, slot, root, onDone);
        }

        function setTab(tab, skipUrl) {
            if (allowed.indexOf(tab) === -1) {
                tab = 'home';
            }
            closeMobileSidebar();
            if (tab === 'home') {
                setTabInner(tab, skipUrl);
                ensureBundlesForTab('home', function () {
                    var homeSlot = root.querySelector('[data-zerti-slot="home"]');
                    if (!homeSlot || homeSlot.getAttribute('data-zerti-loaded') !== '1') {
                        return;
                    }
                    if (homeSlot.querySelector('.zerti-component-home--loading')) {
                        return;
                    }
                    var chartHost = homeSlot.querySelector('[data-zerti-revenue-json]');
                    var chartJson = chartHost ? chartHost.getAttribute('data-zerti-revenue-json') : '';
                    if (chartJson) {
                        runHomeRevenueChart(root);
                    }
                });
                return;
            }
            ensureBundlesForTab(tab, function () {
                setTabInner(tab, skipUrl);
            });
        }

        function setTabInner(tab, skipUrl) {
            if (tab === 'inventory') {
                setInventorySubmenuExpanded(root, true);
            } else {
                setInventorySubmenuExpanded(root, false);
            }
            var finSub = tab === 'financial' ? financialSubFromUrl() : '';
            syncFinancialNavState(root, tab, finSub);
            if (isCustomerRelationsPanelTab(tab)) {
                setCustomerRelationsSubmenuExpanded(root, true);
            } else {
                setCustomerRelationsSubmenuExpanded(root, false);
            }
            root.querySelectorAll('[data-zerti-panel]').forEach(function (panel) {
                var on = panel.getAttribute('data-zerti-panel') === tab;
                if (on) {
                    panel.removeAttribute('hidden');
                } else {
                    panel.setAttribute('hidden', '');
                }
            });
            root.querySelectorAll('.zerti-nav-tab').forEach(function (btn) {
                var navTab = btn.getAttribute('data-zerti-tab') || '';
                var on =
                    (navTab === tab && navTab !== 'financial' && navTab !== 'reports') ||
                    (navTab === 'financial' && tab === 'financial' && !isReportsNavActive(tab, finSub)) ||
                    (navTab === 'reports' && isReportsNavActive(tab, finSub)) ||
                    (navTab === 'customer_relations' && isCustomerRelationsPanelTab(tab));
                btn.classList.toggle('active', on);
                btn.setAttribute('aria-selected', on ? 'true' : 'false');
            });
            if (tab === 'inventory') {
                setInventorySubnavActive(root, inventorySubFromUrl());
            } else {
                setInventorySubnavActive(root, null);
            }
            if (isCustomerRelationsPanelTab(tab)) {
                setCustomerRelationsSubnavActive(root, tab);
            } else {
                setCustomerRelationsSubnavActive(root, null);
            }
            var slot = root.querySelector('[data-zerti-slot="' + tab + '"]');
            if (slot && tabSlotNeedsReload(tab, slot)) {
                clearSlotForReload(tab, slot);
            }
            if (slot) {
                slot.scrollTop = 0;
            }
            updatePanelTitle(root, tab);
            ensureTabContent(tab, root, function () {
                if (!skipUrl) {
                    syncUrl(tab, root, true);
                }
                updatePanelTitle(root, tab);
            });
        }

        root.querySelectorAll('.zerti-nav-tab').forEach(function (btn) {
            btn.addEventListener('click', function (e) {
                var tab = btn.getAttribute('data-zerti-tab') || 'home';
                if (tab === 'inventory') {
                    if (!handleInAppControl(e, btn)) {
                        return;
                    }
                    var invWrap = root.querySelector('.zerti-inv-submenu-wrap');
                    var invOpen = invWrap && !invWrap.hasAttribute('hidden');
                    setFinancialSubmenuExpanded(root, false);
                    setReportsSubmenuExpanded(root, false);
                    setCustomerRelationsSubmenuExpanded(root, false);
                    setInventorySubmenuExpanded(root, !invOpen);
                    return;
                }
                if (tab === 'financial') {
                    if (!handleInAppControl(e, btn)) {
                        return;
                    }
                    var finWrap = root.querySelector('.zerti-fin-submenu-wrap');
                    var finOpen = finWrap && !finWrap.hasAttribute('hidden');
                    setInventorySubmenuExpanded(root, false);
                    setCustomerRelationsSubmenuExpanded(root, false);
                    setReportsSubmenuExpanded(root, false);
                    setFinancialSubmenuExpanded(root, !finOpen);
                    return;
                }
                if (tab === 'reports') {
                    e.preventDefault();
                    var reportsWrap = root.querySelector('.zerti-reports-submenu-wrap');
                    var reportsOpen = reportsWrap && !reportsWrap.hasAttribute('hidden');
                    setInventorySubmenuExpanded(root, false);
                    setFinancialSubmenuExpanded(root, false);
                    setCustomerRelationsSubmenuExpanded(root, false);
                    setReportsSubmenuExpanded(root, !reportsOpen);
                    return;
                }
                if (tab === 'customer_relations') {
                    e.preventDefault();
                    var crmWrap = root.querySelector('.zerti-crm-submenu-wrap');
                    var crmOpen = crmWrap && !crmWrap.hasAttribute('hidden');
                    setInventorySubmenuExpanded(root, false);
                    setFinancialSubmenuExpanded(root, false);
                    setReportsSubmenuExpanded(root, false);
                    setCustomerRelationsSubmenuExpanded(root, !crmOpen);
                    return;
                }
                if (shouldInterceptAdminLink(e, btn)) {
                    e.preventDefault();
                    var topRoute = routeFromNavElement(btn);
                    if (topRoute) {
                        pushRoute(topRoute);
                    }
                    setTab(tab, true);
                    return;
                }
            });
        });

        root.addEventListener('click', function (e) {
            var getProShopBtn =
                e.target && e.target.closest
                    ? e.target.closest(
                          '.zerti-get-pro-btn[data-zerti-get-pro-action="shop"], [data-zerti-edition-footer][data-zerti-edition-state="shop"] .zerti-get-pro-btn'
                      )
                    : null;
            if (getProShopBtn && root.contains(getProShopBtn)) {
                var shopUrl = getProShopBtn.getAttribute('href') || 'https://zerti.shop';
                if (shopUrl.indexOf('http') === 0) {
                    e.preventDefault();
                    window.open(shopUrl, '_blank', 'noopener,noreferrer');
                    return;
                }
            }

            var licenseApi = proLicense();
            if (licenseApi) {
                if (typeof licenseApi.handleLicenseAlertCloseClick === 'function' && licenseApi.handleLicenseAlertCloseClick(e)) {
                    return;
                }

                if (typeof licenseApi.handleLicenseRetryVerifyClick === 'function' && licenseApi.handleLicenseRetryVerifyClick(e)) {
                    return;
                }

                if (typeof licenseApi.handleSettingsLicenseActivateClick === 'function' && licenseApi.handleSettingsLicenseActivateClick(e)) {
                    return;
                }
            }

            var settingsFocusLink =
                e.target && e.target.closest
                    ? e.target.closest('[data-zerti-tab="settings"][data-zerti-settings-focus]')
                    : null;
            if (settingsFocusLink && root.contains(settingsFocusLink)) {
                if (!handleInAppControl(e, settingsFocusLink)) {
                    return;
                }
                e.preventDefault();
                openLicenseSettingsTab(settingsFocusLink.getAttribute('data-zerti-settings-focus') || 'license');
                return;
            }

            var homeShopStat = e.target && e.target.closest ? e.target.closest('.zerti-home-stat-card--link[data-zerti-tab="shop"]') : null;
            if (homeShopStat && root.contains(homeShopStat)) {
                if (!handleInAppControl(e, homeShopStat)) {
                    return;
                }
                var homeRoute = routeFromNavElement(homeShopStat) || { tab: 'shop' };
                pushRoute(homeRoute);
                setTab('shop', true);
                return;
            }

            var homeInvStat =
                e.target && e.target.closest
                    ? e.target.closest('.zerti-home-stat-card--link[data-zerti-tab="inventory"]')
                    : null;
            if (homeInvStat && root.contains(homeInvStat)) {
                if (!handleInAppControl(e, homeInvStat)) {
                    return;
                }
                var homeInvRoute = routeFromNavElement(homeInvStat) || { tab: 'inventory', inv: 'warehouse' };
                if (!homeInvRoute.inv) {
                    homeInvRoute.inv = 'warehouse';
                }
                pushRoute(homeInvRoute);
                setTab('inventory', true);
                return;
            }

            var homeFinStat =
                e.target && e.target.closest
                    ? e.target.closest('.zerti-home-stat-card--link[data-zerti-tab="financial"]')
                    : null;
            if (homeFinStat && root.contains(homeFinStat)) {
                if (!handleInAppControl(e, homeFinStat)) {
                    return;
                }
                var homeFinRoute = routeFromNavElement(homeFinStat) || { tab: 'financial', fin: 'payments' };
                if (!homeFinRoute.fin) {
                    homeFinRoute.fin = 'payments';
                }
                pushRoute(homeFinRoute);
                setTab('financial', true);
                return;
            }

            var backShop = e.target && e.target.closest ? e.target.closest('.zerti-shop-order-back') : null;
            if (backShop && root.contains(backShop)) {
                if (shouldInterceptAdminLink(e, backShop)) {
                    e.preventDefault();
                } else {
                    return;
                }
                var returnFinancial = window.__zertiShopOrderReturnScope === 'financial';
                setShopOrderUrl(0, 'detail');
                window.__zertiShopOrderReturnScope = null;
                if (returnFinancial) {
                    var finSlotBack = root.querySelector('[data-zerti-slot="financial"]');
                    if (finSlotBack && finSlotBack.getAttribute('data-zerti-loaded') === '1') {
                        fetchFinancialPartial(root, finDefault, finSlotBack, function () {
                            syncUrl('financial', root, false);
                        });
                    } else {
                        setTab('financial', true);
                    }
                } else {
                    var shopSlotBack = root.querySelector('[data-zerti-slot="shop"]');
                    if (shopSlotBack && shopSlotBack.getAttribute('data-zerti-loaded') === '1') {
                        fetchComponent('shop', shopSlotBack, root, function () {
                            syncUrl('shop', root, false);
                        });
                    }
                }
                return;
            }

            var backShopDetail = e.target && e.target.closest ? e.target.closest('.zerti-shop-order-back-detail[data-zerti-order-id]') : null;
            if (backShopDetail && root.contains(backShopDetail)) {
                if (shouldInterceptAdminLink(e, backShopDetail)) {
                    e.preventDefault();
                } else {
                    return;
                }
                var oidBackDetail = parseInt(backShopDetail.getAttribute('data-zerti-order-id') || '', 10);
                if (!(oidBackDetail > 0)) {
                    return;
                }
                setShopOrderUrl(oidBackDetail, 'detail');
                var shopSlotBackDetail = root.querySelector('[data-zerti-slot="shop"]');
                var activeNavBackDetail = root.querySelector('.zerti-nav-tab.active');
                var activeTabBackDetail = activeNavBackDetail ? activeNavBackDetail.getAttribute('data-zerti-tab') : '';
                if (activeTabBackDetail === 'shop' && shopSlotBackDetail && shopSlotBackDetail.getAttribute('data-zerti-loaded') === '1') {
                    fetchShopOrderPartial(root, oidBackDetail, 'detail', shopSlotBackDetail, function () {
                        syncUrl('shop', root, false);
                    });
                } else {
                    setTab('shop', true);
                }
                return;
            }

            var invoiceShop = e.target && e.target.closest ? e.target.closest('.zerti-shop-order-invoice-btn[data-zerti-order-id]') : null;
            if (invoiceShop && root.contains(invoiceShop)) {
                if (invoiceShop.classList && invoiceShop.classList.contains('disabled')) {
                    e.preventDefault();
                    return;
                }
                if (shouldInterceptAdminLink(e, invoiceShop)) {
                    e.preventDefault();
                } else {
                    return;
                }
                var oidInvoice = parseInt(invoiceShop.getAttribute('data-zerti-order-id') || '', 10);
                if (!(oidInvoice > 0)) {
                    return;
                }
                setShopOrderUrl(oidInvoice, 'invoice');
                var shopSlotInvoice = root.querySelector('[data-zerti-slot="shop"]');
                var activeNavInvoice = root.querySelector('.zerti-nav-tab.active');
                var activeTabInvoice = activeNavInvoice ? activeNavInvoice.getAttribute('data-zerti-tab') : '';
                if (activeTabInvoice === 'shop' && shopSlotInvoice && shopSlotInvoice.getAttribute('data-zerti-loaded') === '1') {
                    fetchShopOrderPartial(root, oidInvoice, 'invoice', shopSlotInvoice, function () {
                        syncUrl('shop', root, false);
                    });
                } else {
                    setTab('shop', true);
                }
                return;
            }

            var backProduct = e.target && e.target.closest ? e.target.closest('.zerti-inventory-product-back') : null;
            if (backProduct && root.contains(backProduct)) {
                if (shouldInterceptAdminLink(e, backProduct)) {
                    e.preventDefault();
                } else {
                    return;
                }
                setInventoryProductUrl(undefined);
                var invSlotBack = root.querySelector('[data-zerti-slot="inventory"]');
                if (invSlotBack && invSlotBack.getAttribute('data-zerti-loaded') === '1') {
                    fetchInventoryPartial(root, 'warehouse', invSlotBack, function () {
                        syncUrl('inventory', root, false);
                    });
                }
                return;
            }

            var addProduct = e.target && e.target.closest ? e.target.closest('.zerti-product-add-btn[data-zerti-product]') : null;
            if (addProduct && root.contains(addProduct)) {
                if (!handleInAppControl(e, addProduct)) {
                    return;
                }
                setInventoryProductUrl(0);
                var invSlotAdd = root.querySelector('[data-zerti-slot="inventory"]');
                var activeNavAdd = root.querySelector('.zerti-nav-tab.active');
                var activeTabAdd = activeNavAdd ? activeNavAdd.getAttribute('data-zerti-tab') : '';
                if (activeTabAdd === 'inventory' && invSlotAdd && invSlotAdd.getAttribute('data-zerti-loaded') === '1') {
                    fetchInventoryProductPartial(root, 0, invSlotAdd, function () {
                        syncUrl('inventory', root, false);
                    });
                } else {
                    setTab('inventory', true);
                }
                return;
            }

            var detailProduct = e.target && e.target.closest ? e.target.closest('.zerti-product-detail-btn[data-zerti-product]') : null;
            if (detailProduct && root.contains(detailProduct)) {
                if (!handleInAppControl(e, detailProduct)) {
                    return;
                }
                var prodRaw = detailProduct.getAttribute('data-zerti-product') || '';
                var prodNum = parseInt(prodRaw, 10);
                if (!(prodNum > 0)) {
                    return;
                }
                setInventoryProductUrl(prodNum);
                var invSlotDet = root.querySelector('[data-zerti-slot="inventory"]');
                var activeNavProd = root.querySelector('.zerti-nav-tab.active');
                var activeTabProd = activeNavProd ? activeNavProd.getAttribute('data-zerti-tab') : '';
                if (activeTabProd === 'inventory' && invSlotDet && invSlotDet.getAttribute('data-zerti-loaded') === '1') {
                    fetchInventoryProductPartial(root, prodNum, invSlotDet, function () {
                        syncUrl('inventory', root, false);
                    });
                } else {
                    setTab('inventory', true);
                }
                return;
            }

            var backCustomer = e.target && e.target.closest ? e.target.closest('.zerti-customer-detail-back') : null;
            if (backCustomer && root.contains(backCustomer)) {
                if (shouldInterceptAdminLink(e, backCustomer)) {
                    e.preventDefault();
                } else {
                    return;
                }
                setCustomerDetailUrl(0);
                var custSlotBack = root.querySelector('[data-zerti-slot="customers"]');
                if (custSlotBack && custSlotBack.getAttribute('data-zerti-loaded') === '1') {
                    fetchComponent('customers', custSlotBack, root, function () {
                        syncUrl('customers', root, false);
                    });
                }
                return;
            }

            var detailCustomer = e.target && e.target.closest ? e.target.closest('.zerti-customer-detail-btn[data-zerti-customer]') : null;
            if (detailCustomer && root.contains(detailCustomer)) {
                if (!handleInAppControl(e, detailCustomer)) {
                    return;
                }
                var custRaw = detailCustomer.getAttribute('data-zerti-customer') || '';
                var custNum = parseInt(custRaw, 10);
                if (!(custNum > 0)) {
                    return;
                }
                setCustomerDetailUrl(custNum);
                var custSlotDet = root.querySelector('[data-zerti-slot="customers"]');
                var activeNavCust = root.querySelector('.zerti-nav-tab.active');
                var activeTabCust = activeNavCust ? activeNavCust.getAttribute('data-zerti-tab') : '';
                if (activeTabCust === 'customers' && custSlotDet && custSlotDet.getAttribute('data-zerti-loaded') === '1') {
                    fetchCustomerDetailPartial(root, custNum, custSlotDet, function () {
                        syncUrl('customers', root, false);
                    });
                } else {
                    setTab('customers', true);
                }
                return;
            }

            var newShopOrder = e.target && e.target.closest ? e.target.closest('.zerti-shop-order-new-btn') : null;
            if (newShopOrder && root.contains(newShopOrder)) {
                e.preventDefault();
                if (
                    newShopOrder.classList.contains('zerti-shop-order-new-btn--pro') &&
                    !getLicenseComponentsCfg().licenseIsPro
                ) {
                    openLicenseSettingsTab('license');
                    return;
                }
                setShopOrderUrl(0, 'create');
                var shopSlotNew = root.querySelector('[data-zerti-slot="shop"]');
                var activeNavNew = root.querySelector('.zerti-nav-tab.active');
                var activeTabNew = activeNavNew ? activeNavNew.getAttribute('data-zerti-tab') : '';
                if (activeTabNew === 'shop' && shopSlotNew && shopSlotNew.getAttribute('data-zerti-loaded') === '1') {
                    fetchShopOrderCreatePartial(root, shopSlotNew, function () {
                        syncUrl('shop', root, false);
                    });
                } else {
                    setTab('shop', true);
                }
                return;
            }

            var detailShop = e.target && e.target.closest ? e.target.closest('.zerti-shop-order-detail-btn[data-zerti-shop-order]') : null;
            if (detailShop && root.contains(detailShop)) {
                if (!handleInAppControl(e, detailShop)) {
                    return;
                }
                var oidRaw = detailShop.getAttribute('data-zerti-shop-order') || '';
                var oidNum = parseInt(oidRaw, 10);
                if (!(oidNum > 0)) {
                    return;
                }
                setShopOrderUrl(oidNum, 'detail');
                var shopSlotDet = root.querySelector('[data-zerti-slot="shop"]');
                var activeNavShop = root.querySelector('.zerti-nav-tab.active');
                var activeTabShop = activeNavShop ? activeNavShop.getAttribute('data-zerti-tab') : '';
                if (activeTabShop === 'shop' && shopSlotDet && shopSlotDet.getAttribute('data-zerti-loaded') === '1') {
                    fetchShopOrderPartial(root, oidNum, 'detail', shopSlotDet, function () {
                        syncUrl('shop', root, false);
                    });
                } else {
                    setTab('shop', true);
                }
                return;
            }

            var crmBtn = e.target && e.target.closest ? e.target.closest('.zerti-crm-subtab[data-zerti-tab]') : null;
            if (crmBtn && root.contains(crmBtn)) {
                var crmPanelTab = crmBtn.getAttribute('data-zerti-tab') || '';
                if (!isCustomerRelationsPanelTab(crmPanelTab) || !validTab(crmPanelTab)) {
                    return;
                }
                if (shouldInterceptAdminLink(e, crmBtn)) {
                    e.preventDefault();
                } else {
                    return;
                }
                closeMobileSidebar();
                pushRoute({ tab: crmPanelTab });
                setInventorySubmenuExpanded(root, false);
                setFinancialSubmenuExpanded(root, false);
                setReportsSubmenuExpanded(root, false);
                setCustomerRelationsSubmenuExpanded(root, true);
                setCustomerRelationsSubnavActive(root, crmPanelTab);
                setTab(crmPanelTab, true);
                return;
            }

            var fbtn =
                e.target && e.target.closest
                    ? e.target.closest('.zerti-financial-subtab[data-zerti-fin-sub], .zerti-reports-subtab[data-zerti-fin-sub]')
                    : null;
            if (fbtn && root.contains(fbtn)) {
                var fsub = fbtn.getAttribute('data-zerti-fin-sub') || '';
                if (!VALID_FIN_SUBS[fsub]) {
                    return;
                }
                if (shouldInterceptAdminLink(e, fbtn)) {
                    e.preventDefault();
                } else {
                    return;
                }
                closeMobileSidebar();
                pushRoute({ tab: 'financial', fin: fsub });
                setInventorySubmenuExpanded(root, false);
                setCustomerRelationsSubmenuExpanded(root, false);
                syncFinancialNavState(root, 'financial', fsub);
                root.querySelectorAll('.zerti-nav-tab').forEach(function (btn) {
                    var navTab = btn.getAttribute('data-zerti-tab') || '';
                    var on =
                        (navTab === 'financial' && !isReportsNavActive('financial', fsub)) ||
                        (navTab === 'reports' && isReportsNavActive('financial', fsub));
                    btn.classList.toggle('active', on);
                    btn.setAttribute('aria-selected', on ? 'true' : 'false');
                });
                var activeNav2 = root.querySelector('.zerti-nav-tab.active');
                var activeTab2 = activeNav2 ? activeNav2.getAttribute('data-zerti-tab') : '';
                var finSlot = root.querySelector('[data-zerti-slot="financial"]');
                if ((activeTab2 === 'financial' || activeTab2 === 'reports') && finSlot && finSlot.getAttribute('data-zerti-loaded') === '1') {
                    fetchFinancialPartial(root, fsub, finSlot, function () {
                        syncUrl('financial', root, false);
                    });
                } else {
                    setTab('financial', true);
                }
                return;
            }

            var btn = e.target && e.target.closest ? e.target.closest('.zerti-inventory-subtab[data-zerti-inv-sub]') : null;
            if (!btn || !root.contains(btn)) {
                return;
            }
            var sub = btn.getAttribute('data-zerti-inv-sub') || '';
            if (!VALID_INV_SUBS[sub]) {
                return;
            }
            if (shouldInterceptAdminLink(e, btn)) {
                e.preventDefault();
            } else {
                return;
            }
            closeMobileSidebar();
            if (sub === 'warehouse') {
                pushRoute({ tab: 'inventory', inv: 'warehouse' });
            } else {
                pushRoute({ tab: 'inventory', inv: sub });
            }
            setFinancialSubmenuExpanded(root, false);
            setReportsSubmenuExpanded(root, false);
            setCustomerRelationsSubmenuExpanded(root, false);
            setInventorySubmenuExpanded(root, true);
            setInventorySubnavActive(root, sub);
            var activeNav = root.querySelector('.zerti-nav-tab.active');
            var activeTab = activeNav ? activeNav.getAttribute('data-zerti-tab') : '';
            var invSlot = root.querySelector('[data-zerti-slot="inventory"]');
            if (activeTab === 'inventory' && invSlot && invSlot.getAttribute('data-zerti-loaded') === '1') {
                fetchInventoryPartial(root, sub, invSlot, function () {
                    syncUrl('inventory', root, false);
                });
            } else {
                setTab('inventory', true);
            }
        });

        function applyRouteFromLocation() {
            var route = parseRoute();
            var tab = route.tab && validTab(route.tab) ? route.tab : 'home';
            if (tab === 'inventory') {
                setInventorySubmenuExpanded(root, true);
            } else {
                setInventorySubmenuExpanded(root, false);
            }
            var finSub = tab === 'financial' ? route.fin || financialSubFromUrl() : '';
            syncFinancialNavState(root, tab, finSub);
            if (isCustomerRelationsPanelTab(tab)) {
                setCustomerRelationsSubmenuExpanded(root, true);
            } else {
                setCustomerRelationsSubmenuExpanded(root, false);
            }
            setTab(tab, true);
        }

        window.addEventListener('popstate', function () {
            applyRouteFromLocation();
        });

        root.addEventListener('change', function (e) {
            var input = e.target && e.target.closest ? e.target.closest('.zerti-file-upload__input[data-zerti-file-empty]') : null;
            if (!input || !root.contains(input)) {
                return;
            }

            var wrap = input.closest('.zerti-file-upload');
            var nameEl = wrap ? wrap.querySelector('[data-zerti-file-name]') : null;
            if (!nameEl) {
                return;
            }

            var emptyText = input.getAttribute('data-zerti-file-empty') || '';
            nameEl.textContent = input.files && input.files.length > 0 ? input.files[0].name : emptyText;

            var errorEl = wrap ? wrap.querySelector('[data-zerti-file-error]') : null;
            if (errorEl) {
                errorEl.textContent = '';
                errorEl.classList.add('d-none');
            }
        });

        root.addEventListener('submit', function (e) {
            var form = e.target && e.target.closest ? e.target.closest('.zerti-settings-form') : null;
            if (!form || !root.contains(form)) {
                return;
            }

            if (!ajaxUrl) {
                return;
            }

            var submitter = e.submitter || (document.activeElement && form.contains(document.activeElement) ? document.activeElement : null);
            var isRemoveLogo = submitter && submitter.name === 'zerti_remove_identity_logo';
            var input = form.querySelector('.zerti-file-upload__input[data-zerti-max-upload-size]');
            if (!isRemoveLogo && input && input.files && input.files.length > 0) {
                var maxSize = parseInt(input.getAttribute('data-zerti-max-upload-size') || '0', 10);
                if (maxSize && input.files[0].size > maxSize) {
                    e.preventDefault();
                    var sizeWrap = input.closest('.zerti-file-upload');
                    var sizeErrorEl = sizeWrap ? sizeWrap.querySelector('[data-zerti-file-error]') : null;
                    var sizeMsg = input.getAttribute('data-zerti-upload-size-error') || '';
                    if (sizeErrorEl) {
                        sizeErrorEl.textContent = sizeMsg;
                        sizeErrorEl.classList.remove('d-none');
                    } else if (sizeMsg) {
                        window.alert(sizeMsg);
                    }
                    return;
                }

                var allowedExts = (input.getAttribute('data-zerti-allowed-extensions') || '')
                    .split(',')
                    .map(function (ext) {
                        return ext.trim().toLowerCase();
                    })
                    .filter(Boolean);
                var fileName = input.files[0].name || '';
                var fileExt = fileName.indexOf('.') >= 0 ? fileName.split('.').pop().toLowerCase() : '';
                if (allowedExts.length > 0 && allowedExts.indexOf(fileExt) === -1) {
                    e.preventDefault();
                    var typeWrap = input.closest('.zerti-file-upload');
                    var typeErrorEl = typeWrap ? typeWrap.querySelector('[data-zerti-file-error]') : null;
                    var typeMsg = input.getAttribute('data-zerti-upload-type-error') || '';
                    if (typeErrorEl) {
                        typeErrorEl.textContent = typeMsg;
                        typeErrorEl.classList.remove('d-none');
                    } else if (typeMsg) {
                        window.alert(typeMsg);
                    }
                    return;
                }
            }

            e.preventDefault();

            syncPostalPdfPostFields(form);
            syncVisualThemePostField(form);

            var slot = form.closest('.zerti-panel-slot') || root.querySelector('[data-zerti-slot="settings"]');
            if (!slot) {
                form.submit();
                return;
            }

            var body;
            try {
                body = submitter ? new window.FormData(form, submitter) : new window.FormData(form);
            } catch (err0) {
                body = new window.FormData(form);
                if (submitter && submitter.name) {
                    body.append(submitter.name, submitter.value || '1');
                }
            }
            if (!body.has('action')) {
                body.append('action', settingsAction);
            }
            if (settingsNonce && !body.has('_wpnonce')) {
                body.append('_wpnonce', settingsNonce);
            }

            appendPostalPdfFieldsToFormData(form, body);
            body.set(
                'zerti_settings[general][visual_theme]',
                syncVisualThemePostField(form) || 'zerti'
            );

            [
                'zerti_settings[general][pdf_invoice_paper_size]',
                'zerti_settings[general][pdf_postal_label_paper_size]',
                'zerti_settings[general][pdf_warehouse_sheet_paper_size]',
            ].forEach(function (fieldName) {
                var field = form.querySelector('[name="' + fieldName + '"]');
                if (field) {
                    body.set(fieldName, field.value || '');
                }
            });

            var directionField = form.querySelector('[name="zerti_settings[general][text_direction]"]');
            var submittedDirection = directionField ? String(directionField.value || 'rtl') : '';
            var currentDirection = root.getAttribute('dir') || cfg.textDirection || 'rtl';
            var directionWillChange =
                submittedDirection !== '' &&
                submittedDirection !== currentDirection;

            var calendarField = form.querySelector('[name="zerti_settings[general][calendar]"]');
            var submittedCalendar = calendarField ? String(calendarField.value || 'jalali') : '';
            var currentCalendar = cfg.calendar || 'jalali';
            var calendarWillChange =
                submittedCalendar !== '' &&
                submittedCalendar !== currentCalendar;

            var adminLocaleField = form.querySelector('[name="zerti_settings[general][admin_locale]"]');
            var submittedAdminLocale = adminLocaleField ? String(adminLocaleField.value || '') : '';
            var currentAdminLocale = cfg.adminLocale || '';
            var adminLocaleWillChange =
                submittedAdminLocale !== '' &&
                submittedAdminLocale !== currentAdminLocale;

            var digitsFormatField = form.querySelector('[name="zerti_settings[general][digits_format]"]');
            var submittedDigitsFormat = digitsFormatField ? String(digitsFormatField.value || 'auto') : '';
            var currentDigitsFormat = cfg.digitsFormat || 'auto';
            var digitsFormatWillChange =
                submittedDigitsFormat !== '' &&
                submittedDigitsFormat !== currentDigitsFormat;

            var submittedVisualTheme = syncVisualThemePostField(form) || 'zerti';
            var currentVisualTheme = getCurrentVisualTheme(root);
            var visualThemeWillChange =
                submittedVisualTheme !== '' &&
                submittedVisualTheme !== currentVisualTheme;

            var settingsLayout = form.querySelector('.zerti-settings-layout');
            var tabField = form.querySelector('[name="zerti_settings_active_tab"]');
            var activeSettingsTab =
                lastSettingsTabId ||
                (tabField && tabField.value) ||
                getActiveSettingsTabId(settingsLayout) ||
                'identity';
            var themeCustomizationWillApply =
                activeSettingsTab === 'themes' &&
                (submittedVisualTheme === 'rabbitmp' || submittedVisualTheme === 'demerzel');

            slot.setAttribute('aria-busy', 'true');
            var settingsComponent = form.closest('.zerti-component-settings, .zerti-component-bulk-action');
            var saveButton = form.querySelector('.zerti-settings-save-btn');
            if (saveButton) {
                saveButton.disabled = true;
            }
            var overlay = attachSettingsSaveOverlay(settingsComponent || slot);

            window
                .fetch(ajaxUrl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: body,
                })
                .then(parseAjaxJson)
                .then(function (data) {
                    if (!data || !data.success || !data.data || typeof data.data.html !== 'string') {
                        throw new Error('bad response');
                    }
                    var settingsSaved = data.data.saved !== false;
                    slot.innerHTML = data.data.html;
                    slot.setAttribute('data-zerti-loaded', '1');
                    slot.classList.remove('zerti-panel-slot--pending');
                    detachSettingsSaveOverlay(overlay, settingsComponent);
                    overlay = null;
                    settingsComponent = null;
                    var savedVisualTheme = typeof data.data.visualTheme === 'string'
                        ? data.data.visualTheme
                        : submittedVisualTheme;
                    if (
                        settingsSaved &&
                        (
                            directionWillChange ||
                            calendarWillChange ||
                            adminLocaleWillChange ||
                            digitsFormatWillChange ||
                            visualThemeWillChange ||
                            savedVisualTheme !== currentVisualTheme ||
                            themeCustomizationWillApply
                        )
                    ) {
                        window.location.reload();
                        return;
                    }
                    initSettingsTabs(slot);
                    var restoredLayout = slot.querySelector('.zerti-settings-layout');
                    activateSettingsTab(restoredLayout, activeSettingsTab);
                    scheduleSettingsAlerts(slot);
                })
                .catch(function () {
                    detachSettingsSaveOverlay(overlay, settingsComponent);
                    overlay = null;
                    settingsComponent = null;
                    slot.innerHTML = errorMarkup();
                    slot.querySelectorAll('.zerti-component-retry').forEach(function (btn) {
                        btn.addEventListener('click', function () {
                            fetchComponent('settings', slot, root);
                        });
                    });
                })
                .finally(function () {
                    detachSettingsSaveOverlay(overlay, settingsComponent);
                    if (saveButton) {
                        saveButton.disabled = false;
                    }
                    if (slot) {
                        slot.removeAttribute('aria-busy');
                    }
                });
        });

        scheduleSettingsAlerts(root);
        initBulkActionTabs(root);

        /**
         * Open shop order detail from grids (e.g. financial payments row click).
         *
         * @param {number|string} orderId
         * @param {string} [view] `detail` or `invoice`
         */
        window.zertiOpenShopOrderDetail = function (orderId, view) {
            var oidNum = parseInt(String(orderId), 10);
            if (!(oidNum > 0)) {
                return;
            }
            var orderView = view === 'invoice' ? 'invoice' : shopViewDefault;
            var activeNavShopOpen = root.querySelector('.zerti-nav-tab.active');
            var activeTabShopOpen = activeNavShopOpen ? activeNavShopOpen.getAttribute('data-zerti-tab') : '';
            if (activeTabShopOpen === 'financial') {
                captureListContext('financial');
                window.__zertiShopOrderReturnScope = 'financial';
            } else {
                window.__zertiShopOrderReturnScope = 'shop';
            }
            setShopOrderUrl(oidNum, orderView);
            var shopSlotDet = root.querySelector('[data-zerti-slot="shop"]');
            var activeNavShop = root.querySelector('.zerti-nav-tab.active');
            var activeTabShop = activeNavShop ? activeNavShop.getAttribute('data-zerti-tab') : '';
            if (activeTabShop === 'shop' && shopSlotDet && shopSlotDet.getAttribute('data-zerti-loaded') === '1') {
                fetchShopOrderPartial(root, oidNum, orderView, shopSlotDet, function () {
                    syncUrl('shop', root, false);
                });
            } else {
                setTab('shop', true);
            }
        };

        /**
         * Open customer detail from grids (e.g. customers list row click).
         *
         * @param {number|string} customerId
         */
        window.zertiOpenCustomerDetail = function (customerId) {
            var custNum = parseInt(String(customerId), 10);
            if (!(custNum > 0)) {
                return;
            }
            setCustomerDetailUrl(custNum);
            var custSlotDet = root.querySelector('[data-zerti-slot="customers"]');
            var activeNavCust = root.querySelector('.zerti-nav-tab.active');
            var activeTabCust = activeNavCust ? activeNavCust.getAttribute('data-zerti-tab') : '';
            if (activeTabCust === 'customers' && custSlotDet && custSlotDet.getAttribute('data-zerti-loaded') === '1') {
                fetchCustomerDetailPartial(root, custNum, custSlotDet, function () {
                    syncUrl('customers', root, false);
                });
            } else {
                setTab('customers', true);
            }
        };

        var seedRoute =
            cfg.initialRoute && typeof cfg.initialRoute === 'object' ? cfg.initialRoute : parseRoute();
        if (!history.state || !history.state.zerti) {
            history.replaceState({ zerti: seedRoute }, '', routeToUrl(seedRoute));
        }

        setTab(seedRoute.tab || initialTab || 'home', true);

        window.zertiEnsureTabBundles = ensureBundlesForTab;

        if (typeof window.zertiProAdminLicenseInit === 'function') {
            window.zertiProAdminLicenseInit({
                root: root,
                ajaxUrl: ajaxUrl,
                activateSettingsTab: activateSettingsTab,
                openLicenseSettingsTab: openLicenseSettingsTab,
                refreshProGatedPanelSlots: refreshProGatedPanelSlots,
                reloadLicensedProUi: reloadLicensedProUi,
            });
        }

        refreshNavBadges();
        var bootTab = seedRoute.tab || initialTab || 'home';
        var homeSlotBoot = root.querySelector('[data-zerti-slot="home"]');
        var homeStatsHydrating =
            bootTab === 'home' &&
            homeSlotBoot &&
            homeSlotBoot.getAttribute('data-zerti-loaded') === '1' &&
            homeSlotBoot.querySelector('.zerti-component-home--loading');
        if (!homeStatsHydrating) {
            refreshHomeDashboardStats({ refresh: true });
        }

        window.setInterval(function () {
            if (document.visibilityState !== 'visible') {
                return;
            }
            refreshDashboard({ refresh: true });
        }, 120000);

        document.addEventListener('visibilitychange', function () {
            if (document.visibilityState === 'visible') {
                refreshDashboard({ refresh: true });
                var licenseApi = proLicense();
                if (licenseApi && typeof licenseApi.syncLicenseEditionFromServerStatus === 'function') {
                    licenseApi.syncLicenseEditionFromServerStatus(root);
                }
            }
        });

        document.addEventListener('zerti:nav-badges-changed', refreshNavBadges);

        window.zertiReloadInventoryPartial = function (sub, onDone) {
            var invSlot = root.querySelector('[data-zerti-slot="inventory"]');
            if (!invSlot) {
                if (typeof onDone === 'function') {
                    onDone(false);
                }
                return;
            }
            var targetSub = sub && VALID_INV_SUBS[sub] ? sub : inventorySubFromUrl() || invDefault;
            fetchInventoryPartial(root, targetSub, invSlot, onDone);
        };

        /**
         * Open warehouse product editor (0 = new, >0 = edit).
         *
         * @param {number|string} productId
         * @param {boolean} [replaceUrl]
         */
        window.zertiOpenInventoryProductEdit = function (productId, replaceUrl) {
            var pid = parseInt(String(productId), 10);
            if (isNaN(pid) || pid < 0) {
                return;
            }
            if (replaceUrl) {
                replaceRoute({ tab: 'inventory', inv: 'warehouse', product: pid });
            } else {
                setInventoryProductUrl(pid);
            }
            var invSlotDet = root.querySelector('[data-zerti-slot="inventory"]');
            var activeNavProd = root.querySelector('.zerti-nav-tab.active');
            var activeTabProd = activeNavProd ? activeNavProd.getAttribute('data-zerti-tab') : '';
            if (activeTabProd === 'inventory' && invSlotDet && invSlotDet.getAttribute('data-zerti-loaded') === '1') {
                fetchInventoryProductPartial(root, pid, invSlotDet, function () {
                    syncUrl('inventory', root, false);
                });
            } else {
                setTab('inventory', true);
            }
        };
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
