var map, markers = {}, markerLayer, liveInterval, isLive = true;
var vehicleData = [];
var customIcon = L.divIcon({
    html: '<div style="background:#0d6efd;color:#fff;width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;border:2px solid #fff;box-shadow:0 2px 6px rgba(0,0,0,.3)"><i class="bi bi-truck" style="font-size:14px"></i></div>',
    className: '', iconSize: [32, 32], iconAnchor: [16, 16]
});
var idleIcon = L.divIcon({
    html: '<div style="background:#ffc107;color:#000;width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;border:2px solid #fff;box-shadow:0 2px 6px rgba(0,0,0,.3)"><i class="bi bi-clock" style="font-size:14px"></i></div>',
    className: '', iconSize: [32, 32], iconAnchor: [16, 16]
});
var offlineIcon = L.divIcon({
    html: '<div style="background:#dc3545;color:#fff;width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;border:2px solid #fff;box-shadow:0 2px 6px rgba(0,0,0,.3)"><i class="bi bi-wifi-off" style="font-size:14px"></i></div>',
    className: '', iconSize: [32, 32], iconAnchor: [16, 16]
});

$(function () {
    initMap();
    loadPositions();

    $('#liveToggleBtn').on('click', function () {
        isLive = !isLive;
        var $btn = $(this);
        if (isLive) {
            $btn.addClass('active').html('<i class="bi bi-play-fill me-1"></i> Live <span class="spinner-border spinner-border-sm d-none ms-1" id="liveSpinner"></span>');
            startLiveUpdates();
        } else {
            $btn.removeClass('active').html('<i class="bi bi-pause-fill me-1"></i> Paused');
            stopLiveUpdates();
        }
    });

    $('#btnRefreshPositions').on('click', function () {
        loadPositions();
    });

    $('#btnFitAll').on('click', function () {
        fitAllMarkers();
    });

    $('#vehicleFilter').on('input', function () {
        filterVehicleList($(this).val());
    });

    startLiveUpdates();
});

function initMap() {
    map = L.map('trackingMap').setView([9.0579, 7.4951], 6);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://openstreetmap.org">OSM</a>',
        maxZoom: 18
    }).addTo(map);
    markerLayer = L.layerGroup().addTo(map);
}

function loadPositions() {
    showLiveSpinner(true);
    $.get('api/gps_tracking.php', { action: 'live' }, function (r) {
        if (r.status !== 'success') return;
        vehicleData = r.data || [];
        updateKpis(r);
        updateMarkers();
        updateVehicleList();
        loadIdleAlerts();
    }, 'json').always(function () {
        showLiveSpinner(false);
    });
}

function updateKpis(r) {
    var tracked = r.total_tracked || 0;
    var positioned = r.with_position || 0;
    var idle = 0, offline = 0;
    (r.data || []).forEach(function (v) {
        if (v.is_offline) offline++;
        else if (v.is_idle) idle++;
    });
    $('#kpiTracked').text(tracked);
    $('#kpiWithPosition').text(positioned);
    $('#kpiIdle').text(idle);
    $('#kpiOffline').text(offline);
}

function updateMarkers() {
    markerLayer.clearLayers();
    var bounds = [];
    vehicleData.forEach(function (v) {
        if (!v.has_position) return;
        var icon = v.is_offline ? offlineIcon : (v.is_idle ? idleIcon : customIcon);
        var marker = L.marker([v.latitude, v.longitude], { icon: icon })
            .bindPopup(buildPopup(v))
            .addTo(markerLayer);
        markers[v.vehicle_id] = marker;
        bounds.push([v.latitude, v.longitude]);
    });
    if (bounds.length > 0 && isLive) {
        map.fitBounds(bounds, { padding: [30, 30], maxZoom: 14 });
    }
}

function buildPopup(v) {
    var status = v.is_offline ? '<span class="badge bg-danger">Offline</span>'
        : v.is_idle ? '<span class="badge bg-warning text-dark">Idle</span>'
        : v.speed_kmh > 0 ? '<span class="badge bg-success">Moving</span>'
        : '<span class="badge bg-secondary">Stopped</span>';
    var since = v.minutes_since_update !== null ? Math.round(v.minutes_since_update) + ' min ago' : 'N/A';
    return '<div style="min-width:200px">' +
        '<h6>' + esc(v.plate_number) + ' ' + status + '</h6>' +
        '<table>' +
        '<tr><td>Model:</td><td>' + esc(v.vehicle_model || '-') + '</td></tr>' +
        '<tr><td>Speed:</td><td>' + (v.speed_kmh || 0).toFixed(1) + ' km/h</td></tr>' +
        '<tr><td>Heading:</td><td>' + (v.heading || 0).toFixed(0) + '&deg;</td></tr>' +
        '<tr><td>Last seen:</td><td>' + since + '</td></tr>' +
        '<tr><td>Driver:</td><td>' + esc(v.driver_name || '-') + '</td></tr>' +
        '</table>' +
        '<button class="btn btn-sm btn-outline-primary mt-1" onclick="showRoute(' + v.vehicle_id + ')"><i class="bi bi-map"></i> Route</button>' +
        '</div>';
}

function updateVehicleList() {
    var html = '';
    if (!vehicleData.length) {
        html = '<div class="list-group-item text-muted text-center py-4">No tracked vehicles</div>';
    } else {
        vehicleData.forEach(function (v) {
            var statusDot = v.is_offline ? 'bg-danger' : (v.is_idle ? 'bg-warning' : 'bg-success');
            var pos = v.has_position ? (v.latitude.toFixed(4) + ', ' + v.longitude.toFixed(4)) : 'No position';
            html += '<div class="list-group-item list-group-item-action py-2" data-vehicle-id="' + v.vehicle_id + '" style="cursor:pointer">' +
                '<div class="d-flex justify-content-between align-items-center">' +
                '<div><span class="badge rounded-pill ' + statusDot + '" style="width:8px;height:8px;display:inline-block;padding:0">&nbsp;</span> ' +
                '<strong>' + esc(v.plate_number) + '</strong>' +
                '<div class="text-muted" style="font-size:11px">' + pos + '</div></div>' +
                '<div class="text-end"><div class="small">' + (v.speed_kmh || 0).toFixed(1) + ' km/h</div>' +
                '<div class="text-muted" style="font-size:10px">' + (v.minutes_since_update !== null ? Math.round(v.minutes_since_update) + 'm' : '') + '</div></div>' +
                '</div></div>';
        });
    }
    $('#vehicleList').html(html);

    // Click on vehicle list item to center map
    $('#vehicleList .list-group-item').on('click', function () {
        var vid = $(this).data('vehicle-id');
        var v = vehicleData.find(function (x) { return x.vehicle_id === vid; });
        if (v && v.has_position && markers[vid]) {
            map.setView([v.latitude, v.longitude], 15);
            markers[vid].openPopup();
        }
    });
}

function filterVehicleList(query) {
    var q = (query || '').toLowerCase();
    $('#vehicleList .list-group-item').each(function () {
        var text = $(this).text().toLowerCase();
        $(this).toggle(!q || text.indexOf(q) > -1);
    });
}

function loadIdleAlerts() {
    $.get('api/gps_tracking.php', { action: 'idle', threshold: 15 }, function (r) {
        if (r.status !== 'success') return;
        var data = r.data || [];
        var html = '';
        if (!data.length) {
            html = '<div class="list-group-item text-muted text-center py-3">No idle alerts</div>';
        } else {
            data.slice(0, 10).forEach(function (v) {
                var hrs = Math.floor(v.idle_minutes / 60);
                var mins = v.idle_minutes % 60;
                var timeStr = hrs > 0 ? hrs + 'h ' + mins + 'm' : mins + 'm';
                html += '<div class="list-group-item py-2">' +
                    '<div class="d-flex justify-content-between"><strong>' + esc(v.plate_number) + '</strong><span class="badge bg-warning text-dark">' + timeStr + '</span></div>' +
                    '<div class="text-muted" style="font-size:11px">' + esc(v.driver_name || 'No driver') + '</div>' +
                    '</div>';
            });
        }
        $('#idleList').html(html);
    }, 'json');
}

function showRoute(vehicleId) {
    if (!vehicleId) return;
    var v = vehicleData.find(function (x) { return x.vehicle_id === vehicleId; });
    var label = v ? esc(v.plate_number) : 'Vehicle #' + vehicleId;
    var dateFrom = prompt('Route from date (YYYY-MM-DD):', new Date(Date.now() - 86400000).toISOString().slice(0, 10));
    if (!dateFrom) return;
    var dateTo = prompt('Route to date (YYYY-MM-DD):', new Date().toISOString().slice(0, 10));
    if (!dateTo) return;

    $.get('api/gps_tracking.php', { action: 'route', vehicle_id: vehicleId, date_from: dateFrom, date_to: dateTo }, function (r) {
        if (r.status !== 'success') { showAlert(r.message || 'Failed to load route', 'danger'); return; }
        var points = r.data || [];
        if (!points.length) { showAlert('No GPS data for this period', 'warning'); return; }

        var latlngs = points.map(function (p) { return [p.latitude, p.longitude]; });
        var polyline = L.polyline(latlngs, {
            color: '#0d6efd', weight: 3, opacity: 0.7
        }).addTo(markerLayer);

        map.fitBounds(polyline.getBounds(), { padding: [30, 30] });

        // Add start/end markers
        var start = points[0], end = points[points.length - 1];
        L.circleMarker([start.latitude, start.longitude], { color: '#198754', radius: 6, fillColor: '#198754', fillOpacity: 1 })
            .bindPopup('<strong>Start</strong><br>' + start.recorded_at).addTo(markerLayer);
        L.circleMarker([end.latitude, end.longitude], { color: '#dc3545', radius: 6, fillColor: '#dc3545', fillOpacity: 1 })
            .bindPopup('<strong>End</strong><br>' + end.recorded_at + '<br>Speed: ' + end.speed_kmh.toFixed(1) + ' km/h').addTo(markerLayer);

        // Remove route after 30s
        setTimeout(function () {
            if (polyline) markerLayer.removeLayer(polyline);
        }, 30000);

        showAlert('Route loaded: ' + points.length + ' points from ' + dateFrom + ' to ' + dateTo, 'success');
    }, 'json');
}

function fitAllMarkers() {
    var bounds = [];
    vehicleData.forEach(function (v) {
        if (v.has_position) bounds.push([v.latitude, v.longitude]);
    });
    if (bounds.length > 0) map.fitBounds(bounds, { padding: [30, 30] });
}

function startLiveUpdates() {
    stopLiveUpdates();
    liveInterval = setInterval(function () {
        if (isLive) loadPositions();
    }, 15000);
}

function stopLiveUpdates() {
    if (liveInterval) { clearInterval(liveInterval); liveInterval = null; }
}

function showLiveSpinner(show) {
    $('#liveSpinner').toggleClass('d-none', !show);
}

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'); }, 6000);
}

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