function allRoutes() {
    $(".crud_section").html("");

    /***************************************************
     * GLOBALS
     ***************************************************/
    var deviceMap = null;
    var geofenceHoverInfo = null;
    var geofenceInfoWindow = null;
    var distanceLayer = null;
    var directionsService = null;
    var directionsRenderer = null;

    var geofences = [];
    var routeShapes = [];
    var selectedRoute = null;

    const ROUTE_COLORS = {
        DEFAULT: '#3b82f6',
        SELECTED: '#000000',
        HOVER: '#f97316',
        ACTIVE: '#10b981',
        INACTIVE: '#94a3b8',
        COMPLETED: '#22c55e',
        PLANNED: '#f59e0b'
    };

    /***************************************************
     * INIT
     ***************************************************/
    buildLayout();
    setTimeout(() => initMap(), 100);
    loadRoutes();

    /***************************************************
     * UI LAYOUT - MODERN DESIGN
     ***************************************************/
    function buildLayout() {
        let html = `
            <div class="routes-container" style="padding: 24px; background: #ffffff; min-height: 100vh; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
                
                <!-- Header -->
                <div style="background: #ffffff; border-radius: 16px; padding: 24px; margin-bottom: 24px; border: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center;">
                    <div style="display: flex; align-items: center; gap: 16px;">
                        <h1 style="margin: 0; font-size: 28px; font-weight: 600; color: #1a1f36; display: flex; align-items: center; gap: 12px;">
                            <i class="fas fa-route" style="color: #3b82f6;"></i>
                            Routes Management
                        </h1>
                        <span class="route-count" style="background: #f0f2f5; color: #1a1f36; padding: 6px 14px; border-radius: 40px; font-size: 14px; font-weight: 500;">
                            Loading...
                        </span>
                    </div>
                    <div style="display: flex; gap: 8px;">
                        <button onclick="toggleRouteList()" class="btn-outline" style="display: flex; align-items: center; gap: 8px; padding: 10px 16px; background: white; border: 1px solid #eaeef2; border-radius: 10px; cursor: pointer;">
                            <i class="fas fa-list"></i>
                            <span>Show List</span>
                        </button>
                        <button onclick="fitAllRoutes()" class="btn-outline" style="display: flex; align-items: center; gap: 8px; padding: 10px 16px; background: white; border: 1px solid #eaeef2; border-radius: 10px; cursor: pointer;">
                            <i class="fas fa-expand-arrows-alt"></i>
                            <span>Fit All</span>
                        </button>
                        <button onclick="toggleDistanceLayer()" class="btn-outline" id="distanceBtn" style="display: flex; align-items: center; gap: 8px; padding: 10px 16px; background: white; border: 1px solid #eaeef2; border-radius: 10px; cursor: pointer;">
                            <i class="fas fa-ruler"></i>
                            <span>Show Distances</span>
                        </button>
                        <button onclick="addNewRoute()" style="display: flex; align-items: center; gap: 8px; padding: 10px 20px; background: #000; color: white; border: none; border-radius: 10px; cursor: pointer;">
                            <i class="fas fa-plus"></i>
                            <span>Add Route</span>
                        </button>
                    </div>
                </div>

                <!-- Stats Cards -->
                <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-bottom: 24px;">
                    <div class="stat-card" style="background: #ffffff; border-radius: 16px; padding: 20px; border: 1px solid #eaeef2; display: flex; align-items: center; gap: 16px;">
                        <div style="width: 48px; height: 48px; background: #dbeafe; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-route" style="font-size: 20px; color: #3b82f6;"></i>
                        </div>
                        <div>
                            <div style="font-size: 13px; color: #5b677c;">Total Routes</div>
                            <div class="stat-value" id="totalRoutes" style="font-size: 24px; font-weight: 700; color: #1a1f36;">0</div>
                        </div>
                    </div>
                    
                    <div class="stat-card" style="background: #ffffff; border-radius: 16px; padding: 20px; border: 1px solid #eaeef2; display: flex; align-items: center; gap: 16px;">
                        <div style="width: 48px; height: 48px; background: #dcfce7; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-check-circle" style="font-size: 20px; color: #22c55e;"></i>
                        </div>
                        <div>
                            <div style="font-size: 13px; color: #5b677c;">Active Routes</div>
                            <div class="stat-value" id="activeRoutes" style="font-size: 24px; font-weight: 700; color: #22c55e;">0</div>
                        </div>
                    </div>
                    
                    <div class="stat-card" style="background: #ffffff; border-radius: 16px; padding: 20px; border: 1px solid #eaeef2; display: flex; align-items: center; gap: 16px;">
                        <div style="width: 48px; height: 48px; background: #fff3e0; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-clock" style="font-size: 20px; color: #f59e0b;"></i>
                        </div>
                        <div>
                            <div style="font-size: 13px; color: #5b677c;">Planned Routes</div>
                            <div class="stat-value" id="plannedRoutes" style="font-size: 24px; font-weight: 700; color: #f59e0b;">0</div>
                        </div>
                    </div>
                    
                    <div class="stat-card" style="background: #ffffff; border-radius: 16px; padding: 20px; border: 1px solid #eaeef2; display: flex; align-items: center; gap: 16px;">
                        <div style="width: 48px; height: 48px; background: #fee2e2; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-chart-line" style="font-size: 20px; color: #ef4444;"></i>
                        </div>
                        <div>
                            <div style="font-size: 13px; color: #5b677c;">Total Distance</div>
                            <div class="stat-value" id="totalDistance" style="font-size: 24px; font-weight: 700; color: #ef4444;">0 km</div>
                        </div>
                    </div>
                </div>

                <!-- Main Content: Map and Side Panel -->
                <div style="display: grid; gap: 20px; height: 800px;">
                    <!-- Map Container -->
                    <div style="flex: 2; position: relative; background: #ffffff; border-radius: 16px; border: 1px solid #eaeef2; overflow: hidden;">
                        <div id="all_routes_map" style="height: 100%; width: 100%;"></div>
                        
                        <!-- Map Controls Overlay -->
                        <div style="position: absolute; top: 16px; right: 16px; z-index: 10; display: flex; flex-direction: column; gap: 8px;">
                            <button onclick="zoomIn()" style="width: 40px; height: 40px; background: white; border: 1px solid #eaeef2; border-radius: 10px; cursor: pointer; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">
                                <i class="fas fa-plus"></i>
                            </button>
                            <button onclick="zoomOut()" style="width: 40px; height: 40px; background: white; border: 1px solid #eaeef2; border-radius: 10px; cursor: pointer; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">
                                <i class="fas fa-minus"></i>
                            </button>
                            <button onclick="fitAllRoutes()" style="width: 40px; height: 40px; background: white; border: 1px solid #eaeef2; border-radius: 10px; cursor: pointer; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">
                                <i class="fas fa-expand"></i>
                            </button>
                            <button onclick="toggleTrafficLayer()" id="trafficBtn" style="width: 40px; height: 40px; background: white; border: 1px solid #eaeef2; border-radius: 10px; cursor: pointer; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">
                                <i class="fas fa-car"></i>
                            </button>
                        </div>
                        
                        <!-- Coordinates Display -->
                        <div style="position: absolute; bottom: 16px; left: 16px; z-index: 10; background: rgba(255,255,255,0.9); padding: 8px 16px; border-radius: 40px; border: 1px solid #eaeef2; font-size: 12px; color: #5b677c;">
                            <span id="mouseCoordinates">Hover on map to see coordinates</span>
                        </div>
                        
                        <!-- Distance Legend -->
                        <div style="position: absolute; bottom: 16px; right: 16px; z-index: 10; background: white; padding: 12px; border-radius: 12px; border: 1px solid #eaeef2; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">
                            <div style="font-size: 12px; font-weight: 600; margin-bottom: 8px; color: #1a1f36;">Route Status</div>
                            <div style="display: flex; flex-direction: column; gap: 4px;">
                                <div style="display: flex; align-items: center; gap: 8px;">
                                    <span style="width: 20px; height: 3px; background: #22c55e;"></span>
                                    <span style="font-size: 11px; color: #5b677c;">Active</span>
                                </div>
                                <div style="display: flex; align-items: center; gap: 8px;">
                                    <span style="width: 20px; height: 3px; background: #f59e0b; border-                                    <span style="font-size: 11px; color: #5b677c;">Planned</span>
                                </div>
                                <div style="display: flex; align-items: center; gap: 8px;">
                                    <span style="width: 20px; height: 3px; background: #94a3b8;"></span>
                                    <span style="font-size: 11px; color: #5b677c;">Completed</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Side Panel - Routes List -->
                    <div id="routeListPanel" style="flex: 1; background: #ffffff; border-radius: 16px; border: 1px solid #eaeef2; overflow: hidden; display: flex; flex-direction: column;">
                        <div style="padding: 16px; border-bottom: 1px solid #eaeef2; background: #f8fafc;">
                            <h3 style="margin: 0; font-size: 16px; color: #1a1f36; display: flex; align-items: center; gap: 8px;">
                                <i class="fas fa-route"></i>
                                Routes List
                            </h3>
                        </div>
                        
                        <div id="routesList" style="flex: 1; overflow-y: auto; padding: 12px;">
                            <!-- Routes will be loaded here -->
                            <div style="text-align: center; color: #94a3b8; padding: 40px;">
                                <i class="fas fa-spinner fa-spin" style="font-size: 24px; margin-bottom: 12px;"></i>
                                <div>Loading routes...</div>
                            </div>
                        </div>
                        
                        <div style="padding: 12px; border-top: 1px solid #eaeef2; background: #f8fafc;">
                            <button onclick="exportRoutes()" style="width: 100%; padding: 10px; background: #000; color: white; border: none; border-radius: 10px; cursor: pointer;">
                                <i class="fas fa-download"></i> Export Routes Data
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Selected Route Details Panel -->
                <div id="selectedRoutePanel" style="display: none; margin-top: 20px; background: #ffffff; border-radius: 16px; border: 1px solid #eaeef2; overflow: hidden;">
                    <!-- Dynamic content will be inserted here -->
                </div>

                <!-- Waypoints Panel -->
                <div id="waypointsPanel" style="display: none; margin-top: 20px; background: #ffffff; border-radius: 16px; border: 1px solid #eaeef2; overflow: hidden;">
                    <div style="padding: 16px; border-bottom: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center;">
                        <h3 style="margin: 0; font-size: 16px; color: #1a1f36;">
                            <i class="fas fa-map-pin"></i> Route Waypoints
                        </h3>
                        <button onclick="hideWaypointsPanel()" style="background: none; border: none; cursor: pointer;">
                            <i class="fas fa-times" style="color: #94a3b8;"></i>
                        </button>
                    </div>
                    <div id="waypointsList" style="padding: 16px; max-height: 300px; overflow-y: auto;"></div>
                </div>

                <style>
                    /* Hover effects */
                    .stat-card {
                        transition: transform 0.2s, box-shadow 0.2s;
                    }
                    .stat-card:hover {
                        transform: translateY(-2px);
                        box-shadow: 0 8px 16px rgba(0,0,0,0.05);
                    }
                    
                    /* Route list items */
                    .route-list-item {
                        padding: 12px;
                        border-bottom: 1px solid #eaeef2;
                        cursor: pointer;
                        transition: all 0.2s;
                    }
                    .route-list-item:hover {
                        background: #f8fafc;
                    }
                    .route-list-item.selected {
                        background: #f0f2f5;
                        border-left: 3px solid #3b82f6;
                    }
                    
                    /* Status badges */
                    .status-badge {
                        display: inline-block;
                        padding: 2px 8px;
                        border-radius: 12px;
                        font-size: 10px;
                        font-weight: 600;
                    }
                    .status-active { background: #dcfce7; color: #22c55e; }
                    .status-planned { background: #fff3e0; color: #f59e0b; }
                    .status-completed { background: #f1f5f9; color: #64748b; }
                    
                    /* Waypoint items */
                    .waypoint-item {
                        padding: 10px;
                        background: #f8fafc;
                        border-radius: 8px;
                        margin-bottom: 8px;
                        display: flex;
                        align-items: center;
                        gap: 12px;
                    }
                    .waypoint-index {
                        width: 24px;
                        height: 24px;
                        background: #3b82f6;
                        color: white;
                        border-radius: 50%;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        font-size: 12px;
                        font-weight: 600;
                    }
                    
                    /* Custom scrollbar */
                    #routesList::-webkit-scrollbar,
                    #waypointsList::-webkit-scrollbar {
                        width: 6px;
                    }
                    #routesList::-webkit-scrollbar-track,
                    #waypointsList::-webkit-scrollbar-track {
                        background: #f1f1f1;
                        border-radius: 10px;
                    }
                    #routesList::-webkit-scrollbar-thumb,
                    #waypointsList::-webkit-scrollbar-thumb {
                        background: #cbd5e1;
                        border-radius: 10px;
                    }
                    
                    /* Traffic layer active */
                    .traffic-active {
                        background: #3b82f6 !important;
                        color: white !important;
                    }
                    
                    /* Distance labels */
                    .distance-label {
                        background: white;
                        padding: 4px 8px;
                        border-radius: 12px;
                        border: 1px solid #eaeef2;
                        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
                        font-size: 11px;
                        font-weight: 600;
                    }
                    
                </style>
            </div>
        `;

        $(".tab_routes").html(html);
    }

    /***************************************************
     * MAP INIT
     ***************************************************/
    function initMap() {
        const mapElement = document.getElementById("all_routes_map");
        if (!mapElement) return;

        deviceMap = new google.maps.Map(mapElement, {
            zoom: 7,
            center: { lat: 11.5721, lng: 43.1456 },
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            gestureHandling: "greedy",
            mapTypeControl: true,
            streetViewControl: true,
            zoomControl: false,
            fullscreenControl: true,
            styles: [
                {
                    featureType: "poi",
                    elementType: "labels",
                    stylers: [{ visibility: "off" }]
                },
                {
                    featureType: "transit",
                    elementType: "labels",
                    stylers: [{ visibility: "off" }]
                }
            ]
        });

        // Initialize services
        directionsService = new google.maps.DirectionsService();
        directionsRenderer = new google.maps.DirectionsRenderer({
            suppressMarkers: true,
            polylineOptions: {
                strokeColor: ROUTE_COLORS.DEFAULT,
                strokeWeight: 4,
                strokeOpacity: 0.8
            }
        });

        // Initialize info windows
        geofenceHoverInfo = new google.maps.InfoWindow({
            disableAutoPan: true,
            pixelOffset: new google.maps.Size(0, -10)
        });

        geofenceInfoWindow = new google.maps.InfoWindow({
            maxWidth: 350
        });

        // Add mouse move listener
        deviceMap.addListener('mousemove', function(e) {
            const lat = e.latLng.lat().toFixed(6);
            const lng = e.latLng.lng().toFixed(6);
            $('#mouseCoordinates').html(`Lat: ${lat}, Lng: ${lng}`);
        });

        // Add click listener for creating waypoints
        deviceMap.addListener('click', function(e) {
            if ($('#drawBtn').hasClass('drawing-active')) {
                addWaypoint(e.latLng);
            }
        });
    }

    /***************************************************
     * LOAD ROUTES
     ***************************************************/
    function loadRoutes() {
        controller.getAuthRequest(
            serverURL + "geofences/routes?size=1000",
            true,
            res => {
                geofences = res?.content || [];
                
                // Update stats
                updateStats(geofences);
                
                // Draw routes on map
                drawRoutesOnly();
                
                // Populate routes list
                populateRoutesList(geofences);
                
                // Update route count badge
                $('.route-count').text(`${geofences.length} Routes`);
            },
            error => {
                console.error("Error loading routes:", error);
                $("#routesList").html(`
                    <div style="text-align: center; color: #dc2626; padding: 40px;">
                        <i class="fas fa-exclamation-triangle" style="font-size: 32px; margin-bottom: 12px;"></i>
                        <div>Failed to load routes</div>
                        <button onclick="loadRoutes()" style="margin-top: 16px; padding: 8px 16px; background: #000; color: white; border: none; border-radius: 8px; cursor: pointer;">
                            Retry
                        </button>
                    </div>
                `);
            }
        );
    }

    /***************************************************
     * UPDATE STATISTICS
     ***************************************************/
    function updateStats(routes) {
        const total = routes.length;
        const activeRoutes = routes.filter(r => r.status === 'ACTIVE').length;
        const plannedRoutes = routes.filter(r => r.status === 'PLANNED').length;
        
        // Calculate total distance
        let totalDistance = 0;
        routes.forEach(route => {
            if (route.coordinatesJson) {
                try {
                    const coords = JSON.parse(route.coordinatesJson);
                    totalDistance += calculateRouteDistance(coords);
                } catch (e) {}
            }
        });

        animateNumber('#totalRoutes', total);
        animateNumber('#activeRoutes', activeRoutes);
        animateNumber('#plannedRoutes', plannedRoutes);
        $('#totalDistance').text(`${Math.round(totalDistance)} km`);
    }

    function calculateRouteDistance(coords) {
        if (!coords || coords.length < 2) return 0;
        
        let distance = 0;
        for (let i = 0; i < coords.length - 1; i++) {
            const p1 = new google.maps.LatLng(coords[i].lat || coords[i][1], coords[i].lng || coords[i][0]);
            const p2 = new google.maps.LatLng(coords[i + 1].lat || coords[i + 1][1], coords[i + 1].lng || coords[i + 1][0]);
            distance += google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000;
        }
        return distance;
    }

    function animateNumber(selector, target) {
        const element = $(selector);
        const current = parseInt(element.text()) || 0;
        const increment = (target - current) / 20;
        let step = 0;

        const interval = setInterval(() => {
            step++;
            const value = Math.round(current + (increment * step));
            element.text(value);
            
            if (step >= 20) {
                element.text(target);
                clearInterval(interval);
            }
        }, 20);
    }

    /***************************************************
     * POPULATE ROUTES LIST
     ***************************************************/
    function populateRoutesList(routes) {
        const $list = $("#routesList");
        $list.empty();

        routes.sort((a, b) => a.name.localeCompare(b.name));

        routes.forEach(route => {
            const distance = calculateRouteDistance(JSON.parse(route.coordinatesJson || '[]'));
            const waypointCount = route.coordinatesJson ? JSON.parse(route.coordinatesJson).length : 0;
            const statusClass = getStatusClass(route.status);

            $list.append(`
                <div class="route-list-item" data-id="${route.id}" onclick="selectRoute('${route.id}')">
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <div style="width: 36px; height: 36px; background: ${route.colorHex || ROUTE_COLORS.DEFAULT}20; border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-route" style="color: ${route.colorHex || ROUTE_COLORS.DEFAULT};"></i>
                        </div>
                        <div style="flex: 1;">
                            <div style="font-weight: 600; color: #1a1f36;">${route.name}</div>
                            <div style="font-size: 11px; color: #5b677c; display: flex; gap: 8px; margin-top: 4px;">
                                <span><i class="fas fa-ruler"></i> ${distance.toFixed(1)} km</span>
                                <span><i class="fas fa-map-pin"></i> ${waypointCount} points</span>
                                <span class="status-badge ${statusClass}">${route.status || 'PLANNED'}</span>
                            </div>
                        </div>
                    </div>
                </div>
            `);
        });

        // Add search functionality
        $("#routeSearch").on("keyup", function() {
            const searchTerm = $(this).val().toLowerCase();
            $('.route-list-item').each(function() {
                const name = $(this).text().toLowerCase();
                $(this).toggle(name.includes(searchTerm));
            });
        });

        // Add filter functionality
        $("#routeStatusFilter").on("change", function() {
            filterRoutes();
        });
    }

    function getStatusClass(status) {
        switch(status?.toUpperCase()) {
            case 'ACTIVE': return 'status-active';
            case 'PLANNED': return 'status-planned';
            case 'COMPLETED': return 'status-completed';
            default: return 'status-planned';
        }
    }

    function filterRoutes() {
        const statusFilter = $("#routeStatusFilter").val();
        
        $('.route-list-item').each(function() {
            const $item = $(this);
            const statusText = $item.find('.status-badge').text();
            
            let showByStatus = statusFilter === 'all' || statusText.toLowerCase() === statusFilter;
            $item.toggle(showByStatus);
        });
    }

    /***************************************************
     * DRAW ROUTES
     ***************************************************/
    function drawRoutesOnly() {
        // Clear existing shapes
        routeShapes.forEach(r => {
            if (r) r.setMap(null);
        });
        routeShapes = [];

        let bounds = new google.maps.LatLngBounds();
        let hasBounds = false;

        geofences.forEach(f => {
            if (!f.route || !f.coordinatesJson) return;

            try {
                let coords = JSON.parse(f.coordinatesJson);
                
                // Convert coordinates if needed
                if (coords.length > 0 && Array.isArray(coords[0]) && coords[0].length === 2) {
                    coords = coords.map(coord => ({
                        lat: coord[1],
                        lng: coord[0]
                    }));
                }

                // Determine line style based on status
                const lineColor = getStatusColor(f.status, f.colorHex);
                
                const polyline = new google.maps.Polyline({
                    map: deviceMap,
                    path: coords,
                    strokeColor: lineColor,
                    strokeWeight: f.status === 'ACTIVE' ? 5 : 4,
                    strokeOpacity: f.status === 'ACTIVE' ? 1 : 0.7,
                    clickable: true,
                    zIndex: f.status === 'ACTIVE' ? 10 : 1,
                    metadata: f
                });

                // Add arrow icons for direction
                if (f.status === 'ACTIVE') {
                    polyline.setOptions({
                        icons: [{
                            icon: {
                                path: google.maps.SymbolPath.FORWARD_OPEN_ARROW,
                                scale: 3,
                                strokeColor: lineColor,
                                strokeWeight: 2
                            },
                            offset: '100%',
                            repeat: '100px'
                        }]
                    });
                }

                // Store metadata
                polyline.metadata = f;
                
                // Attach events
                attachRouteEvents(polyline);
                
                routeShapes.push(polyline);
                
                // Extend bounds
                coords.forEach(p => bounds.extend(p));
                hasBounds = true;

                // Add distance markers if enabled
                if (distanceLayer) {
                    addDistanceMarkers(polyline, coords);
                }
                
            } catch (e) {
                console.error("Invalid route coordinates:", f.name, e);
            }
        });

        // Fit bounds if we have shapes
        if (hasBounds && deviceMap) {
            deviceMap.fitBounds(bounds);
        }
    }

    function getStatusColor(status, defaultColor) {
        if (defaultColor) return defaultColor;
        
        switch(status?.toUpperCase()) {
            case 'ACTIVE': return ROUTE_COLORS.ACTIVE;
            case 'PLANNED': return ROUTE_COLORS.PLANNED;
            case 'COMPLETED': return ROUTE_COLORS.COMPLETED;
            default: return ROUTE_COLORS.DEFAULT;
        }
    }

    /***************************************************
     * ROUTE EVENTS
     ***************************************************/
    function attachRouteEvents(polyline) {
        const originalStyle = {
            strokeWeight: polyline.strokeWeight,
            strokeOpacity: polyline.strokeOpacity,
            zIndex: polyline.zIndex
        };

        const hoverStyle = {
            strokeWeight: originalStyle.strokeWeight + 2,
            strokeOpacity: 1,
            zIndex: 100
        };

        // Mouse over
        polyline.addListener("mouseover", (e) => {
            polyline.setOptions(hoverStyle);
            
            // Show hover info
            let position = e?.latLng;
            if (!position) {
                const bounds = new google.maps.LatLngBounds();
                polyline.getPath().forEach(p => bounds.extend(p));
                position = bounds.getCenter();
            }

            geofenceHoverInfo.setContent(buildRouteInfoCard(polyline.metadata, 'hover'));
            geofenceHoverInfo.setPosition(position);
            geofenceHoverInfo.open(deviceMap);
        });

        // Mouse out
        polyline.addListener("mouseout", () => {
            polyline.setOptions(originalStyle);
            geofenceHoverInfo.close();
        });

        // Click
        polyline.addListener("click", (e) => {
            // Close any open info windows
            geofenceInfoWindow.close();
            
            // Show detailed info
            let position = e?.latLng;
            if (!position) {
                const bounds = new google.maps.LatLngBounds();
                polyline.getPath().forEach(p => bounds.extend(p));
                position = bounds.getCenter();
            }

            geofenceInfoWindow.setContent(buildRouteInfoCard(polyline.metadata, 'detailed'));
            geofenceInfoWindow.setPosition(position);
            geofenceInfoWindow.open(deviceMap);
            
            // Highlight selected route
            highlightRoute(polyline.metadata.id);
            
            // Show detailed panel
            showRouteDetails(polyline.metadata);
        });

        // Right click - show waypoints
        polyline.addListener("rightclick", () => {
            showRouteWaypoints(polyline.metadata);
        });
    }

    /***************************************************
     * ROUTE INFO CARD
     ***************************************************/
    function buildRouteInfoCard(route, type = 'hover') {
        const distance = calculateRouteDistance(JSON.parse(route.coordinatesJson || '[]'));
        const waypointCount = route.coordinatesJson ? JSON.parse(route.coordinatesJson).length : 0;
        const statusClass = getStatusClass(route.status);
        
        if (type === 'hover') {
            return `
                <div style="padding: 8px; min-width: 200px;">
                    <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
                        <div style="width: 30px; height: 30px; background: ${route.colorHex || ROUTE_COLORS.DEFAULT}20; border-radius: 8px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-route" style="color: ${route.colorHex || ROUTE_COLORS.DEFAULT};"></i>
                        </div>
                        <div style="font-weight: 600; color: #1a1f36;">${route.name}</div>
                    </div>
                    ${route.description ? `<div style="font-size: 12px; color: #5b677c; margin-bottom: 4px;">${route.description}</div>` : ''}
                    <div style="display: flex; gap: 8px; margin-top: 4px;">
                        <span class="status-badge ${statusClass}">${route.status || 'PLANNED'}</span>
                        <span style="font-size: 11px; color: #94a3b8;">
                            <i class="fas fa-ruler"></i> ${distance.toFixed(1)} km
                        </span>
                    </div>
                </div>
            `;
        } else {
            return `
                <div style="padding: 12px; min-width: 300px;">
                    <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 12px;">
                        <div style="width: 40px; height: 40px; background: ${route.colorHex || ROUTE_COLORS.DEFAULT}20; border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-route" style="font-size: 18px; color: ${route.colorHex || ROUTE_COLORS.DEFAULT};"></i>
                        </div>
                        <div>
                            <div style="font-weight: 600; font-size: 16px; color: #1a1f36;">${route.name}</div>
                            <div style="font-size: 12px; color: #5b677c;">Route ID: ${route.id}</div>
                        </div>
                    </div>
                    
                    <div style="border-top: 1px solid #eaeef2; padding-top: 12px;">
                        ${route.description ? `
                            <div style="margin-bottom: 8px;">
                                <div style="font-size: 11px; color: #94a3b8; margin-bottom: 2px;">Description</div>
                                <div style="font-size: 13px; color: #1a1f36;">${route.description}</div>
                            </div>
                        ` : ''}
                        
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 8px;">
                            <div>
                                <div style="font-size: 11px; color: #94a3b8;">Status</div>
                                <div><span class="status-badge ${statusClass}">${route.status || 'PLANNED'}</span></div>
                            </div>
                            <div>
                                <div style="font-size: 11px; color: #94a3b8;">Distance</div>
                                <div style="font-size: 12px; color: #1a1f36;">${distance.toFixed(2)} km</div>
                            </div>
                            <div>
                                <div style="font-size: 11px; color: #94a3b8;">Waypoints</div>
                                <div style="font-size: 12px; color: #1a1f36;">${waypointCount}</div>
                            </div>
                            <div>
                                <div style="font-size: 11px; color: #94a3b8;">Est. Time</div>
                                <div style="font-size: 12px; color: #1a1f36;">${Math.round(distance / 50 * 60)} mins</div>
                            </div>
                        </div>
                        
                        ${route.assignedVehicleIds?.length ? `
                            <div style="margin-top: 8px;">
                                <div style="font-size: 11px; color: #94a3b8;">Assigned Vehicles</div>
                                <div style="display: flex; flex-wrap: wrap; gap: 4px; margin-top: 4px;">
                                    ${route.assignedVehicleIds.map(vehicleId => `
                                        <span style="background: #f0f2f5; padding: 2px 8px; border-radius: 12px; font-size: 11px; color: #1a1f36;">
                                            ${vehicleId}
                                        </span>
                                    `).join('')}
                                </div>
                            </div>
                        ` : ''}
                        
                        <div style="display: flex; gap: 8px; margin-top: 16px;">
                            <button onclick="editRoute('${route.id}')" style="flex: 1; padding: 8px; background: #000; color: white; border: none; border-radius: 8px; font-size: 12px; cursor: pointer;">
                                <i class="fas fa-edit"></i> Edit
                            </button>
                            <button onclick="optimizeRoute('${route.id}')" style="flex: 1; padding: 8px; background: #f0f2f5; color: #1a1f36; border: none; border-radius: 8px; font-size: 12px; cursor: pointer;">
                                <i class="fas fa-route"></i> Optimize
                            </button>
                        </div>
                    </div>
                </div>
            `;
        }
    }

    /***************************************************
     * ADD DISTANCE MARKERS
     ***************************************************/
    function addDistanceMarkers(polyline, coords) {
        for (let i = 0; i < coords.length - 1; i++) {
            const p1 = new google.maps.LatLng(coords[i].lat || coords[i][1], coords[i].lng || coords[i][0]);
            const p2 = new google.maps.LatLng(coords[i + 1].lat || coords[i + 1][1], coords[i + 1].lng || coords[i + 1][0]);
            
            // Calculate midpoint
            const midLat = (p1.lat() + p2.lat()) / 2;
            const midLng = (p1.lng() + p2.lng()) / 2;
            
            // Calculate distance
            const distance = google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000;
            
            // Create marker with distance label
            const marker = new google.maps.Marker({
                position: { lat: midLat, lng: midLng },
                map: deviceMap,
                icon: {
                    path: google.maps.SymbolPath.CIRCLE,
                    scale: 0,
                    labelOrigin: new google.maps.Point(0, 0)
                },
                label: {
                    text: distance.toFixed(1) + 'km',
                    color: '#1a1f36',
                    fontSize: '11px',
                    fontWeight: '600',
                    className: 'distance-label'
                }
            });
            
            routeShapes.push(marker);
        }
    }

    /***************************************************
     * HIGHLIGHT ROUTE
     ***************************************************/
    function highlightRoute(routeId) {
        // Reset all shapes
        routeShapes.forEach(shape => {
            if (shape instanceof google.maps.Polyline) {
                shape.setOptions({
                    strokeWeight: 4,
                    zIndex: 1
                });
            }
        });

        // Find and highlight selected shape
        const selectedShape = routeShapes.find(s => s.metadata && s.metadata.id === routeId);
        if (selectedShape) {
            selectedShape.setOptions({
                strokeWeight: 7,
                strokeColor: '#000000',
                zIndex: 100
            });
        }

        // Highlight in list
        $('.route-list-item').removeClass('selected');
        $(`.route-list-item[data-id="${routeId}"]`).addClass('selected');
    }

    /***************************************************
     * SHOW ROUTE DETAILS
     ***************************************************/
    function showRouteDetails(route) {
        const distance = calculateRouteDistance(JSON.parse(route.coordinatesJson || '[]'));
        const waypointCount = route.coordinatesJson ? JSON.parse(route.coordinatesJson).length : 0;
        const statusClass = getStatusClass(route.status);
        
        const detailsHtml = `
            <div style="padding: 24px;">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                    <h3 style="margin: 0; display: flex; align-items: center; gap: 12px;">
                        <i class="fas fa-route" style="color: ${route.colorHex || ROUTE_COLORS.DEFAULT};"></i>
                        ${route.name}
                    </h3>
                    <button onclick="hideRouteDetails()" style="background: none; border: none; cursor: pointer;">
                        <i class="fas fa-times" style="color: #94a3b8;"></i>
                    </button>
                </div>
                
                <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin-bottom: 20px;">
                    <div style="background: #f8fafc; padding: 12px; border-radius: 12px;">
                        <div style="font-size: 11px; color: #94a3b8;">Status</div>
                        <div><span class="status-badge ${statusClass}">${route.status || 'PLANNED'}</span></div>
                    </div>
                    <div style="background: #f8fafc; padding: 12px; border-radius: 12px;">
                        <div style="font-size: 11px; color: #94a3b8;">Distance</div>
                        <div style="font-weight: 600; color: #1a1f36;">${distance.toFixed(2)} km</div>
                    </div>
                    <div style="background: #f8fafc; padding: 12px; border-radius: 12px;">
                        <div style="font-size: 11px; color: #94a3b8;">Waypoints</div>
                        <div style="font-weight: 600; color: #1a1f36;">${waypointCount}</div>
                    </div>
                    <div style="background: #f8fafc; padding: 12px; border-radius: 12px;">
                        <div style="font-size: 11px; color: #94a3b8;">Est. Duration</div>
                        <div style="font-weight: 600; color: #1a1f36;">${Math.round(distance / 50 * 60)} mins</div>
                    </div>
                </div>
                
                ${route.description ? `
                    <div style="margin-bottom: 20px;">
                        <div style="font-size: 12px; color: #94a3b8; margin-bottom: 4px;">Description</div>
                        <div style="background: #f8fafc; padding: 12px; border-radius: 12px; color: #1a1f36;">
                            ${route.description}
                        </div>
                    </div>
                ` : ''}
                
                <div style="display: flex; gap: 12px; margin-bottom: 20px;">
                    <button onclick="showRouteWaypoints('${route.id}')" style="flex: 1; padding: 12px; background: #f0f2f5; color: #1a1f36; border: none; border-radius: 12px; cursor: pointer;">
                        <i class="fas fa-map-pin"></i> View Waypoints
                    </button>
                    <button onclick="downloadRouteGPX('${route.id}')" style="flex: 1; padding: 12px; background: #f0f2f5; color: #1a1f36; border: none; border-radius: 12px; cursor: pointer;">
                        <i class="fas fa-download"></i> Download GPX
                    </button>
                </div>
                
                <div style="display: flex; gap: 12px;">
                    <button onclick="editRoute('${route.id}')" style="flex: 1; padding: 12px; background: #000; color: white; border: none; border-radius: 12px; cursor: pointer;">
                        <i class="fas fa-edit"></i> Edit Route
                    </button>
                    <button onclick="deleteRoute('${route.id}')" style="flex: 1; padding: 12px; background: #fee2e2; color: #ef4444; border: none; border-radius: 12px; cursor: pointer;">
                        <i class="fas fa-trash"></i> Delete
                    </button>
                </div>
            </div>
        `;
        
        $('#selectedRoutePanel').html(detailsHtml).slideDown();
    }

    /***************************************************
     * SHOW ROUTE WAYPOINTS
     ***************************************************/
    function showRouteWaypoints(routeId) {
        const route = geofences.find(r => r.id == routeId);
        if (!route || !route.coordinatesJson) return;
        
        const coords = JSON.parse(route.coordinatesJson);
        let waypointsHtml = '';
        
        coords.forEach((coord, index) => {
            const lat = coord.lat || coord[1];
            const lng = coord.lng || coord[0];
            
            waypointsHtml += `
                <div class="waypoint-item">
                    <div class="waypoint-index">${index + 1}</div>
                    <div style="flex: 1;">
                        <div style="font-weight: 600; color: #1a1f36;">Waypoint ${index + 1}</div>
                        <div style="font-size: 11px; color: #5b677c;">
                            Lat: ${lat.toFixed(6)}, Lng: ${lng.toFixed(6)}
                        </div>
                    </div>
                    <button onclick="centerOnWaypoint(${lat}, ${lng})" style="background: none; border: none; cursor: pointer;">
                        <i class="fas fa-crosshairs" style="color: #94a3b8;"></i>
                    </button>
                </div>
            `;
        });
        
        $('#waypointsList').html(waypointsHtml);
        $('#waypointsPanel').slideDown();
        
        // Store current route for waypoint operations
        window.currentWaypointRoute = route;
    }

    /***************************************************
     * UTILITY FUNCTIONS
     ***************************************************/
    window.zoomIn = function() {
        if (deviceMap) {
            deviceMap.setZoom(deviceMap.getZoom() + 1);
        }
    };

    window.zoomOut = function() {
        if (deviceMap) {
            deviceMap.setZoom(deviceMap.getZoom() - 1);
        }
    };

    window.fitAllRoutes = function() {
        if (!deviceMap || routeShapes.length === 0) return;
        
        const bounds = new google.maps.LatLngBounds();
        routeShapes.forEach(shape => {
            if (shape instanceof google.maps.Polyline) {
                shape.getPath().forEach(p => bounds.extend(p));
            }
        });
        
        deviceMap.fitBounds(bounds);
    };

    window.selectRoute = function(routeId) {
        const route = geofences.find(r => r.id == routeId);
        if (route) {
            highlightRoute(routeId);
            showRouteDetails(route);
            
            // Find and center on the shape
            const shape = routeShapes.find(s => s.metadata && s.metadata.id == routeId);
            if (shape) {
                const bounds = new google.maps.LatLngBounds();
                shape.getPath().forEach(p => bounds.extend(p));
                deviceMap.fitBounds(bounds);
            }
        }
    };

    window.hideRouteDetails = function() {
        $('#selectedRoutePanel').slideUp();
    };

    window.hideWaypointsPanel = function() {
        $('#waypointsPanel').slideUp();
    };

    window.centerOnWaypoint = function(lat, lng) {
        deviceMap.panTo({ lat, lng });
        deviceMap.setZoom(16);
    };

    window.toggleRouteList = function() {
        $('#routeListPanel').toggleClass('collapsed');
    };

    window.toggleDistanceLayer = function() {
        if (distanceLayer) {
            distanceLayer = null;
            $('#distanceBtn').removeClass('active');
            // Redraw routes without distance markers
            drawRoutesOnly();
        } else {
            distanceLayer = true;
            $('#distanceBtn').addClass('active');
            // Redraw routes with distance markers
            drawRoutesOnly();
        }
    };

    window.toggleTrafficLayer = function() {
        if (window.trafficLayer) {
            window.trafficLayer.setMap(null);
            window.trafficLayer = null;
            $('#trafficBtn').removeClass('traffic-active');
        } else {
            window.trafficLayer = new google.maps.TrafficLayer();
            window.trafficLayer.setMap(deviceMap);
            $('#trafficBtn').addClass('traffic-active');
        }
    };

    window.exportRoutes = function() {
        const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(geofences, null, 2));
        const downloadAnchor = document.createElement('a');
        downloadAnchor.setAttribute("href", dataStr);
        downloadAnchor.setAttribute("download", "routes_export.json");
        document.body.appendChild(downloadAnchor);
        downloadAnchor.click();
        downloadAnchor.remove();
    };

    window.addNewRoute = function() {
        Swal.fire({
            title: 'Create New Route',
            html: `
                <input id="routeName" class="swal2-input" placeholder="Route Name">
                <textarea id="routeDesc" class="swal2-textarea" placeholder="Description"></textarea>
                <select id="routeStatus" class="swal2-select">
                    <option value="PLANNED">Planned</option>
                    <option value="ACTIVE">Active</option>
                </select>
            `,
            showCancelButton: true,
            confirmButtonText: 'Create',
            preConfirm: () => {
                const name = document.getElementById('routeName').value;
                if (!name) {
                    Swal.showValidationMessage('Please enter a name');
                    return false;
                }
                return {
                    name: name,
                    description: document.getElementById('routeDesc').value,
                    status: document.getElementById('routeStatus').value
                };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                // Enable drawing mode for route creation
                enableRouteDrawing();
            }
        });
    };

    function enableRouteDrawing() {
        // This would enable click-to-add waypoint mode
        $('#drawBtn').addClass('drawing-active');
        Swal.fire({
            title: 'Draw Route',
            text: 'Click on the map to add waypoints. Right-click to finish.',
            icon: 'info',
            timer: 3000,
            showConfirmButton: false
        });
        
        // Store waypoints array
        window.newRouteWaypoints = [];
    }

    function addWaypoint(latLng) {
        if (!window.newRouteWaypoints) return;
        
        window.newRouteWaypoints.push({
            lat: latLng.lat(),
            lng: latLng.lng()
        });
        
        // Add temporary marker
        new google.maps.Marker({
            position: latLng,
            map: deviceMap,
            icon: {
                path: google.maps.SymbolPath.CIRCLE,
                scale: 6,
                fillColor: '#3b82f6',
                fillOpacity: 1,
                strokeColor: '#ffffff',
                strokeWeight: 2
            },
            label: window.newRouteWaypoints.length.toString()
        });
    }

    window.editRoute = function(routeId) {
        alert('Edit route: ' + routeId + ' (To be implemented)');
    };

    window.deleteRoute = function(routeId) {
        if (confirm('Are you sure you want to delete this route?')) {
            alert('Delete route: ' + routeId + ' (To be implemented)');
        }
    };

    window.optimizeRoute = function(routeId) {
        alert('Optimize route: ' + routeId + ' (To be implemented)');
    };

    window.downloadRouteGPX = function(routeId) {
        const route = geofences.find(r => r.id == routeId);
        if (!route || !route.coordinatesJson) return;
        
        // Generate GPX content
        const coords = JSON.parse(route.coordinatesJson);
        let gpx = '<?xml version="1.0" encoding="UTF-8"?>\n';
        gpx += '<gpx version="1.1" creator="Fleet Management System">\n';
        gpx += '  <trk>\n';
        gpx += '    <name>' + route.name + '</name>\n';
        gpx += '    <trkseg>\n';
        
        coords.forEach(coord => {
            const lat = coord.lat || coord[1];
            const lng = coord.lng || coord[0];
            gpx += `      <trkpt lat="${lat}" lon="${lng}"></trkpt>\n`;
        });
        
        gpx += '    </trkseg>\n';
        gpx += '  </trk>\n';
        gpx += '</gpx>';
        
        // Download
        const blob = new Blob([gpx], { type: 'application/gpx+xml' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = route.name.replace(/\s+/g, '_') + '.gpx';
        a.click();
    };

    function formatDate(dateString) {
        if (!dateString) return 'N/A';
        const date = new Date(dateString);
        const now = new Date();
        const diff = Math.floor((now - date) / 1000);
        
        if (diff < 60) return 'just now';
        if (diff < 3600) return Math.floor(diff / 60) + ' minutes ago';
        if (diff < 86400) return Math.floor(diff / 3600) + ' hours ago';
        if (diff < 604800) return Math.floor(diff / 86400) + ' days ago';
        
        return date.toLocaleDateString();
    }

    // Make functions globally accessible
    window.selectRoute = selectRoute;
    window.hideRouteDetails = hideRouteDetails;
    window.hideWaypointsPanel = hideWaypointsPanel;
    window.centerOnWaypoint = centerOnWaypoint;
    window.toggleRouteList = toggleRouteList;
    window.toggleDistanceLayer = toggleDistanceLayer;
    window.toggleTrafficLayer = toggleTrafficLayer;
    window.fitAllRoutes = fitAllRoutes;
    window.zoomIn = zoomIn;
    window.zoomOut = zoomOut;
    window.exportRoutes = exportRoutes;
    window.addNewRoute = addNewRoute;
    window.editRoute = editRoute;
    window.deleteRoute = deleteRoute;
    window.optimizeRoute = optimizeRoute;
    window.downloadRouteGPX = downloadRouteGPX;
}