/**
 * Business Intelligence dashboard — live ERP data + application settings.
 */
(function () {
    'use strict';

    const API = '/api/v1/bi';
    let charts = {};
    let trendPeriodDays = 30;

    const categoryColors = {
        quantity: '#3498db', length: '#2ecc71', area: '#9b59b6', volume: '#1abc9c',
        weight: '#e67e22', temperature: '#e74c3c', pressure: '#34495e', speed: '#16a085',
        time: '#8e44ad', angle: '#d35400', energy: '#c0392b', power: '#f39c12', nautical: '#2980b9',
    };

    function fmtMoney(n) {
        if (typeof formatCurrency === 'function') return formatCurrency(Number(n) || 0);
        return (Number(n) || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    }

    function fmtPct(n) {
        const v = Number(n) || 0;
        return (v >= 0 ? '+' : '') + v.toFixed(1) + '%';
    }

    async function apiGet(path) {
        const res = await fetch(API + path);
        const body = await res.json().catch(() => ({}));
        if (!res.ok) throw new Error(body.detail || body.message || res.statusText);
        return body;
    }

    function destroyChart(key) {
        if (charts[key]) {
            charts[key].destroy();
            charts[key] = null;
        }
    }

    async function loadOverviewKPIs() {
        const result = await apiGet('/dashboard/overview');
        if (!result.success) return;
        const data = result.data;
        document.getElementById('totalProducts').textContent = (data.total_products || 0).toLocaleString();
        document.getElementById('totalUOMs').textContent = (data.total_active_uoms || 0).toLocaleString();
        document.getElementById('totalCategories').textContent = Object.keys(data.products_by_category || {}).length;
        const utilization = data.total_active_uoms > 0
            ? ((data.total_products / data.total_active_uoms) * 100).toFixed(1) : 0;
        document.getElementById('avgUtilization').textContent = utilization + '%';
        renderProductsByCategoryChart(data.products_by_category || {});
        renderTopUnitsChart(data.top_used_uoms || []);
    }

    function renderProductsByCategoryChart(categoryData) {
        destroyChart('productsByCategory');
        const ctx = document.getElementById('productsByCategoryChart').getContext('2d');
        const labels = Object.keys(categoryData);
        charts.productsByCategory = new Chart(ctx, {
            type: 'pie',
            data: {
                labels,
                datasets: [{
                    data: Object.values(categoryData),
                    backgroundColor: labels.map(c => categoryColors[c] || '#95a5a6'),
                }],
            },
            options: { responsive: true, plugins: { legend: { position: 'bottom' } } },
        });
    }

    function renderTopUnitsChart(topUoms) {
        destroyChart('topUnits');
        const ctx = document.getElementById('topUnitsChart').getContext('2d');
        charts.topUnits = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: topUoms.map(u => u.unit_name),
                datasets: [{
                    label: 'Products',
                    data: topUoms.map(u => u.product_count),
                    backgroundColor: topUoms.map(u => categoryColors[u.category] || '#3498db'),
                }],
            },
            options: {
                responsive: true,
                indexAxis: 'y',
                plugins: { legend: { display: false } },
            },
        });
    }

    async function loadCategoryDistribution() {
        const result = await apiGet('/uom/category-distribution');
        if (!result.success) return;
        const data = result.data || [];
        renderCategoryDistributionChart(data);
        const tbody = document.getElementById('distributionTableBody');
        if (!data.length) {
            tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">No UOM data yet</td></tr>';
            return;
        }
        tbody.innerHTML = data.map(row => `
            <tr>
                <td><span class="category-badge badge-${row.category || 'quantity'}">${row.category || '—'}</span></td>
                <td>${row.subcategory || '—'}</td>
                <td>${row.unit_count}</td>
                <td>${row.product_count}</td>
                <td>${row.utilization_rate}%</td>
            </tr>`).join('');
    }

    function renderCategoryDistributionChart(data) {
        destroyChart('categoryDistribution');
        const categories = [...new Set(data.map(d => d.category))];
        const ctx = document.getElementById('categoryDistributionChart').getContext('2d');
        charts.categoryDistribution = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: categories,
                datasets: [
                    { label: 'Units', data: categories.map(c => data.filter(d => d.category === c).reduce((s, x) => s + x.unit_count, 0)), backgroundColor: '#3498db' },
                    { label: 'Products', data: categories.map(c => data.filter(d => d.category === c).reduce((s, x) => s + x.product_count, 0)), backgroundColor: '#2ecc71' },
                ],
            },
            options: { responsive: true, scales: { y: { beginAtZero: true } } },
        });
    }

    async function loadPrecisionAnalysis() {
        const result = await apiGet('/uom/precision-analysis');
        if (!result.success) return;
        const data = result.data || [];
        destroyChart('precision');
        const ctx = document.getElementById('precisionChart').getContext('2d');
        const grouped = {};
        data.forEach(r => {
            grouped[r.category] = (grouped[r.category] || 0) + r.product_count;
        });
        charts.precision = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: Object.keys(grouped),
                datasets: [{ data: Object.values(grouped), backgroundColor: Object.keys(grouped).map(c => categoryColors[c] || '#95a5a6') }],
            },
            options: { responsive: true, plugins: { legend: { position: 'bottom' } } },
        });
    }

    async function loadInventoryValue() {
        const result = await apiGet('/inventory/category-value');
        if (!result.success) return;
        const data = result.data || [];
        destroyChart('inventoryValue');
        const ctx = document.getElementById('inventoryValueChart').getContext('2d');
        charts.inventoryValue = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: data.map(d => d.category),
                datasets: [{
                    label: 'Stock value',
                    data: data.map(d => d.total_value),
                    backgroundColor: data.map(d => categoryColors[d.category] || '#3498db'),
                }],
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: { callback: v => fmtMoney(v) },
                    },
                },
            },
        });
    }

    async function loadSystemVsCustom() {
        const result = await apiGet('/uom/system-vs-custom');
        if (!result.success) return;
        renderSystemVsCustomChart(result.data || []);
    }

    function renderSystemVsCustomChart(data) {
        destroyChart('systemVsCustom');
        let systemCount = 0, customCount = 0;
        data.forEach(item => {
            if (item.unit_type === 'System') systemCount += item.unit_count;
            else customCount += item.unit_count;
        });
        const ctx = document.getElementById('systemVsCustomChart').getContext('2d');
        charts.systemVsCustom = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: ['System Units', 'Custom Units'],
                datasets: [{ data: [systemCount, customCount], backgroundColor: ['#3498db', '#e67e22'] }],
            },
            options: { responsive: true, plugins: { legend: { position: 'bottom' } } },
        });
    }

    async function loadExecutiveSummary(days) {
        const result = await apiGet('/analytics/executive-summary?days=' + days);
        if (!result.success) return;
        const d = result.data;
        document.getElementById('growthRate').textContent = fmtPct(d.growth_rate);
        document.getElementById('avgDailySales').textContent = fmtMoney(d.avg_daily_sales);
        document.getElementById('lowStockCount').textContent = String(d.low_stock_count);
        document.getElementById('topCategory').textContent = d.top_category || '—';
        document.getElementById('totalRevenue').textContent = fmtMoney(d.total_revenue);
        document.getElementById('profitMargin').textContent = d.profit_margin + '%';
    }

    async function loadSalesTrend(days) {
        const result = await apiGet('/analytics/sales-trend?days=' + days);
        if (!result.success) return;
        const d = result.data;
        destroyChart('historicalTrends');
        const ctx = document.getElementById('historicalTrendsChart').getContext('2d');
        charts.historicalTrends = new Chart(ctx, {
            type: 'line',
            data: {
                labels: d.labels,
                datasets: [
                    { label: 'Sales revenue', data: d.revenue, borderColor: '#2ecc71', backgroundColor: 'rgba(46,204,113,0.1)', yAxisID: 'y', fill: true, tension: 0.3 },
                    { label: 'Purchases', data: d.purchases, borderColor: '#e74c3c', backgroundColor: 'rgba(231,76,60,0.08)', yAxisID: 'y', fill: true, tension: 0.3 },
                ],
            },
            options: {
                responsive: true,
                interaction: { mode: 'index', intersect: false },
                scales: {
                    y: { beginAtZero: true, ticks: { callback: v => fmtMoney(v) } },
                },
            },
        });
    }

    async function loadDemandForecast() {
        const result = await apiGet('/analytics/demand-forecast');
        if (!result.success) return;
        const d = result.data;
        destroyChart('demandForecast');
        const ctx = document.getElementById('demandForecastChart').getContext('2d');
        const labels = [...d.history_labels.slice(-14), ...d.forecast_labels];
        const actual = [...d.history_units.slice(-14), ...Array(d.forecast_labels.length).fill(null)];
        const forecast = [...Array(14).fill(null), ...d.forecast_units];
        charts.demandForecast = new Chart(ctx, {
            type: 'line',
            data: {
                labels,
                datasets: [
                    { label: 'Units sold (history)', data: actual, borderColor: '#2ecc71', fill: true, backgroundColor: 'rgba(46,204,113,0.1)' },
                    { label: 'Forecast (7-day avg)', data: forecast, borderColor: '#3498db', borderDash: [5, 5], fill: false },
                ],
            },
            options: { responsive: true, scales: { y: { beginAtZero: true } } },
        });
    }

    async function loadInventoryOptimization() {
        const result = await apiGet('/analytics/inventory-alerts?limit=8');
        if (!result.success) return;
        const items = result.data || [];
        destroyChart('inventoryOptimization');
        const ctx = document.getElementById('inventoryOptimizationChart').getContext('2d');
        if (!items.length) {
            charts.inventoryOptimization = new Chart(ctx, {
                type: 'bar',
                data: { labels: ['No alerts'], datasets: [{ label: 'Stock', data: [0], backgroundColor: '#95a5a6' }] },
                options: { responsive: true },
            });
            return;
        }
        charts.inventoryOptimization = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: items.map(i => (i.name || i.sku).substring(0, 20)),
                datasets: [
                    { label: 'Current', data: items.map(i => i.current_stock), backgroundColor: '#3498db' },
                    { label: 'Optimal', data: items.map(i => i.optimal_stock), backgroundColor: '#2ecc71' },
                    { label: 'Reorder', data: items.map(i => i.reorder_point), type: 'line', borderColor: '#e74c3c', fill: false },
                ],
            },
            options: { responsive: true, scales: { y: { beginAtZero: true } } },
        });
    }

    async function loadSupplyChain() {
        const result = await apiGet('/analytics/supply-chain?days=90');
        if (!result.success) return;
        const d = result.data;
        document.getElementById('onTimeDelivery').textContent =
            d.on_time_delivery_pct != null ? d.on_time_delivery_pct + '%' : 'N/A';
        document.getElementById('avgLeadTime').textContent =
            d.avg_lead_time_days != null ? d.avg_lead_time_days + ' days' : 'N/A';
        destroyChart('supplyChain');
        const suppliers = d.suppliers || [];
        const ctx = document.getElementById('supplyChainChart').getContext('2d');
        if (!suppliers.length) {
            charts.supplyChain = new Chart(ctx, {
                type: 'bar',
                data: { labels: ['No purchase data'], datasets: [{ data: [0], backgroundColor: '#95a5a6' }] },
                options: { responsive: true },
            });
            return;
        }
        charts.supplyChain = new Chart(ctx, {
            type: 'radar',
            data: {
                labels: suppliers.map(s => s.name.substring(0, 18)),
                datasets: [{ label: 'Spend score', data: suppliers.map(s => s.score), backgroundColor: 'rgba(52,152,219,0.2)', borderColor: '#3498db' }],
            },
            options: { responsive: true, scales: { r: { beginAtZero: true, max: 100 } } },
        });
    }

    async function loadFinancialMonthly() {
        const result = await apiGet('/analytics/financial-monthly?months=6');
        if (!result.success) return;
        const d = result.data;
        destroyChart('financialPerformance');
        const ctx = document.getElementById('financialPerformanceChart').getContext('2d');
        charts.financialPerformance = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: d.labels,
                datasets: [
                    { label: 'Revenue', data: d.revenue, backgroundColor: '#2ecc71' },
                    { label: 'Purchases', data: d.expenses, backgroundColor: '#e74c3c' },
                    { label: 'Gross surplus', data: d.profit, backgroundColor: '#3498db' },
                ],
            },
            options: {
                responsive: true,
                scales: { y: { ticks: { callback: v => fmtMoney(v) } } },
            },
        });
    }

    async function loadInsights(days) {
        const result = await apiGet('/analytics/insights?days=' + days);
        const panel = document.getElementById('insightsPanel');
        if (!result.success || !panel) return;
        const levelClass = { success: 'success', warning: 'warning', info: 'info', primary: 'primary' };
        panel.innerHTML = (result.data || []).map(i => `
            <div class="alert alert-${levelClass[i.level] || 'info'} border-0 mb-2">
                <strong>${i.title}:</strong> ${i.message}
            </div>`).join('');
    }

    async function loadDataStatus() {
        const result = await apiGet('/analytics/data-status');
        if (!result.success) return;
        const d = result.data;
        document.getElementById('dataSyncStatus').textContent = d.sync_status === 'live' ? 'Live' : d.sync_status;
        document.getElementById('dataRecordCount').textContent = (d.records_processed || 0).toLocaleString();
        const lu = d.last_update ? new Date(d.last_update).toLocaleString() : 'No transactions yet';
        document.getElementById('dataLastUpdate').textContent = lu;
        document.getElementById('dataQuality').textContent = (d.data_quality_pct || 0) + '%';
    }

    async function loadAdvancedAnalytics(days) {
        await Promise.all([
            loadExecutiveSummary(days),
            loadSalesTrend(days),
            loadDemandForecast(),
            loadInventoryOptimization(),
            loadSupplyChain(),
            loadFinancialMonthly(),
            loadInsights(days),
            loadDataStatus(),
        ]);
    }

    async function initDashboard() {
        try {
            if (window.settingsLoader) await window.settingsLoader.init();
            await Promise.all([
                loadOverviewKPIs(),
                loadCategoryDistribution(),
                loadPrecisionAnalysis(),
                loadInventoryValue(),
                loadSystemVsCustom(),
            ]);
            await loadAdvancedAnalytics(trendPeriodDays);
        } catch (err) {
            console.error('[BI] Dashboard load failed:', err);
        }
    }

    window.changeTrendPeriod = function (period) {
        const map = { '7d': 7, '30d': 30, '90d': 90, '1y': 365 };
        trendPeriodDays = map[period] || 30;
        document.querySelectorAll('.trend-period-btn').forEach(btn => {
            btn.classList.toggle('active', btn.dataset.period === period);
        });
        loadAdvancedAnalytics(trendPeriodDays);
    };

    window.refreshData = function () {
        initDashboard().then(() => {
            const el = document.getElementById('refreshToast');
            if (el) el.classList.remove('d-none');
            setTimeout(() => el && el.classList.add('d-none'), 3000);
        });
    };

    window.showTrendAnalysis = () => changeTrendPeriod('30d');
    window.showPredictiveAnalytics = () => document.getElementById('demandForecastChart')?.scrollIntoView({ behavior: 'smooth' });
    window.showSupplyChainInsights = () => document.getElementById('supplyChainChart')?.scrollIntoView({ behavior: 'smooth' });
    window.showFinancialPlanning = () => document.getElementById('financialPerformanceChart')?.scrollIntoView({ behavior: 'smooth' });
    window.exportReport = () => alert('Export: use your browser Print → Save as PDF on this dashboard for now.');
    window.scheduleReport = () => alert('Scheduled reports are not configured yet.');

    document.addEventListener('DOMContentLoaded', initDashboard);
})();
