let dashboardCharts = {};
let dashboardData = {};

$(function () {
    initDashboard();
    setInterval(function () { loadDashboardData(); updateLastUpdateTime(); }, 60000);
});

function initDashboard() {
    bindEvents();
    loadDashboardData();
}

function bindEvents() {
    $('#activityPeriod').on('change', loadDashboardData);
    $('#dashboardSearch, #dashboardFilter').on('keyup change', filterFleetTable);
    $('#btnRefreshDashboard').on('click', function () { $('#btnRefreshDashboard').html('<span class="spinner-border spinner-border-sm me-1"></span>Loading...').prop('disabled', true); loadDashboardData(); });
    $('#btnViewAllAlerts').on('click', function () { showDetailsCanvas('alerts'); });
    $('#btnViewAllActivity').on('click', function () { showDetailsCanvas('activity'); });
}

function loadDashboardData() {
    var period = $('#activityPeriod').val() || 30;
    $.get('api/dashboard.php', { action: 'init', period: period }, function (res) {
        if (res.status !== 'success') { showLoadError(); return; }
        dashboardData = res.data || {};
        updateDashboardKPIs();
        updateLastUpdateTime();
    }).fail(function () { showLoadError(); })
    .always(function () { $('#btnRefreshDashboard').html('<i class="bi bi-arrow-clockwise me-1"></i>Refresh').prop('disabled', false); });
}

function showLoadError() {
    $('#alertsList').html('<div class="text-danger small"><i class="bi bi-exclamation-triangle me-1"></i>Could not load data</div>');
    $('#activityFeed').html('<div class="text-danger small"><i class="bi bi-exclamation-triangle me-1"></i>Could not load activity</div>');
    $('#fleetTableBody').html('<tr><td colspan="8" class="text-center text-danger py-4"><i class="bi bi-exclamation-triangle me-1"></i>Could not load fleet data</td></tr>');
}

function updateDashboardKPIs() {
    var stats = dashboardData.fleet_stats || {};
    var kpis = dashboardData.kpis || {};

    $('#statActiveVehicles').text(stats.active_vehicles || 0);
    $('#statActiveDrivers').text(stats.active_drivers || 0);
    $('#statInWorkshop').text(stats.in_workshop || 0);
    $('#statExpiring').text(stats.expiring_docs || 0);
    $('#statPendingApprovals').text(stats.pending_approvals || 0);
    $('#statMaintenanceJobs').text(stats.maintenance_complaints || 0);

    $('#kpiUtilization').text(kpis.utilization + '%');
    $('#utilizationBar').css('width', kpis.utilization + '%');
    $('#kpiHealth').text(kpis.health + '%');
    $('#healthBar').css('width', kpis.health + '%');
    $('#kpiCompliance').text(kpis.compliance + '%');
    $('#complianceBar').css('width', kpis.compliance + '%');
    var wf = kpis.workflow || 0;
    $('#kpiWorkflow').text(wf);
    $('#workflowBar').css('width', Math.min(wf * 5, 100) + '%');

    renderAlerts(dashboardData.alerts);
    renderActivityFeed(dashboardData.activity_feed);
    renderFleetTable(dashboardData.fleet_table);
    updateCharts();
}

function updateCharts() {
    updateActivityTimelineChart();
    updateActionBucketChart();
    updateMaintenancePipelineChart();
    updateFuelSpendChart();
}

function updateActivityTimelineChart() {
    var data = dashboardData.activity_timeline || [];
    var ctx = document.getElementById('activityTimelineChart');
    if (!ctx) return;
    if (dashboardCharts.activityTimeline) dashboardCharts.activityTimeline.destroy();
    dashboardCharts.activityTimeline = new Chart(ctx, {
        type: 'line',
        data: {
            labels: data.map(function (d) { return d.date || ''; }),
            datasets: [{
                label: 'Daily Activities',
                data: data.map(function (d) { return d.count || 0; }),
                borderColor: '#0d6efd',
                backgroundColor: 'rgba(13,110,253,0.1)',
                borderWidth: 2, fill: true, tension: 0.4,
                pointStyle: 'circle', pointRadius: 4,
                pointBackgroundColor: '#0d6efd', pointBorderColor: '#fff', pointBorderWidth: 2
            }]
        },
        options: {
            responsive: true, maintainAspectRatio: true,
            plugins: { legend: { display: false } },
            scales: { y: { beginAtZero: true, ticks: { stepSize: 5 } } },
            interaction: { intersect: false, mode: 'index' }
        }
    });
}

function updateActionBucketChart() {
    var buckets = dashboardData.action_buckets || {};
    var labels = Object.keys(buckets);
    var values = Object.values(buckets);
    var colors = { 'Fuel':'#198754','Maintenance':'#dc3545','Driver':'#0d6efd','Vehicle':'#ffc107','Compliance':'#6f42c1','Other':'#0dcaf0' };
    var ctx = document.getElementById('actionTypeChart');
    if (!ctx) return;
    if (dashboardCharts.actionType) dashboardCharts.actionType.destroy();
    dashboardCharts.actionType = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: labels,
            datasets: [{ data: values, backgroundColor: labels.map(function (l) { return colors[l] || '#adb5bd'; }) }]
        },
        options: { responsive: true, maintainAspectRatio: true, plugins: { legend: { position: 'bottom' } } }
    });
}

function updateMaintenancePipelineChart() {
    var stages = (dashboardData.maintenance || {}).stages || {};
    var labels = Object.keys(stages);
    var values = Object.values(stages);
    var ctx = document.getElementById('maintenancePipelineChart');
    if (!ctx) return;
    if (dashboardCharts.maintenancePipeline) dashboardCharts.maintenancePipeline.destroy();
    dashboardCharts.maintenancePipeline = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: 'Jobs by Stage',
                data: values,
                backgroundColor: '#0d6efd',
                borderRadius: 6, borderSkipped: false
            }]
        },
        options: { indexAxis: 'y', responsive: true, maintainAspectRatio: true, plugins: { legend: { display: false } }, scales: { x: { beginAtZero: true } } }
    });
}

function updateFuelSpendChart() {
    var monthly = (dashboardData.fuel || {}).monthly || {};
    var labels = Object.keys(monthly);
    var values = Object.values(monthly);
    var ctx = document.getElementById('fuelSpendChart');
    if (!ctx) return;
    if (dashboardCharts.fuelSpend) dashboardCharts.fuelSpend.destroy();
    dashboardCharts.fuelSpend = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: 'Monthly Fuel Spend',
                data: values,
                borderColor: '#198754',
                backgroundColor: 'rgba(25,135,84,0.1)',
                borderWidth: 2, fill: true, tension: 0.4
            }]
        },
        options: { responsive: true, maintainAspectRatio: true, plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true } } }
    });
}

function renderAlerts(alerts) {
    var list = (alerts || []).slice(0, 5);
    var html = '';
    if (!list.length) { html = '<div class="text-muted small">No alerts at this moment</div>'; }
    else {
        list.forEach(function (a) {
            var badgeClass = a.severity === 'critical' ? 'bg-danger' : a.severity === 'warning' ? 'bg-warning' : 'bg-info';
            html += '<div class="alert-item mb-2 pb-2 border-bottom"><div class="d-flex justify-content-between align-items-start"><div class="flex-grow-1"><div class="fw-semibold small">' + esc(a.title || '-') + '</div><div class="text-muted small">' + esc(a.description || '-') + '</div><div class="small text-muted mt-1">Due: ' + fmtDate(a.due_date) + '</div></div><span class="badge ' + badgeClass + '">' + (a.severity || 'info') + '</span></div></div>';
        });
    }
    $('#alertsList').html(html);
}

function renderActivityFeed(feed) {
    var list = (feed || []).slice(0, 8);
    var html = '';
    if (!list.length) { html = '<div class="text-muted small">No recent activity</div>'; }
    else {
        list.forEach(function (a) {
            html += '<div class="activity-item mb-3"><div class="d-flex gap-3"><div class="activity-icon" style="font-size:1.2rem;">' + getActivityIcon(a.action || '') + '</div><div class="flex-grow-1 min-width-0"><div class="fw-semibold small">' + esc(a.title || '-') + '</div><div class="text-muted small">' + esc(a.description || '-') + '</div><div class="text-muted small mt-1">' + fmtRelTime(a.timestamp) + '</div></div></div></div>';
        });
    }
    $('#activityFeed').html(html);
}

function renderFleetTable(vehicles) {
    var search = ($('#dashboardSearch').val() || '').toLowerCase();
    var filter = $('#dashboardFilter').val();
    var filtered = (vehicles || []).filter(function (v) {
        var ms = !search || ((v.plate_number || '').toLowerCase().includes(search) || (v.vehicle_model || '').toLowerCase().includes(search) || (v.driver_name || '').toLowerCase().includes(search));
        var mf = !filter || v.status === filter;
        return ms && mf;
    });
    var html = '';
    if (!filtered.length) { html = '<tr><td colspan="8" class="text-center text-muted py-4">No vehicles found</td></tr>'; }
    else {
        filtered.forEach(function (v) {
            html += '<tr><td><strong>' + esc(v.plate_number || '-') + '</strong></td><td><div class="small">' + esc(v.vehicle_model || '-') + '</div><div class="text-muted small">' + esc(v.vehicle_type || '-') + '</div></td><td>' + esc(v.driver_name || 'Unassigned') + '</td><td>' + statusBadge(v.status) + '</td><td>' + fleetModeBadge(v.fleet_mode) + '</td><td>' + maintBadge(v.maintenance_status) + '</td><td>' + complBadge(v.compliance_status) + '</td><td><a href="vehicle_profile.php?id=' + (v.vehicle_id || 0) + '" class="btn btn-sm btn-outline-primary"><i class="bi bi-eye"></i></a></td></tr>';
        });
    }
    $('#fleetTableBody').html(html);
}

function filterFleetTable() { renderFleetTable(dashboardData.fleet_table); }

function getActivityIcon(a) {
    var m = {
        'vehicle_assigned':'<i class="bi bi-link-45deg text-primary"></i>',
        'fuel_approved':'<i class="bi bi-check-circle text-success"></i>',
        'maintenance_logged':'<i class="bi bi-exclamation-triangle text-warning"></i>',
        'work_order_created':'<i class="bi bi-file-earmark text-info"></i>',
        'inspection_completed':'<i class="bi bi-clipboard-check text-success"></i>',
        'driver_assigned':'<i class="bi bi-person-plus text-primary"></i>',
        'compliance_updated':'<i class="bi bi-shield-check text-info"></i>',
        'default':'<i class="bi bi-arrow-right-circle text-secondary"></i>'
    };
    return m[a] || m.default;
}

function statusBadge(s) {
    var m = { 'active':'<span class="badge bg-success">Active</span>', 'workshop':'<span class="badge bg-warning text-dark">Workshop</span>', 'inactive':'<span class="badge bg-secondary">Inactive</span>', 'maintenance':'<span class="badge bg-info">Maintenance</span>' };
    return m[s] || '<span class="badge bg-light text-dark">' + esc(s || 'Unknown') + '</span>';
}

function fleetModeBadge(m) {
    var b = { 'owned':'<span class="badge bg-primary-subtle text-primary">Owned</span>', 'leased':'<span class="badge bg-info-subtle text-info">Leased</span>' };
    return b[m] || '<span class="badge bg-light text-dark">-</span>';
}

function maintBadge(s) {
    var b = { 'due':'<span class="badge bg-warning">Due</span>', 'overdue':'<span class="badge bg-danger">Overdue</span>', 'completed':'<span class="badge bg-success">Completed</span>', 'pending':'<span class="badge bg-secondary">Pending</span>' };
    return b[s] || '<span class="badge bg-light text-dark">-</span>';
}

function complBadge(s) {
    var b = { 'valid':'<span class="badge bg-success">Valid</span>', 'expiring':'<span class="badge bg-warning text-dark">Expiring</span>', 'expired':'<span class="badge bg-danger">Expired</span>' };
    return b[s] || '<span class="badge bg-light text-dark">-</span>';
}

function showDetailsCanvas(type) {
    var canvas = new bootstrap.Offcanvas(document.getElementById('dashboardDetailsCanvas'));
    var html = '';
    if (type === 'alerts') {
        html = '<h6>All Alerts</h6>';
        (dashboardData.alerts || []).forEach(function (a) {
            html += '<div class="alert-item mb-3 pb-3 border-bottom"><div class="fw-semibold">' + esc(a.title || '-') + '</div><div class="text-muted small">' + esc(a.description || '-') + '</div><div class="small mt-2">Due: ' + fmtDate(a.due_date) + '</div></div>';
        });
    } else if (type === 'activity') {
        html = '<h6>All Recent Activity</h6>';
        (dashboardData.activity_feed || []).forEach(function (a) {
            html += '<div class="activity-item mb-3 pb-3 border-bottom"><div class="fw-semibold">' + esc(a.title || '-') + '</div><div class="text-muted small">' + esc(a.description || '-') + '</div><div class="small mt-2">' + fmtRelTime(a.timestamp) + '</div></div>';
        });
    }
    $('#detailsBody').html(html || '<div class="text-muted">No data available</div>');
    canvas.show();
}

function updateLastUpdateTime() { $('#lastUpdateTime').text('Last updated: ' + new Date().toLocaleTimeString()); }
function fmtDate(d) { if (!d) return '-'; try { return new Date(d).toLocaleDateString(); } catch(e) { return d; } }
function fmtRelTime(t) {
    if (!t) return '-';
    try {
        var diff = Math.floor((new Date() - new Date(t)) / 1000);
        if (diff < 60) return 'just now';
        if (diff < 3600) return Math.floor(diff / 60) + ' min ago';
        if (diff < 86400) return Math.floor(diff / 3600) + ' hrs ago';
        return Math.floor(diff / 86400) + ' days ago';
    } catch(e) { return t; }
}
function esc(t) { var d = document.createElement('div'); d.textContent = t || ''; return d.innerHTML; }