/**
 * Bizmart Dashboard JS — extracted from inline scripts for CSP compliance & caching.
 * Receives dynamic data via wp_localize_script → window.BizmartDashConfig
 *
 * @package Bizmart
 */
(function () {
    'use strict';

    /* ─── Bootstrap i18n helper ──────────────────────────────────────── */
    window.BizmartAnalytics = window.BizmartAnalytics || {};
    window.BizmartDashboard = window.BizmartDashboard || {};

    var cfg = window.BizmartDashConfig || {};
    if (cfg.ajax_url) BizmartAnalytics.ajax_url = cfg.ajax_url;
    if (cfg.nonce) BizmartAnalytics.nonce = cfg.nonce;
    if (cfg.currency) BizmartAnalytics.currency = cfg.currency;
    if (cfg.admin_lang) BizmartAnalytics.admin_lang = cfg.admin_lang;

    BizmartDashboard.adminLang = cfg.admin_lang || 'en';
    BizmartDashboard.t = function (en, fr, ar) {
        if (BizmartDashboard.adminLang === 'ar') {
            var dict = (window.BizmartI18n && BizmartI18n.ar) ? BizmartI18n.ar : null;
            return ar || (dict && dict[en]) || en;
        }
        return (BizmartDashboard.adminLang === 'fr') ? fr : en;
    };

    var t = BizmartDashboard.t;
    var currency = cfg.currency || 'USD';
    var ajaxUrl = function () { return BizmartAnalytics.ajax_url || window.ajaxurl || ''; };
    var nonce = function () { return BizmartAnalytics.nonce || ''; };

    /* ─── Price formatter ────────────────────────────────────────────── */
    window.formatPrice = function (price) {
        if (!price) return 'N/A';
        try {
            return new Intl.NumberFormat(undefined, { style: 'currency', currency: currency }).format(price);
        } catch (e) {
            return price;
        }
    };

    /* ─── Compare-panel toggle ───────────────────────────────────────── */
    function initComparePanel() {
        var btn = document.getElementById('biz-compare-toggle');
        var panel = document.getElementById('biz-compare-panel');
        var compareForm = document.getElementById('biz-compare-form');
        var compareStart = document.getElementById('biz-compare-start');
        var compareEnd = document.getElementById('biz-compare-end');
        if (!btn || !panel) return;

        var mainStart = document.querySelector('form:not(#biz-compare-form) input[name="start_date"]');
        var mainEnd = document.querySelector('form:not(#biz-compare-form) input[name="end_date"]');

        var syncDatesFromMain = function () {
            if (!compareStart || !compareEnd) return;
            if (mainStart && mainStart.value) compareStart.value = mainStart.value;
            if (mainEnd && mainEnd.value) compareEnd.value = mainEnd.value;
        };

        var updateCustom = function () {
            var mode = document.querySelector('input[name="compare_mode"]:checked');
            var custom = document.getElementById('biz-compare-custom');
            if (!custom) return;
            custom.style.display = (mode && mode.value === 'custom') ? 'block' : 'none';
        };

        btn.addEventListener('click', function () {
            var isOpen = panel.style.display !== 'none';
            panel.style.display = isOpen ? 'none' : 'block';
            btn.setAttribute('aria-expanded', isOpen ? 'false' : 'true');
            if (!isOpen) syncDatesFromMain();
            updateCustom();
        });

        if (compareForm) {
            compareForm.addEventListener('submit', function () { syncDatesFromMain(); });
        }

        document.addEventListener('click', function (e) {
            if (!panel || panel.style.display === 'none') return;
            if (panel.contains(e.target) || btn.contains(e.target)) return;
            panel.style.display = 'none';
            btn.setAttribute('aria-expanded', 'false');
        });

        document.addEventListener('keydown', function (e) {
            if (e.key !== 'Escape') return;
            if (!panel || panel.style.display === 'none') return;
            panel.style.display = 'none';
            btn.setAttribute('aria-expanded', 'false');
        });

        document.querySelectorAll('input[name="compare_mode"]').forEach(function (r) {
            r.addEventListener('change', updateCustom);
        });

        updateCustom();
    }

    /* ─── Missing Prices Popup ───────────────────────────────────────── */
    window.openMissingPricesPopup = function () {
        togglePopup('biz-missing-prices-popup', true);
    };

    window.closeMissingPricesPopup = function () {
        togglePopup('biz-missing-prices-popup', false);
    };

    function togglePopup(popupId, shouldOpen) {
        var popup = document.getElementById(popupId);
        if (!popup) return;
        popup.style.display = shouldOpen ? 'flex' : 'none';
        document.body.style.overflow = shouldOpen ? 'hidden' : '';
    }

    window.openPriceAlertsPopup = function () {
        togglePopup('biz-price-alerts-popup', true);
    };

    window.closePriceAlertsPopup = function () {
        togglePopup('biz-price-alerts-popup', false);
    };

    window.openLowMarginPopup = function () {
        togglePopup('biz-low-margin-popup', true);
    };

    window.closeLowMarginPopup = function () {
        togglePopup('biz-low-margin-popup', false);
    };

    function parseNumber(value) {
        var parsed = parseFloat(value);
        return isFinite(parsed) ? parsed : 0;
    }

    function roundNumber(value) {
        return Math.round(parseFloat(value || 0) * 100) / 100;
    }

    function computeMargin(purchasePrice, sellingPrice) {
        if (sellingPrice <= 0) return 0;
        return roundNumber(((sellingPrice - purchasePrice) / sellingPrice) * 100);
    }

    function computeSellingFromMargin(purchasePrice, marginPercent) {
        var safeMargin = Math.max(0, Math.min(99.99, marginPercent));
        var divisor = 1 - (safeMargin / 100);
        if (divisor <= 0) return 0;
        return roundNumber(purchasePrice / divisor);
    }

    function syncPricingRow(row, sourceRole) {
        if (!row) return;
        var purchaseInput = row.querySelector('[data-role="purchase"]');
        var sellingInput = row.querySelector('[data-role="selling"]');
        var marginInput = row.querySelector('[data-role="margin"]');
        if (!purchaseInput || !sellingInput || !marginInput) return;

        var purchase = parseNumber(purchaseInput.value);
        var selling = parseNumber(sellingInput.value);
        var margin = parseNumber(marginInput.value);

        if (sourceRole === 'margin') {
            selling = computeSellingFromMargin(purchase, margin);
            sellingInput.value = selling > 0 ? selling.toFixed(2) : '';
        } else {
            margin = computeMargin(purchase, selling);
            marginInput.value = margin.toFixed(2);
        }
    }

    function syncLowMarginRow(row, sourceRole) {
        syncPricingRow(row, sourceRole);
    }

    function updateDashboardAlertHubState() {
        var hub = document.getElementById('biz-stock-alert-hub');
        var lowMarginCta = document.getElementById('biz-low-margin-cta');
        var missingPricingCta = document.getElementById('biz-missing-pricing-cta');
        var crisisStockCta = document.getElementById('biz-crisis-stock-cta');
        var lowStockCta = document.getElementById('biz-low-stock-cta');
        var pendingOrdersCta = document.getElementById('biz-pending-orders-cta');
        if (!hub) return;

        var lowMarginVisible = !!(lowMarginCta && lowMarginCta.style.display !== 'none');
        var missingVisible = !!(missingPricingCta && missingPricingCta.style.display !== 'none');
        var crisisVisible = !!(crisisStockCta && crisisStockCta.style.display !== 'none');
        var lowStockVisible = !!(lowStockCta && lowStockCta.style.display !== 'none');
        var pendingVisible = !!(pendingOrdersCta && pendingOrdersCta.style.display !== 'none');
        hub.style.display = (lowMarginVisible || missingVisible || crisisVisible || lowStockVisible || pendingVisible) ? 'flex' : 'none';
    }

    function updateLowMarginCtaState() {
        var rows = document.querySelectorAll('[data-low-margin-row]');
        var count = rows.length;
        var countBadge = document.getElementById('biz-low-margin-cta-count');
        var cta = document.getElementById('biz-low-margin-cta');
        var emptyState = document.getElementById('biz-low-margin-empty');
        if (countBadge) countBadge.textContent = String(count);
        if (emptyState) emptyState.style.display = count === 0 ? 'block' : 'none';
        if (cta) cta.style.display = count === 0 ? 'none' : 'inline-flex';
        updateDashboardAlertHubState();
    }

    function missingPricingStatusMeta(statusKey) {
        if (statusKey === 'both') {
            return { label: t('Missing both prices', 'Prix achat et vente manquants', 'أسعار الشراء والبيع مفقودة'), background: '#fee2e2', color: '#991b1b' };
        }
        if (statusKey === 'selling') {
            return { label: t('Missing selling price', 'Prix de vente manquant', 'سعر البيع مفقود'), background: '#dbeafe', color: '#1d4ed8' };
        }
        if (statusKey === 'children') {
            return { label: t('Variations need pricing', 'Des variations ont besoin de prix', 'المتغيرات تحتاج تسعير'), background: '#ede9fe', color: '#6d28d9' };
        }
        if (statusKey === 'purchase') {
            return { label: t('Missing purchase price', 'Prix d\'achat manquant', 'سعر الشراء مفقود'), background: '#fef3c7', color: '#92400e' };
        }
        if (statusKey === 'loss') {
            return { label: t('Selling below cost', 'Vente sous le coût', 'البيع أقل من التكلفة'), background: '#fee2e2', color: '#991b1b' };
        }
        if (statusKey === 'break_even') {
            return { label: t('Break-even price', 'Prix sans gain ni perte', 'سعر بدون ربح أو خسارة'), background: '#fde68a', color: '#92400e' };
        }
        if (statusKey === 'low_margin') {
            return { label: t('Low margin', 'Marge faible', 'هامش منخفض'), background: '#fef3c7', color: '#92400e' };
        }
        return { label: t('Pricing complete', 'Tarification complète', 'التسعير مكتمل'), background: '#dcfce7', color: '#166534' };
    }

    function currentLowMarginThreshold() {
        var thresholdInput = document.getElementById('biz-low-margin-threshold');
        var threshold = thresholdInput ? parseNumber(thresholdInput.value) : 10;
        if (!isFinite(threshold) || threshold < 0) threshold = 10;
        return threshold;
    }

    function setMissingPricingStatus(row, statusKey) {
        var badge = row ? row.querySelector('[data-role="status-badge"]') : null;
        if (!badge) return;
        var meta = missingPricingStatusMeta(statusKey);
        badge.textContent = meta.label;
        badge.setAttribute('data-status-key', statusKey);
        badge.style.background = meta.background;
        badge.style.color = meta.color;
    }

    function updateMissingPricingCtaState() {
        var count = document.querySelectorAll('[data-missing-pricing-row][data-countable="1"]').length;
        var countBadge = document.getElementById('biz-missing-pricing-cta-count');
        var cta = document.getElementById('biz-missing-pricing-cta');
        var emptyState = document.getElementById('biz-missing-pricing-empty');

        if (countBadge) countBadge.textContent = String(count);
        if (cta) cta.style.display = count === 0 ? 'none' : 'inline-flex';
        if (emptyState) emptyState.style.display = count === 0 ? 'block' : 'none';
        updateDashboardAlertHubState();
    }

    function updateMissingPricingRowState(row) {
        if (!row) return false;

        var purchaseInput = row.querySelector('[data-role="purchase"]');
        var sellingInput = row.querySelector('[data-role="selling"]');
        var purchase = parseNumber(purchaseInput && purchaseInput.value);
        var selling = parseNumber(sellingInput && sellingInput.value);
        var margin = computeMargin(purchase, selling);
        var threshold = currentLowMarginThreshold();
        var rowKind = row.getAttribute('data-row-kind') || '';
        var groupId = row.getAttribute('data-group-id') || row.getAttribute('data-product-id') || '';
        var variationRows = groupId
            ? document.querySelectorAll('[data-row-kind="variation"][data-parent-id="' + groupId + '"]')
            : [];

        if (rowKind === 'group' && variationRows.length > 0) {
            setMissingPricingStatus(row, 'children');
            return false;
        }
        if (purchase <= 0 && selling <= 0) {
            setMissingPricingStatus(row, 'both');
            return false;
        }
        if (purchase <= 0) {
            setMissingPricingStatus(row, 'purchase');
            return false;
        }
        if (selling <= 0) {
            setMissingPricingStatus(row, 'selling');
            return false;
        }

        if (selling < purchase) {
            setMissingPricingStatus(row, 'loss');
            return false;
        }
        if (Math.abs(selling - purchase) < 0.005) {
            setMissingPricingStatus(row, 'break_even');
            return false;
        }
        if (margin < threshold) {
            setMissingPricingStatus(row, 'low_margin');
            return false;
        }

        setMissingPricingStatus(row, 'ready');
        return true;
    }

    function removeMissingPricingRow(row) {
        if (!row) return;
        row.style.transition = 'opacity 0.25s ease, transform 0.25s ease';
        row.style.opacity = '0';
        row.style.transform = 'translateY(-6px)';
        setTimeout(function () {
            if (row.parentNode) {
                row.parentNode.removeChild(row);
            }
            updateMissingPricingCtaState();
        }, 260);
    }

    function refreshMissingPricingGroup(groupId) {
        if (!groupId) {
            updateMissingPricingCtaState();
            return;
        }

        var parentRow = document.querySelector('[data-row-kind="group"][data-group-id="' + groupId + '"]');
        if (!parentRow) {
            updateMissingPricingCtaState();
            return;
        }

        var resolved = updateMissingPricingRowState(parentRow);
        var remainingVariations = document.querySelectorAll('[data-row-kind="variation"][data-parent-id="' + groupId + '"]');
        if (parentRow.getAttribute('data-has-child-issues') === '1' && remainingVariations.length === 0) {
            removeMissingPricingRow(parentRow);
            return;
        }
        if (resolved && remainingVariations.length === 0) {
            removeMissingPricingRow(parentRow);
            return;
        }

        updateMissingPricingCtaState();
    }

    function setThresholdLabels(threshold) {
        document.querySelectorAll('[data-low-margin-threshold-label]').forEach(function (node) {
            node.textContent = t('below', 'sous', 'أقل من') + ' ' + roundNumber(threshold).toFixed(2).replace(/\.00$/, '') + '%';
        });
        var thresholdInput = document.getElementById('biz-low-margin-threshold');
        if (thresholdInput) {
            thresholdInput.value = roundNumber(threshold).toFixed(2).replace(/\.00$/, '');
        }
    }

    function saveLowMarginRow(button) {
        var row = button && button.closest ? button.closest('[data-low-margin-row]') : null;
        if (!row || !ajaxUrl() || !nonce()) return;

        var productId = parseInt(row.getAttribute('data-product-id') || '0', 10);
        var purchaseInput = row.querySelector('[data-role="purchase"]');
        var sellingInput = row.querySelector('[data-role="selling"]');
        var marginInput = row.querySelector('[data-role="margin"]');
        var lastChangeCell = row.querySelector('[data-role="last-change"]');
        var thresholdInput = document.getElementById('biz-low-margin-threshold');
        var threshold = thresholdInput ? parseNumber(thresholdInput.value) : 10;
        var purchase = parseNumber(purchaseInput && purchaseInput.value);
        var selling = parseNumber(sellingInput && sellingInput.value);

        if (!productId || purchase < 0 || selling <= 0) {
            alert(t('Enter valid purchase and selling prices.', 'Entrez des prix d\'achat et de vente valides.', 'أدخل سعري شراء وبيع صالحين.'));
            return;
        }

        button.disabled = true;
        var originalText = button.textContent;
        button.textContent = t('Saving...', 'Enregistrement...', 'جارٍ الحفظ...');

        var data = new URLSearchParams();
        data.append('action', 'bizmart_dashboard_update_margin_product');
        data.append('nonce', nonce());
        data.append('product_id', String(productId));
        data.append('purchase_price', purchase.toFixed(2));
        data.append('selling_price', selling.toFixed(2));

        fetch(ajaxUrl(), { method: 'POST', body: data })
            .then(function (response) { return response.json(); })
            .then(function (json) {
                button.disabled = false;
                button.textContent = originalText;

                if (!json || !json.success) {
                    alert((json && json.data && json.data.message) || t('Save error', 'Erreur lors de la sauvegarde', 'خطأ في الحفظ'));
                    return;
                }

                var result = json.data || {};
                purchaseInput.value = parseNumber(result.purchase_price).toFixed(2);
                sellingInput.value = parseNumber(result.selling_price).toFixed(2);
                marginInput.value = parseNumber(result.margin_pct).toFixed(2);
                if (lastChangeCell) {
                    lastChangeCell.textContent = t('Now', 'Maintenant', 'الآن');
                }

                if (parseNumber(result.margin_pct) >= threshold) {
                    row.style.transition = 'opacity 0.25s ease, transform 0.25s ease';
                    row.style.opacity = '0';
                    row.style.transform = 'translateY(-6px)';
                    setTimeout(function () {
                        row.remove();
                        updateLowMarginCtaState();
                    }, 260);
                }
            })
            .catch(function () {
                button.disabled = false;
                button.textContent = originalText;
                alert(t('Request error', 'Erreur lors de la requête', 'خطأ في الطلب'));
            });
    }

    function saveLowMarginThreshold() {
        var thresholdInput = document.getElementById('biz-low-margin-threshold');
        var statusNode = document.getElementById('biz-low-margin-threshold-status');
        var saveButton = document.getElementById('biz-save-low-margin-threshold');
        if (!thresholdInput || !saveButton || !ajaxUrl() || !nonce()) return;

        var threshold = Math.max(0, Math.min(100, parseNumber(thresholdInput.value)));
        saveButton.disabled = true;
        if (statusNode) statusNode.textContent = t('Saving...', 'Enregistrement...', 'جارٍ الحفظ...');

        var data = new URLSearchParams();
        data.append('action', 'bizmart_dashboard_save_margin_threshold');
        data.append('nonce', nonce());
        data.append('threshold', threshold.toFixed(2));

        fetch(ajaxUrl(), { method: 'POST', body: data })
            .then(function (response) { return response.json(); })
            .then(function (json) {
                saveButton.disabled = false;
                if (!json || !json.success) {
                    if (statusNode) statusNode.textContent = t('Save failed.', 'Échec de l\'enregistrement.', 'فشل الحفظ.');
                    return;
                }

                setThresholdLabels(json.data.threshold || threshold);
                document.querySelectorAll('[data-missing-pricing-row]').forEach(function (row) {
                    updateMissingPricingRowState(row);
                });
                updateMissingPricingCtaState();
                if (statusNode) statusNode.textContent = t('Default threshold updated.', 'Seuil par défaut mis à jour.', 'تم تحديث الحد الافتراضي.');
            })
            .catch(function () {
                saveButton.disabled = false;
                if (statusNode) statusNode.textContent = t('Request error.', 'Erreur de requête.', 'خطأ في الطلب.');
            });
    }

    function initAlertPopups() {
        ['biz-price-alerts-popup', 'biz-low-margin-popup', 'biz-missing-prices-popup'].forEach(function (popupId) {
            var popup = document.getElementById(popupId);
            if (!popup) return;
            popup.addEventListener('click', function (event) {
                if (event.target !== popup) return;
                togglePopup(popupId, false);
            });
        });

        document.querySelectorAll('[data-low-margin-row]').forEach(function (row) {
            ['purchase', 'selling', 'margin'].forEach(function (role) {
                var input = row.querySelector('[data-role="' + role + '"]');
                if (!input) return;
                input.addEventListener('input', function () {
                    syncLowMarginRow(row, role === 'margin' ? 'margin' : role);
                });
            });
            syncLowMarginRow(row, 'selling');
        });

        document.querySelectorAll('[data-action="save-low-margin-row"]').forEach(function (button) {
            button.addEventListener('click', function () {
                saveLowMarginRow(button);
            });
        });

        var saveThresholdButton = document.getElementById('biz-save-low-margin-threshold');
        if (saveThresholdButton) {
            saveThresholdButton.addEventListener('click', saveLowMarginThreshold);
        }

        updateLowMarginCtaState();
    }

    function initMissingPricingRows() {
        document.querySelectorAll('[data-missing-pricing-row]').forEach(function (row) {
            ['purchase', 'selling', 'margin'].forEach(function (role) {
                var input = row.querySelector('[data-role="' + role + '"]');
                if (!input) return;
                input.addEventListener('input', function () {
                    syncPricingRow(row, role === 'margin' ? 'margin' : role);
                    updateMissingPricingRowState(row);
                });
            });

            syncPricingRow(row, 'selling');
            updateMissingPricingRowState(row);
        });

        updateMissingPricingCtaState();
    }

    window.toggleVariationRows = function(parentId) {
        var rows = document.querySelectorAll('.biz-var-subrow-' + parentId);
        rows.forEach(function(r) {
            r.style.display = r.style.display === 'none' ? '' : 'none';
        });
    };

    window.saveQuickPrice = function (productId) {
        var row = document.querySelector('[data-missing-pricing-row][data-product-id="' + productId + '"]');
        if (!row) return;

        var purchaseInput = row.querySelector('[data-role="purchase"]');
        var sellingInput = row.querySelector('[data-role="selling"]');
        var marginInput = row.querySelector('[data-role="margin"]');
        var applyAllInput = row.querySelector('[data-role="apply-all"]');
        var purchase = parseNumber(purchaseInput && purchaseInput.value);
        var selling = parseNumber(sellingInput && sellingInput.value);

        if (purchase < 0 || selling <= 0) {
            alert(t('Enter valid purchase and selling prices.', 'Entrez des prix d\'achat et de vente valides.', 'أدخل سعري شراء وبيع صالحين.'));
            if (selling <= 0 && sellingInput) {
                sellingInput.focus();
            } else if (purchaseInput) {
                purchaseInput.focus();
            }
            return;
        }

        if (!ajaxUrl() || !nonce()) {
            alert(t('Missing AJAX configuration. Please refresh the page.', 'Configuration AJAX manquante. Veuillez actualiser la page.', 'إعدادات AJAX مفقودة. يرجى تحديث الصفحة.'));
            return;
        }

        var originalBg = row ? row.style.background : '';
        if (row) row.style.background = '#fef9c3';
        var applyToVariations = !!(applyAllInput && applyAllInput.checked);
        var rowKind = row.getAttribute('data-row-kind') || '';
        var groupId = row.getAttribute('data-group-id') || '';

        var data = new URLSearchParams();
        data.append('action', 'bizmart_dashboard_update_margin_product');
        data.append('nonce', nonce());
        data.append('product_id', productId);
        data.append('purchase_price', purchase.toFixed(2));
        data.append('selling_price', selling.toFixed(2));
        if (applyToVariations) {
            data.append('apply_to_variations', '1');
        }

        fetch(ajaxUrl(), { method: 'POST', body: data })
            .then(function (r) { return r.json(); })
            .then(function (json) {
                if (json.success) {
                    var result = json.data || {};
                    if (purchaseInput) purchaseInput.value = parseNumber(result.purchase_price).toFixed(2);
                    if (sellingInput) sellingInput.value = parseNumber(result.selling_price).toFixed(2);
                    if (marginInput) marginInput.value = parseNumber(result.margin_pct).toFixed(2);

                    if (rowKind === 'variation') {
                        removeMissingPricingRow(row);
                        setTimeout(function () {
                            refreshMissingPricingGroup(groupId);
                        }, 280);
                        return;
                    }

                    if (rowKind === 'group' && applyToVariations) {
                        document.querySelectorAll('[data-row-kind="variation"][data-parent-id="' + productId + '"]').forEach(function (variationRow) {
                            if (variationRow.parentNode) {
                                variationRow.parentNode.removeChild(variationRow);
                            }
                        });
                        removeMissingPricingRow(row);
                        return;
                    }

                    row.style.background = originalBg;
                    if (updateMissingPricingRowState(row)) {
                        removeMissingPricingRow(row);
                        return;
                    }
                } else {
                    if (row) row.style.background = originalBg;
                    alert((json && json.data && json.data.message) || json.data || t('Save error', 'Erreur lors de la sauvegarde', 'خطأ في الحفظ'));
                }

                updateMissingPricingCtaState();
            })
            .catch(function (err) {
                if (row) row.style.background = originalBg;
                alert(t('Request error', 'Erreur lors de la requête', 'خطأ في الطلب'));
            });
    };

    /* ─── Chart.js Sales/Profit chart ────────────────────────────────── */
    function initChart() {
        var el = document.getElementById('bizChart');
        if (!el) return;

        // If Chart.js didn't load, show a friendly fallback instead of blank space
        if (typeof Chart === 'undefined') {
            el.parentElement.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#6b7280;font-size:15px;">' +
                t('Chart library failed to load. Please refresh the page.', 'La bibliothèque de graphiques n\'a pas pu charger. Veuillez actualiser la page.', 'فشل تحميل مكتبة الرسوم البيانية. يرجى تحديث الصفحة.') +
                '</div>';
            return;
        }

        // Always build chart data — use empty arrays as last resort
        var chartData = cfg.chart || {};
        var labels = chartData.labels || [];
        var sales = chartData.sales || [];
        var profit = chartData.profit || [];
        var expenses = chartData.expenses || [];
        var netProfit = chartData.net_profit || [];

        // Check if ALL data is zero (no orders at all)
        var hasData = false;
        for (var i = 0; i < sales.length; i++) {
            if (sales[i] > 0 || profit[i] > 0 || expenses[i] > 0) { hasData = true; break; }
        }

        var ctx = el.getContext('2d');
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: t('Sales', 'Ventes', 'المبيعات'),
                        data: sales,
                        borderColor: '#2b9bf4',
                        backgroundColor: 'rgba(43,155,244,0.12)',
                        tension: 0.25, fill: true, pointRadius: 3, pointHoverRadius: 5
                    },
                    {
                        label: t('Gross profit', 'Profit brut', 'الربح الإجمالي'),
                        data: profit,
                        borderColor: '#10B981',
                        backgroundColor: 'rgba(16,185,129,0.10)',
                        tension: 0.25, fill: true, pointRadius: 3, pointHoverRadius: 5
                    },
                    {
                        label: t('Expenses', 'Dépenses', 'المصاريف'),
                        data: expenses,
                        borderColor: '#EF4444',
                        backgroundColor: 'rgba(239,68,68,0.10)',
                        tension: 0.25, fill: true, pointRadius: 3, pointHoverRadius: 5
                    },
                    {
                        label: t('Net profit', 'Profit net', 'صافي الربح'),
                        data: netProfit,
                        borderColor: '#8B5CF6',
                        backgroundColor: 'rgba(139,92,246,0.10)',
                        tension: 0.25, fill: true, pointRadius: 3, pointHoverRadius: 5
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: { mode: 'index', intersect: false },
                plugins: {
                    legend: { position: 'top' },
                    tooltip: {
                        callbacks: {
                            label: function (context) {
                                var v = context.parsed.y ?? context.raw;
                                try {
                                    return context.dataset.label + ': ' + new Intl.NumberFormat(undefined, { style: 'currency', currency: currency }).format(v);
                                } catch (e) { return context.dataset.label + ': ' + v; }
                            }
                        }
                    },
                    zoom: {
                        pan: { enabled: true, mode: 'x' },
                        zoom: { wheel: { enabled: true }, pinch: { enabled: true }, mode: 'x' }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function (v) {
                                try { return new Intl.NumberFormat(undefined, { style: 'currency', currency: currency }).format(v); }
                                catch (e) { return v; }
                            }
                        }
                    },
                    x: { ticks: { autoSkip: true, maxRotation: 0 } }
                },
                animation: { duration: 500 }
            }
        });

        // If no real data, show a helpful overlay message on top of the empty chart
        if (!hasData) {
            var overlay = document.createElement('div');
            overlay.style.cssText = 'position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);text-align:center;color:#9ca3af;pointer-events:none;z-index:2;';
            overlay.innerHTML = '<div style="font-size:36px;margin-bottom:8px;">📊</div>' +
                '<div style="font-size:15px;font-weight:600;">' + t('No sales data yet', 'Aucune donnée de vente', 'لا توجد بيانات مبيعات بعد') + '</div>' +
                '<div style="font-size:13px;margin-top:4px;">' + t('Data will appear here once orders are placed', 'Les données apparaîtront ici une fois les commandes passées', 'ستظهر البيانات هنا بعد تسجيل الطلبات') + '</div>';
            el.parentElement.style.position = 'relative';
            el.parentElement.appendChild(overlay);
        }
    }

    /* ─── Recent Orders scroll/toggle ────────────────────────────────── */
    function initRecentOrders() {
        var table = document.getElementById('biz-recent-orders-table');
        if (!table) return;
        var tbody = table.querySelector('tbody');
        if (!tbody) return;
        var rows = tbody.querySelectorAll('tr').length;
        var container = document.getElementById('biz-recent-orders-scroll');
        if (!container) return;
        var toggle = document.getElementById('biz-recent-toggle');

        if (rows > 10) {
            container.style.maxHeight = '360px';
            container.style.overflow = 'auto';
            if (toggle) { toggle.style.display = 'inline-flex'; toggle.textContent = t('Show all', 'Afficher tout', 'عرض الكل'); }
        } else {
            container.style.maxHeight = 'none';
            container.style.overflow = 'visible';
            if (toggle) toggle.style.display = 'none';
        }

        if (toggle) {
            var expanded = false;
            toggle.addEventListener('click', function () {
                if (!expanded) {
                    container.style.maxHeight = 'none';
                    container.style.overflow = 'visible';
                    toggle.textContent = t('Collapse', 'Réduire', 'طي');
                } else {
                    container.style.maxHeight = '360px';
                    container.style.overflow = 'auto';
                    toggle.textContent = t('Show all', 'Afficher tout', 'عرض الكل');
                }
                expanded = !expanded;
            });
        }

        var search = document.getElementById('biz-orders-search');
        if (search && tbody) {
            search.addEventListener('input', function () {
                var q = this.value.toLowerCase();
                tbody.querySelectorAll('tr').forEach(function (tr) {
                    tr.style.display = tr.cells[0].textContent.toLowerCase().includes(q) ? '' : 'none';
                });
            });
        }
    }

    /* ─── Product detail popup ───────────────────────────────────────── */
    window.openProductPopup = function (id) {
        if (!ajaxUrl()) { alert(t('Missing AJAX URL (admin-ajax.php).', 'URL AJAX manquante (admin-ajax.php).', 'رابط AJAX مفقود (admin-ajax.php).')); return; }
        if (!nonce()) { alert(t('Missing security token (nonce). Please refresh the page.', 'Jeton de sécurité (nonce) manquant. Veuillez actualiser la page.', 'رمز الأمان (nonce) مفقود. يرجى تحديث الصفحة.')); return; }

        var data = new URLSearchParams();
        data.append('action', 'bizmart_get_product_details');
        data.append('nonce', nonce());
        data.append('product_id', id);

        fetch(ajaxUrl(), { method: 'POST', body: data })
            .then(function (r) { return r.json(); })
            .then(function (json) {
                if (!json.success) { alert(json.data || t('Error', 'Erreur', 'خطأ')); return; }
                var d = json.data;
                document.getElementById('biz-product-popup-title').textContent = d.name;
                document.getElementById('biz-product-popup-content').innerHTML =
                    '<p><strong>ID:</strong> ' + d.id + '</p>' +
                    '<p><strong>SKU:</strong> ' + (d.sku || 'N/A') + '</p>' +
                    '<p><strong>' + t('Sale price', 'Prix de vente', 'سعر البيع') + ':</strong> ' + formatPrice(d.price) + '</p>' +
                    '<p><strong>' + t('Regular price', 'Prix régulier', 'السعر العادي') + ':</strong> ' + formatPrice(d.regular_price) + '</p>' +
                    (d.sale_price ? '<p><strong>' + t('Sale price (promo)', 'Prix promo', 'سعر التخفيض') + ':</strong> ' + formatPrice(d.sale_price) + '</p>' : '') +
                    '<p><strong>' + t('Purchase price', "Prix d'achat", 'سعر الشراء') + ':</strong> ' + (d.purchase_price ? formatPrice(d.purchase_price) : t('Not set', 'Non défini', 'غير محدد')) + '</p>' +
                    '<p><strong>Stock:</strong> ' + (d.stock_quantity !== null ? d.stock_quantity : 'N/A') + ' (' + d.stock_status + ')</p>' +
                    '<p><strong>Type:</strong> ' + d.type + '</p>' +
                    (d.image ? '<img src="' + d.image + '" style="max-width:100%;height:auto;margin-top:10px;">' : '') +
                    '<a id="biz-product-edit-link" href="' + d.edit_link + '" style="display:none;"></a>';
                document.getElementById('biz-product-popup').style.display = 'flex';
            })
            .catch(function () { alert(t('Request error', 'Erreur lors de la requête', 'خطأ في الطلب')); });
    };

    window.closeProductPopup = function () {
        document.getElementById('biz-product-popup').style.display = 'none';
    };

    /* ─── Purchase Price popup ───────────────────────────────────────── */
    var bizCurrentProductId = null;

    window.openPurchasePricePopup = function (id) {
        if (!ajaxUrl()) { alert(t('Missing AJAX URL (admin-ajax.php).', 'URL AJAX manquante (admin-ajax.php).', 'رابط AJAX مفقود (admin-ajax.php).')); return; }
        if (!nonce()) { alert(t('Missing security token (nonce). Please refresh the page.', 'Jeton de sécurité (nonce) manquant. Veuillez actualiser la page.', 'رمز الأمان (nonce) مفقود. يرجى تحديث الصفحة.')); return; }
        bizCurrentProductId = id;

        var data = new URLSearchParams();
        data.append('action', 'bizmart_get_purchase_price');
        data.append('nonce', nonce());
        data.append('product_id', id);

        fetch(ajaxUrl(), { method: 'POST', body: data })
            .then(function (r) { return r.json(); })
            .then(function (json) {
                if (!json.success) { alert(json.data || t('Error', 'Erreur', 'خطأ')); return; }
                document.getElementById('biz-price-popup-product-name').textContent = json.data.name || '';
                document.getElementById('biz-price-popup-value').value = json.data.purchase_price || '';
                document.getElementById('biz-price-popup').style.display = 'flex';
            })
            .catch(function () { alert(t('Request error', 'Erreur lors de la requête', 'خطأ في الطلب')); });
    };

    window.closePurchasePricePopup = function () {
        document.getElementById('biz-price-popup').style.display = 'none';
        bizCurrentProductId = null;
    };

    window.savePurchasePrice = function () {
        if (!ajaxUrl() || !nonce()) { alert(t('Missing AJAX configuration.', 'Configuration AJAX manquante.', 'إعدادات AJAX مفقودة.')); return; }

        var data = new URLSearchParams();
        data.append('action', 'bizmart_set_purchase_price');
        data.append('nonce', nonce());
        data.append('product_id', bizCurrentProductId);
        data.append('purchase_price', document.getElementById('biz-price-popup-value').value);

        fetch(ajaxUrl(), { method: 'POST', body: data })
            .then(function (r) { return r.json(); })
            .then(function (json) {
                if (json.success) {
                    document.getElementById('biz-price-popup').style.display = 'none';
                    setTimeout(function () { window.location.reload(); }, 300);
                } else {
                    alert(json.data || t('Save error', 'Erreur lors de la sauvegarde', 'خطأ في الحفظ'));
                }
            })
            .catch(function () { alert(t('Request error', 'Erreur lors de la requête', 'خطأ في الطلب')); });
    };

    /* ─── Missing-prices backdrop close ──────────────────────────────── */
    function initBackdropClose() {
        var popup = document.getElementById('biz-missing-prices-popup');
        if (popup) {
            popup.addEventListener('click', function (e) {
                if (e.target === this) closeMissingPricesPopup();
            });
        }
    }

    /* ─── Range tooltips for metric cards ───────────────────────────── */
    function initRangeTooltips() {
        document.querySelectorAll('.biz-card[data-range-tooltip]').forEach(function (card) {
            var text = card.getAttribute('data-range-tooltip') || '';
            if (!text) return;
            var icon = card.querySelector('.biz-range-icon');
            if (!icon) {
                icon = document.createElement('span');
                icon.className = 'biz-range-icon';
                icon.setAttribute('aria-hidden', 'true');
                icon.textContent = 'i';
                var lbl = card.querySelector('.biz-label');
                if (lbl) lbl.appendChild(icon);
                else card.insertBefore(icon, card.firstChild);
            }
            icon.title = text;
            icon.setAttribute('aria-label', text);
        });
    }

    /* ─── Boot everything on DOMContentLoaded ────────────────────────── */
    document.addEventListener('DOMContentLoaded', function () {
        initComparePanel();
        initChart();
        initRecentOrders();
        initAlertPopups();
        initBackdropClose();
        initMissingPricingRows();
        initRangeTooltips();
    });

    /* ─── Price History Modal Scripts ─── */
(function(){
    // v3.0 Price History Modal
    var phChart = null;
    var phProductId = 0;
    var phOffset = 0;
    var cfg = window.BizmartDashConfig || {};
    var fmtP = function(v) {
        if (typeof wc_price_format !== 'undefined') return wc_price_format(v);
        var num = parseFloat(v).toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2});
        return num + ' ' + (cfg.currency || '');
    };

    window.openPriceHistoryModal = function(productId) {
        phProductId = productId;
        phOffset = 0;
        document.getElementById('biz-ph-tbody').innerHTML = '';
        document.getElementById('biz-price-history-modal').style.display = 'flex';
        document.body.style.overflow = 'hidden';
        loadPriceHistoryData();
        loadPriceChart();
        loadSupplierCompare();
    };

    window.closePriceHistoryModal = function() {
        document.getElementById('biz-price-history-modal').style.display = 'none';
        document.body.style.overflow = '';
        if (phChart) { phChart.destroy(); phChart = null; }
    };

    function loadPriceHistoryData() {
        jQuery.post(cfg.ajax_url, {
            action: 'bizmart_get_product_price_history',
            nonce: cfg.nonce,
            product_id: phProductId,
            limit: 50,
            offset: phOffset
        }, function(res) {
            if (!res.success) return;
            var d = res.data;
            document.getElementById('biz-ph-title').innerHTML = '📊 ' + (d.product_name || 'Price History');
            document.getElementById('biz-ph-wac').textContent = d.wac > 0 ? fmtP(d.wac) : '—';
            document.getElementById('biz-ph-last-pp').textContent = d.last.purchase_price > 0 ? fmtP(d.last.purchase_price) : '—';
            document.getElementById('biz-ph-last-sp').textContent = d.last.selling_price > 0 ? fmtP(d.last.selling_price) : '—';

            var pp = parseFloat(d.last.purchase_price), sp = parseFloat(d.last.selling_price);
            if (sp > 0 && pp > 0) {
                var m = ((sp - pp) / sp * 100).toFixed(1);
                document.getElementById('biz-ph-margin').textContent = m + '%';
                document.getElementById('biz-ph-margin').style.color = m < 10 ? '#dc2626' : '#581c87';
            } else {
                document.getElementById('biz-ph-margin').textContent = '—';
            }

            d.history.forEach(function(h) { appendPriceRow(h); });
            phOffset += d.history.length;
            document.getElementById('biz-ph-load-more').style.display = d.history.length >= 50 ? 'block' : 'none';
        });
    }

    window.loadMorePriceHistory = function() { loadPriceHistoryData(); };

    function appendPriceRow(h) {
        var tr = document.createElement('tr');
        var marginColor = (h.margin_pct !== null && h.margin_pct < 10) ? '#dc2626' : '#059669';
        tr.innerHTML = '<td>' + (h.created_at ? h.created_at.substring(0, 10) : '—') + '</td>'
            + '<td style="font-weight:600;">' + fmtP(h.purchase_price) + '</td>'
            + '<td>' + fmtP(h.selling_price) + '</td>'
            + '<td><span style="color:' + marginColor + '; font-weight:600;">' + (h.margin_pct !== null ? h.margin_pct + '%' : '—') + '</span></td>'
            + '<td>' + (h.supplier_name || '—') + '</td>'
            + '<td>' + (h.quantity || 1) + '</td>'
            + '<td><span style="background:#e5e7eb; padding:2px 6px; border-radius:4px; font-size:11px;">' + (h.source || 'invoice') + '</span></td>';
        document.getElementById('biz-ph-tbody').appendChild(tr);
    }

    function loadPriceChart() {
        jQuery.post(cfg.ajax_url, {
            action: 'bizmart_get_product_price_chart',
            nonce: cfg.nonce,
            product_id: phProductId
        }, function(res) {
            if (!res.success || !res.data.labels.length) return;
            var ctx = document.getElementById('biz-ph-chart').getContext('2d');
            if (phChart) phChart.destroy();
            phChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: res.data.labels,
                    datasets: [
                        { label: '<?php echo esc_js(bizmart_text("Purchase Price", "Prix d\'Achat", "سعر الشراء")); ?>', data: res.data.pp, borderColor: '#3b82f6', backgroundColor: 'rgba(59,130,246,0.1)', fill: true, tension: 0.3, yAxisID: 'y' },
                        { label: '<?php echo esc_js(bizmart_text("Selling Price", "Prix de Vente", "سعر البيع")); ?>', data: res.data.sp, borderColor: '#10b981', backgroundColor: 'rgba(16,185,129,0.1)', fill: true, tension: 0.3, yAxisID: 'y' },
                        { label: '<?php echo esc_js(bizmart_text("Margin %", "Marge %", "الهامش %")); ?>', data: res.data.margin, borderColor: '#f59e0b', borderDash: [5,5], fill: false, tension: 0.3, yAxisID: 'y1' }
                    ]
                },
                options: {
                    responsive: true, maintainAspectRatio: false,
                    interaction: { mode: 'index', intersect: false },
                    scales: {
                        y: { position: 'left', title: { display: true, text: '<?php echo esc_js(bizmart_text("Price", "Prix", "السعر")); ?>' } },
                        y1: { position: 'right', grid: { drawOnChartArea: false }, title: { display: true, text: '%' }, min: 0 }
                    },
                    plugins: { legend: { position: 'top' } }
                }
            });
        });
    }

    function loadSupplierCompare() {
        jQuery.post(cfg.ajax_url, {
            action: 'bizmart_get_supplier_compare',
            nonce: cfg.nonce,
            product_id: phProductId
        }, function(res) {
            var wrap = document.getElementById('biz-ph-suppliers');
            var body = document.getElementById('biz-ph-suppliers-body');
            if (!res.success || !res.data.length) { wrap.style.display = 'none'; return; }
            wrap.style.display = 'block';
            var html = '<table class="biz-table" style="font-size:13px;"><thead><tr>'
                + '<th><?php echo esc_js(bizmart_text("Supplier", "Fournisseur", "المورد")); ?></th>'
                + '<th><?php echo esc_js(bizmart_text("Avg Price", "Prix Moyen", "متوسط السعر")); ?></th>'
                + '<th><?php echo esc_js(bizmart_text("Min", "Min", "أدنى")); ?></th>'
                + '<th><?php echo esc_js(bizmart_text("Max", "Max", "أقصى")); ?></th>'
                + '<th><?php echo esc_js(bizmart_text("Orders", "Commandes", "طلبات")); ?></th>'
                + '<th><?php echo esc_js(bizmart_text("Last Order", "Dernière Commande", "آخر طلب")); ?></th>'
                + '</tr></thead><tbody>';
            res.data.forEach(function(s, i) {
                var badge = i === 0 ? ' <span style="background:#dcfce7; color:#166534; padding:2px 6px; border-radius:4px; font-size:10px;">🥇 Best</span>' : '';
                html += '<tr><td style="font-weight:600;">' + s.supplier_name + badge + '</td>'
                    + '<td>' + fmtP(s.avg_price) + '</td>'
                    + '<td>' + fmtP(s.min_price) + '</td>'
                    + '<td>' + fmtP(s.max_price) + '</td>'
                    + '<td>' + s.order_count + '</td>'
                    + '<td>' + (s.last_order ? s.last_order.substring(0, 10) : '—') + '</td></tr>';
            });
            html += '</tbody></table>';
            body.innerHTML = html;
        });
    }

    // Close on backdrop click
    document.getElementById('biz-price-history-modal').addEventListener('click', function(e) {
        if (e.target === this) closePriceHistoryModal();
    });
})();

})();
