/**
 * 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 () {
        var popup = document.getElementById('biz-missing-prices-popup');
        if (popup) {
            popup.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }
    };

    window.closeMissingPricesPopup = function () {
        var popup = document.getElementById('biz-missing-prices-popup');
        if (popup) {
            popup.style.display = 'none';
            document.body.style.overflow = '';
        }
    };

    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 input = document.getElementById('biz-price-input-' + productId);
        if (!input) return;

        var price = input.value.trim();
        if (price === '' || isNaN(parseFloat(price)) || parseFloat(price) < 0) {
            alert(t('Please enter a valid price', 'Veuillez entrer un prix valide', 'يرجى إدخال سعر صالح'));
            input.focus();
            return;
        }

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

        var row = document.getElementById('biz-missing-row-' + productId);
        var originalBg = row ? row.style.background : '';
        if (row) row.style.background = '#fef9c3';

        // Check if "Apply to all variations" is checked for variable products
        var applyAllCheckbox = document.getElementById('biz-apply-all-vars-' + productId);
        var applyToVariations = applyAllCheckbox && applyAllCheckbox.checked;

        var data = new URLSearchParams();
        data.append('action', 'bizmart_set_purchase_price');
        data.append('nonce', nonce());
        data.append('product_id', productId);
        data.append('purchase_price', price);
        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) {
                    input.disabled = true;
                    // If applied to all variations, also remove their sub-rows
                    if (applyToVariations) {
                        var subRows = document.querySelectorAll('.biz-var-subrow-' + productId);
                        subRows.forEach(function(r) {
                            r.style.transition = 'opacity 0.3s ease';
                            r.style.opacity = '0';
                            setTimeout(function() { r.remove(); }, 350);
                        });
                    }
                    if (row) {
                        row.style.transition = 'transform 0.4s ease, opacity 0.4s ease';
                        row.style.transform = 'translateX(-20px)';
                        row.style.opacity = '0';
                        setTimeout(function () {
                            row.remove();
                            var tbody = document.getElementById('biz-missing-prices-tbody');
                            if (tbody && tbody.children.length === 0) {
                                setTimeout(function () { window.location.reload(); }, 300);
                            }
                        }, 450);
                    }
                } else {
                    if (row) row.style.background = originalBg;
                    alert(json.data || t('Save error', 'Erreur lors de la sauvegarde', 'خطأ في الحفظ'));
                }
            })
            .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 && labels.length > 0) {
            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() {
        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 getUrlParam = function (name) {
            var params = new URLSearchParams(window.location.search);
            return params.get(name);
        };

        var fmtDate = function (d) {
            try {
                var dt = new Date(d + 'T00:00:00');
                if (isNaN(dt)) return d;
                var locale = BizmartDashboard.adminLang || undefined;
                return new Intl.DateTimeFormat(locale, { day: '2-digit', month: '2-digit', year: 'numeric' }).format(dt);
            } catch (e) { return d; }
        };

        var makeText = function () {
            var start = mainStart && mainStart.value ? mainStart.value : null;
            var end = mainEnd && mainEnd.value ? mainEnd.value : null;
            var template = t('Data range: %s → %s', 'Plage de données : %s → %s', 'نطاق البيانات: %s → %s');

            if (start && end) {
                return template.replace('%s', fmtDate(start)).replace('%s', fmtDate(end));
            }

            // Fallback to quick range param
            var r = getUrlParam('range');
            if (r === '7') return t('Last 7 days', '7 derniers jours', 'آخر 7 أيام');
            if (r === '30') return t('Last 30 days', '30 derniers jours', 'آخر 30 يومًا');
            if (r === 'all') return t('Since the beginning', 'Depuis le début', 'منذ البداية');

            // Last fallback: show explicit start/end from server-rendered inputs (if present elsewhere)
            if (start || end) {
                return template.replace('%s', start || 'N/A').replace('%s', end || 'N/A');
            }
            return t('Date range not specified', 'Plage non spécifiée', 'نطاق التاريخ غير محدد');
        };

        var update = function () {
            var text = makeText();
            document.querySelectorAll('.biz-card').forEach(function (card) {
                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);
            });
        };

        // Wire up changes
        update();
        if (mainStart) mainStart.addEventListener('change', update);
        if (mainEnd) mainEnd.addEventListener('change', update);
        // Also run update on popstate (back/forward) or URL changes
        window.addEventListener('popstate', update);
    }

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