$(function () {
    loadDashboard();
    loadSuggestions();
    loadPredictive();
    loadDriverBehavior();
    loadFuelPredict();
    loadUtilization();
    loadRouteOptim();
    loadChatHistory();

    $('#btnRefreshAll').on('click', function () {
        loadDashboard();
        loadSuggestions();
        loadPredictive();
        loadDriverBehavior();
        loadFuelPredict();
        loadUtilization();
        loadRouteOptim();
        showAlert('All insights refreshed', 'success');
    });

    $('#btnSendChat').on('click', sendChatMessage);
    $('#chatInput').on('keypress', function (e) {
        if (e.which === 13) sendChatMessage();
    });

    $(document).on('click', '.btn-dismiss-suggestion', function () {
        var id = $(this).data('id');
        dismissSuggestion(id);
    });

    $(document).on('click', '.btn-dismiss-type', function () {
        var type = $(this).data('type');
        dismissSuggestionType(type);
    });
});

function loadDashboard() {
    $.get('api/ai_insights.php', { action: 'dashboard' }, function (r) {
        if (r.status !== 'success') return;
        var d = r.data || {};
        $('#kpiCriticalVal').text(d.critical || 0);
        $('#kpiWarningsVal').text(d.warnings || 0);
        $('#kpiInfoVal').text(d.info || 0);
        var kpiCriticalCard = $('#kpiCritical');
        if (d.critical > 0) kpiCriticalCard.addClass('border-danger border-2');
        else kpiCriticalCard.removeClass('border-danger border-2');
    }, 'json');
}

function loadSuggestions() {
    $.get('api/ai_insights.php', { action: 'suggestions' }, function (r) {
        if (r.status !== 'success') return;
        var items = r.data || [];
        var html = '';
        if (!items.length) {
            html = '<div class="list-group-item text-muted text-center py-4">No active suggestions</div>';
        } else {
            items.forEach(function (s) {
                var sevClass = s.severity === 'critical' ? 'danger' : (s.severity === 'warning' ? 'warning text-dark' : 'info');
                var sevIcon = s.severity === 'critical' ? 'exclamation-triangle-fill' : (s.severity === 'warning' ? 'exclamation-circle-fill' : 'info-circle-fill');
                html += '<div class="list-group-item list-group-item-action py-2">' +
                    '<div class="d-flex justify-content-between align-items-start">' +
                    '<div><span class="badge bg-' + sevClass + ' mb-1"><i class="bi bi-' + sevIcon + '"></i> ' + esc(s.severity) + '</span>' +
                    '<div class="fw-semibold small">' + esc(s.title) + '</div>' +
                    '<div class="text-muted" style="font-size:11px">' + esc(s.description) + '</div></div>' +
                    '<button class="btn btn-sm btn-outline-secondary btn-dismiss-suggestion" data-id="' + s.id + '" title="Dismiss"><i class="bi bi-x"></i></button>' +
                    '</div></div>';
            });
        }
        $('#suggestionsList').html(html);
    }, 'json');
}

function loadPredictive() {
    $.get('api/ai_insights.php', { action: 'predictive' }, function (r) {
        if (r.status !== 'success') return;
        var data = r.data || {};
        var alerts = data.maintenance_alerts || [];
        var html = '';

        var criticalCount = data.total_at_risk || 0;
        var warningCount = data.total_warning || 0;

        html += '<div class="d-flex gap-3 mb-3">' +
            '<span class="badge bg-danger">' + criticalCount + ' Critical</span>' +
            '<span class="badge bg-warning text-dark">' + warningCount + ' Warning</span>' +
            '<span class="badge bg-info">' + (alerts.length - criticalCount - warningCount) + ' Upcoming</span>' +
            '</div>';

        if (!alerts.length) {
            html += '<div class="text-muted">No maintenance predictions available. Ensure service intervals are configured.</div>';
        } else {
            html += '<div class="table-responsive"><table class="table table-sm small mb-0"><thead><tr><th>Vehicle</th><th>Status</th><th>Due</th><th>Odometer</th></tr></thead><tbody>';
            alerts.forEach(function (a) {
                var cls = a.urgency === 'critical' ? 'danger' : (a.urgency === 'warning' ? 'warning' : 'info');
                html += '<tr class="table-' + cls + '">' +
                    '<td><strong>' + esc(a.plate_number) + '</strong><br><span class="text-muted">' + esc(a.vehicle_model || '') + '</span></td>' +
                    '<td><span class="badge bg-' + cls + '">' + esc(a.label) + '</span></td>' +
                    '<td>' + (a.due_date || '-') + '<br><small>' + (a.due_mileage ? a.due_mileage.toLocaleString() + ' km' : '') + '</small></td>' +
                    '<td>' + (a.current_odometer ? a.current_odometer.toLocaleString() + ' km' : '-') + '</td>' +
                    '</tr>';
            });
            html += '</tbody></table></div>';
        }
        $('#predictiveContent').html(html);
    }, 'json');
}

function loadDriverBehavior() {
    $.get('api/ai_insights.php', { action: 'driver_behavior' }, function (r) {
        if (r.status !== 'success') return;
        var data = r.data || {};
        var drivers = data.drivers || [];

        $('#kpiDriverScore').text((data.average_score || 0) + '%');

        if (!drivers.length) {
            $('#driverContent').html('<div class="text-muted">No driver data available for analysis.</div>');
            return;
        }

        var html = '<div class="d-flex gap-3 mb-3">' +
            '<span class="badge bg-success">' + (data.excellent || 0) + ' Excellent</span>' +
            '<span class="badge bg-warning text-dark">' + (data.needs_improvement || 0) + ' Needs Improvement</span>' +
            '<span class="badge bg-info">' + (drivers.length - (data.excellent || 0) - (data.needs_improvement || 0)) + ' Moderate</span>' +
            '</div>';

        html += '<div class="table-responsive"><table class="table table-sm small mb-0"><thead><tr><th>Driver</th><th>Score</th><th>Rating</th><th>Trips</th><th>Incidents</th><th>Violations</th></tr></thead><tbody>';
        drivers.forEach(function (d) {
            var cls = d.behavior_score >= 80 ? 'success' : (d.behavior_score >= 60 ? 'warning' : (d.behavior_score >= 40 ? 'warning' : 'danger'));
            var barWidth = Math.min(d.behavior_score, 100);
            html += '<tr>' +
                '<td><strong>' + esc(d.full_name) + '</strong></td>' +
                '<td><div class="d-flex align-items-center gap-2"><div class="progress flex-grow-1" style="height:6px;width:60px"><div class="progress-bar bg-' + cls + '" style="width:' + barWidth + '%"></div></div><strong>' + d.behavior_score + '</strong></div></td>' +
                '<td><span class="badge bg-' + cls + '">' + esc(d.rating) + '</span></td>' +
                '<td>' + d.trip_count + '</td>' +
                '<td>' + d.incidents_90d + '</td>' +
                '<td>' + d.violations_90d + '</td>' +
                '</tr>';
        });
        html += '</tbody></table></div>';
        $('#driverContent').html(html);
    }, 'json');
}

function loadFuelPredict() {
    $.get('api/ai_insights.php', { action: 'fuel_predict' }, function (r) {
        if (r.status !== 'success') return;
        var data = r.data || {};
        var vehicles = data.vehicles || [];

        if (!vehicles.length) {
            $('#fuelContent').html('<div class="text-muted">Insufficient fuel data for predictions. Need at least 2 entries per vehicle.</div>');
            return;
        }

        var html = '<div class="d-flex gap-3 mb-3">' +
            '<span class="badge bg-info">' + data.total_analyzed + ' Vehicles Analyzed</span>' +
            '<span class="badge bg-' + (data.overall_variance_percent > 10 ? 'warning text-dark' : 'success') + '">Actual vs Predicted: ' + (data.overall_variance_percent > 0 ? '+' : '') + (data.overall_variance_percent || 0) + '%</span>' +
            '</div>';

        html += '<div class="table-responsive"><table class="table table-sm small mb-0"><thead><tr><th>Vehicle</th><th>Baseline</th><th>Actual</th><th>Variance</th><th>Predicted Next Month</th></tr></thead><tbody>';
        vehicles.forEach(function (v) {
            var effClass = v.is_efficient ? 'success' : 'danger';
            html += '<tr>' +
                '<td><strong>' + esc(v.plate_number) + '</strong></td>' +
                '<td>' + v.baseline_consumption + ' L/100km</td>' +
                '<td>' + v.actual_consumption + ' L/100km</td>' +
                '<td><span class="badge bg-' + effClass + '">' + (v.variance_percent > 0 ? '+' : '') + v.variance_percent + '%</span></td>' +
                '<td>' + v.predicted_next_month_liters + ' L (₦' + v.predicted_next_month_cost.toLocaleString() + ')</td>' +
                '</tr>';
        });
        html += '</tbody></table></div>';
        $('#fuelContent').html(html);
    }, 'json');
}

function loadUtilization() {
    $.get('api/ai_insights.php', { action: 'utilization' }, function (r) {
        if (r.status !== 'success') return;
        var data = r.data || {};
        var vehicles = data.vehicles || [];

        var html = '<div class="d-flex gap-3 mb-3 flex-wrap">' +
            '<span class="badge bg-success">' + (data.active_count || 0) + ' Active</span>' +
            '<span class="badge bg-warning text-dark">' + (data.underutilized_count || 0) + ' Underutilized</span>' +
            '<span class="badge bg-secondary">' + (data.idle_count || 0) + ' Idle</span>' +
            '<span class="badge bg-info">Fleet Utilization: ' + (data.fleet_utilization_rate || 0) + '%</span>' +
            '</div>';

        if (!vehicles.length) {
            html += '<div class="text-muted">No vehicle data available.</div>';
        } else {
            html += '<div class="table-responsive"><table class="table table-sm small mb-0"><thead><tr><th>Vehicle</th><th>Utilization</th><th>Status</th><th>Trips (90d)</th><th>Forecast (30d)</th></tr></thead><tbody>';
            vehicles.forEach(function (v) {
                var cls = v.utilization_status === 'Active' ? 'success' : (v.utilization_status === 'Underutilized' ? 'warning' : 'secondary');
                var barWidth = Math.min(v.utilization_rate, 100);
                html += '<tr>' +
                    '<td><strong>' + esc(v.plate_number) + '</strong><br><span class="text-muted">' + esc(v.vehicle_type || '') + '</span></td>' +
                    '<td><div class="d-flex align-items-center gap-2"><div class="progress flex-grow-1" style="height:6px;width:60px"><div class="progress-bar bg-' + cls + '" style="width:' + barWidth + '%"></div></div>' + v.utilization_rate + '%</div></td>' +
                    '<td><span class="badge bg-' + cls + '">' + esc(v.utilization_status) + '</span></td>' +
                    '<td>' + v.trip_count_90d + ' trips<br><small>' + v.total_km_90d.toLocaleString() + ' km</small></td>' +
                    '<td>' + v.predicted_trips_next_30d + ' trips<br><small>' + v.predicted_km_next_30d.toLocaleString() + ' km</small></td>' +
                    '</tr>';
            });
            html += '</tbody></table></div>';
        }
        $('#utilContent').html(html);
    }, 'json');
}

function loadRouteOptim() {
    $.get('api/ai_insights.php', { action: 'route_optim' }, function (r) {
        if (r.status !== 'success') return;
        var data = r.data || {};

        var html = '<div class="d-flex gap-3 mb-3 flex-wrap">' +
            '<span class="badge bg-info">' + (data.trips_analyzed || 0) + ' Trips Analyzed</span>' +
            '<span class="badge bg-primary">Avg ' + (data.avg_km_per_trip || 0) + ' km/trip</span>' +
            '<span class="badge bg-' + (data.savings_percent > 10 ? 'success' : 'secondary') + '">Potential Savings: ' + (data.potential_savings_km || 0).toLocaleString() + ' km (' + (data.savings_percent || 0) + '%)</span>' +
            '</div>';

        var inefficient = data.inefficient_trips || [];
        if (inefficient.length > 0) {
            html += '<div class="fw-semibold small mb-2">Inefficient Trips (highest waste):</div>';
            html += '<div class="table-responsive"><table class="table table-sm small mb-0"><thead><tr><th>Vehicle</th><th>Route</th><th>Actual</th><th>Optimal</th><th>Wasted</th></tr></thead><tbody>';
            inefficient.forEach(function (t) {
                html += '<tr>' +
                    '<td>' + esc(t.plate_number) + '</td>' +
                    '<td><small>' + esc(t.start) + ' &rarr; ' + esc(t.end) + '</small></td>' +
                    '<td>' + t.actual_km + ' km</td>' +
                    '<td>' + t.optimal_km + ' km</td>' +
                    '<td class="text-danger">' + t.wasted_km + ' km</td>' +
                    '</tr>';
            });
            html += '</tbody></table></div>';
        } else {
            html += '<div class="text-muted">No significantly inefficient trips found in the analyzed period.</div>';
        }
        $('#routeContent').html(html);
    }, 'json');
}

function loadChatHistory() {
    $.get('api/ai_insights.php', { action: 'chat_history' }, function (r) {
        if (r.status !== 'success') return;
        var msgs = r.data || [];
        var html = '';
        msgs.forEach(function (m) {
            html += renderChatMessage(m.role, m.message);
        });
        if (html) {
            $('#chatMessages').html(html);
            scrollChat();
        }
    }, 'json');
}

function sendChatMessage() {
    var msg = $('#chatInput').val().trim();
    if (!msg) return;
    $('#chatInput').val('');

    $('#chatMessages').append(renderChatMessage('user', msg));
    scrollChat();
    $('#chatMessages').append(renderChatMessage('assistant', 'Thinking...'));
    scrollChat();

    $.post('api/ai_insights.php?action=chat', { message: msg, csrf_token: window.CSRF_TOKEN }, function (r) {
        $('#chatMessages .thinking').last().remove();
        if (r.status !== 'success') {
            $('#chatMessages').append(renderChatMessage('assistant', 'Sorry, I encountered an error. Please try again.'));
        } else {
            $('#chatMessages').append(renderChatMessage('assistant', r.data.response));
        }
        scrollChat();
    }, 'json').fail(function () {
        $('#chatMessages .thinking').last().remove();
        $('#chatMessages').append(renderChatMessage('assistant', 'Network error. Please try again.'));
        scrollChat();
    });
}

function renderChatMessage(role, text) {
    var isUser = role === 'user';
    var align = isUser ? 'end' : 'start';
    var bg = isUser ? 'bg-primary text-white' : 'bg-light';
    var name = isUser ? 'You' : 'AI Assistant';
    var thinking = text === 'Thinking...' ? ' thinking' : '';
    return '<div class="d-flex justify-content-' + align + ' mb-2">' +
        '<div class="' + bg + ' rounded-3 px-3 py-2' + thinking + '" style="max-width:85%">' +
        '<div class="fw-semibold small">' + name + '</div>' +
        '<div class="small">' + formatChatText(text) + '</div>' +
        '</div></div>';
}

function formatChatText(text) {
    return (text || '').replace(/\n/g, '<br>').replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
}

function scrollChat() {
    var chat = document.getElementById('chatMessages');
    if (chat) chat.scrollTop = chat.scrollHeight;
}

function dismissSuggestion(id) {
    $.post('api/ai_insights.php?action=dismiss', { id: id, csrf_token: window.CSRF_TOKEN }, function (r) {
        if (r.status === 'success') loadSuggestions();
    }, 'json');
}

function dismissSuggestionType(type) {
    $.post('api/ai_insights.php?action=dismiss', { type: type, csrf_token: window.CSRF_TOKEN }, function (r) {
        if (r.status === 'success') loadSuggestions();
    }, 'json');
}

function showAlert(msg, type) {
    var box = $('#alertBox');
    box.removeClass('d-none alert-success alert-danger alert-warning alert-info')
        .addClass('alert-' + type).html(msg);
    setTimeout(function () { box.addClass('d-none'); }, 4000);
}

function esc(t) { return $('<div>').text(t || '').html(); }
