{% extends 'generic/object_list.html' %}
{% load static %}
{% load helpers %}
{% load buttons %}
{% load helpers %}
{% load plugins %}
{% load render_table from django_tables2 %}
{% load i18n %}

{% block title %}Segments Map View{% endblock %}

{% block content %}
   {# Object list tab #}
    <div class="tab-pane show active" id="object-list" role="tabpanel" aria-labelledby="object-list-tab">

      {# Applied filters #}
      {% if filter_form %}
        {% applied_filters model filter_form request.GET %}
      {% endif %}

      {# Object table controls #}
      
      <form method="post" class="form form-horizontal">
        {% csrf_token %}
        {# "Select all" form #}
        {% if table.paginator.num_pages > 1 %}
          <div id="select-all-box" class="d-none card d-print-none">
            <div class="form col-md-12">
              <div class="card-body d-flex justify-content-between">
                <div class="form-check">
                  <input type="checkbox" id="select-all" name="_all" class="form-check-input" />
                  <label for="select-all" class="form-check-label">
                    {% blocktrans trimmed with count=table.page.paginator.count object_type_plural=table.data.verbose_name_plural %}
                      Select <strong>all <span class="total-object-count">{{ count }}</span> {{ object_type_plural }}</strong> matching query
                    {% endblocktrans %}
                  </label>
                </div>
                <div class="bulk-action-buttons">
                  {% if 'bulk_edit' in actions %}
                    {% bulk_edit_button model query_params=request.GET %}
                  {% endif %}
                  {% if 'bulk_delete' in actions %}
                    {% bulk_delete_button model query_params=request.GET %}
                  {% endif %}
                </div>
              </div>
            </div>
          </div>
        {% endif %}

        <div class="form form-horizontal">
          {% csrf_token %}
          <input type="hidden" name="return_url" value="{% if return_url %}{{ return_url }}{% else %}{{ request.path }}{% if request.GET %}?{{ request.GET.urlencode }}{% endif %}{% endif %}" />

          {# Warn of any missing prerequisite objects #}
          {% if prerequisite_model %}
            {% include 'inc/missing_prerequisites.html' %}
          {% endif %}

          {# Objects table #}
<div class="row">
    <!-- Full Width Map Area -->
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="mdi mdi-map" aria-hidden="true"></i>
                    Segments Map
                    <span class="badge bg-info text-dark">{{ segments_count }} segments</span>
                </h5>
                <div class="card-actions">
                    <a href="{% url 'plugins:cesnet_service_path_plugin:segment_list' %}{% if request.GET %}?{{ request.GET.urlencode }}{% endif %}" class="btn btn-outline-secondary btn-sm">
                        <i class="mdi mdi-table" aria-hidden="true"></i> Table View
                    </a>
                    
                    <!-- Color Scheme Selector -->                    
                    <div class="btn-group ms-2" role="group">
                        <button type="button" class="btn btn-outline-info btn-sm dropdown-toggle" data-bs-toggle="dropdown" id="colorSchemeButton">
                            <i class="mdi mdi-palette" aria-hidden="true"></i> <span id="currentColorScheme">Status</span>
                        </button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="#" data-scheme="status">
                                <i class="mdi mdi-circle-medium" style="color: #198754;"></i> By Status
                            </a></li>
                            <li><a class="dropdown-item" href="#" data-scheme="provider">
                                <i class="mdi mdi-circle-medium" style="color: #e74c3c;"></i> By Provider
                            </a></li>
                            <li><a class="dropdown-item" href="#" data-scheme="segment_type">
                                <i class="mdi mdi-circle-medium" style="color: #9c27b0;"></i> By Segment Type
                            </a></li>
                        </ul>
                    </div>
                    
                    <!-- Map Legend -->
                    <div class="btn-group ms-2" role="group">
                        <button type="button" class="btn btn-outline-info btn-sm dropdown-toggle" data-bs-toggle="dropdown">
                            <i class="mdi mdi-map-legend" aria-hidden="true"></i> Legend
                        </button>
                        <ul class="dropdown-menu" id="legendDropdown">
                            <!-- Legend content will be populated by JavaScript -->
                        </ul>
                    </div>
                    
                    <!-- Map Controls -->
                     <button type="button" id="fitBounds" class="btn btn-outline-primary btn-sm">
                        <i class="mdi mdi-fit-to-page-outline" aria-hidden="true"></i> Fit All
                    </button>
                    <!-- Use the shared layer dropdown -->
                    {% include './inc/map_layer_dropdown.html' %}
                </div>
            </div>
            <div class="card-body">
                {% if map_warning %}
                    <div class="alert alert-warning" role="alert">
                        <i class="mdi mdi-alert" aria-hidden="true"></i>
                        {{ map_warning }}
                    </div>
                {% endif %}
                
                {% if segments_count == 0 %}
                    <div class="alert alert-info" role="alert">
                        <i class="mdi mdi-information" aria-hidden="true"></i>
                        No segments match the current filters.
                    </div>
                {% else %}
                    <!-- Map Container -->
                    <div id="map" style="height: 800px; width: 100%; border: 1px solid #ddd; border-radius: 4px;"></div>
                    
                    <!-- Load Leaflet -->
                    {% include './inc/leaflet_includes.html' %}
                    
                    <!-- Load custom styles for overlapping segments -->
                    {% include './inc/map_layers_styles.html' %}
                    
                    <!-- Segment Info Panel (Initially Hidden) -->
                    <div id="segmentInfo" class="mt-3" style="display: none;">
                        <div class="card">
                            <div class="card-header">
                                <h6 class="card-title mb-0">Selected Segment</h6>
                                <button type="button" class="btn-close" onclick="hideSegmentInfo()"></button>
                            </div>
                            <div class="card-body" id="segmentInfoContent">
                                <!-- Content will be populated by JavaScript -->
                            </div>
                        </div>
                    </div>
                    
                    <!-- Template data as JSON -->
                    <script type="application/json" id="map-data">
                    {
                        "segments": {{ segments_data_json|safe }},
                        "mapBounds": {{ map_bounds_json|safe }},
                        "mapCenter": {{ map_center_json|safe }},
                        "apiUrl": "{{ api_url }}"
                    }
                    </script>

                    <!-- Include common layer configuration -->
                    {% include './inc/map_layers_config.html' %}

                    <script>
                    // Parse template data
                    const mapData = JSON.parse(document.getElementById('map-data').textContent);
                    const segmentsData = mapData.segments;
                    const mapBounds = mapData.mapBounds;
                    const mapCenter = mapData.mapCenter;
                    const apiUrl = mapData.apiUrl;

                    // Create map
                    const map = L.map('map').setView([mapCenter.lat, mapCenter.lng], mapCenter.zoom);

                    // Initialize layers using common function
                    initializeMapLayers(map);

                    // Layer groups for different types
                    const pathLayers = L.layerGroup().addTo(map);
                    const siteLayers = L.layerGroup().addTo(map);

                    // Color schemes
                    let currentColorScheme = 'status';

                    // Status color mapping
                    const statusColorsLine = {
                        "Active": "#198754",       // Dark Green
                        "Planned": "#3b82f6",      // Blue
                        "Offline": "#dc3545",      // Red
                        "Maintenance": "#ff8c00",  // Dark Orange
                        "Decommissioned": "#6c757d" // Gray
                    };

                    const statusBadge = {
                        "Active": "success",
                        "Planned": "primary", 
                        "Offline": "danger",
                        "Decommissioned": "secondary"
                    };

                    // Provider color mapping - generate colors dynamically
                    const providerColors = {};

                    // NEW: Segment type color mapping
                    const segmentTypeColors = {
                        "Dark Fiber": "#9c27b0",      // Purple (matches your SegmentTypeChoices)
                        "Optical Spectrum": "#ff9800", // Orange (matches your SegmentTypeChoices)  
                        "Ethernet Service": "#4caf50"  // Green (matches your SegmentTypeChoices)
                    };

                    // Generate color palette for providers
                    const colorPalette = [
                        '#d32f2f', // strong red    
                        '#1976d2', // strong blue
                        '#512da8', // deep purple
                        '#f57c00', // vivid orange
                        '#7b1fa2', // purple
                        '#c2185b', // magenta
                        '#303f9f', // deep indigo
                        '#00796b', // teal (dark enough)
                        '#455a64', // dark gray-blue
                        '#ff1744', // bright pink-red
                        '#00bcd4', // cyan
                        '#e64a19', // orange-red
                        '#5d4037', // brown
                        '#3f51b5', // indigo
                        '#9c27b0', // purple
                        '#ff5722', // orange
                        '#b71c1c', // deep red
                        '#0d47a1', // navy blue
                        '#ad1457', // dark pink
                        '#4a148c'  // very dark purple
                    ];

                    // Build provider color mappings from segments data
                    function buildProviderColors() {
                        const uniqueProviders = [...new Set(segmentsData.map(s => s.provider).filter(p => p))];
                        uniqueProviders.forEach((provider, index) => {
                            providerColors[provider] = colorPalette[index % colorPalette.length];
                        });
                    }

                    // Initialize provider colors
                    buildProviderColors();

                    // Store all segments with their layers
                    let segmentLayers = new Map(); // segmentId -> layer

                    // Function to get segment color based on current scheme
                    function getSegmentColor(segment) {
                        if (currentColorScheme === 'status') {
                            return statusColorsLine[segment.status] || '#dc3545';
                        } else if (currentColorScheme === 'provider') {
                            return providerColors[segment.provider] || '#6c757d';
                        } else if (currentColorScheme === 'segment_type') {
                            return segmentTypeColors[segment.segment_type] || '#6c757d';
                        }
                        return '#dc3545';
                    }

                    // Function to get status badge color 
                    function getStatusBadgeColor(segment) {
                        return statusBadge[segment.status] || 'secondary';
                    }

                    // Function to generate path data badge
                    function getPathDataBadge(segment) {
                        return segment.has_path_data 
                            ? '<span class="badge text-bg-success">Has Path Data</span>'
                            : '<span class="badge text-bg-warning">No Path Data</span>';
                    }

                    // Function to update legend based on current color scheme
                    function updateLegend() {
                        const legendDropdown = document.getElementById('legendDropdown');
                        legendDropdown.innerHTML = '';
                        
                        if (currentColorScheme === 'status') {
                            // Status legend
                            Object.entries(statusColorsLine).forEach(([status, color]) => {
                                const li = document.createElement('li');
                                li.innerHTML = `<span class="dropdown-item-text small">
                                    <span style="display: inline-block; width: 20px; height: 3px; background-color: ${color}; margin-right: 8px;"></span>
                                    ${status}
                                </span>`;
                                legendDropdown.appendChild(li);
                            });
                        } else if (currentColorScheme === 'provider') {
                            // Provider legend
                            Object.entries(providerColors).forEach(([provider, color]) => {
                                const li = document.createElement('li');
                                li.innerHTML = `<span class="dropdown-item-text small">
                                    <span style="display: inline-block; width: 20px; height: 3px; background-color: ${color}; margin-right: 8px;"></span>
                                    ${provider}
                                </span>`;
                                legendDropdown.appendChild(li);
                            });
                        } else if (currentColorScheme === 'segment_type') {
                            // NEW: Segment type legend
                            Object.entries(segmentTypeColors).forEach(([segmentType, color]) => {
                                const li = document.createElement('li');
                                li.innerHTML = `<span class="dropdown-item-text small">
                                    <span style="display: inline-block; width: 20px; height: 3px; background-color: ${color}; margin-right: 8px;"></span>
                                    ${segmentType}
                                </span>`;
                                legendDropdown.appendChild(li);
                            });
                        }
                        
                        // Add common legend items
                        const divider = document.createElement('li');
                        divider.innerHTML = '<hr class="dropdown-divider">';
                        legendDropdown.appendChild(divider);
                        
                        const pathInfo = document.createElement('li');
                        pathInfo.innerHTML = `<span class="dropdown-item-text small">
                            <strong>Solid line:</strong> Actual path data<br>
                            <strong>Dashed line:</strong> No path data
                        </span>`;
                        legendDropdown.appendChild(pathInfo);
                    }

                    // Function to switch color scheme
                    function switchColorScheme(scheme) {
                        currentColorScheme = scheme;
                        
                        // Update button text
                        const schemeButton = document.getElementById('currentColorScheme');
                        if (scheme === 'status') {
                            schemeButton.textContent = 'Status';
                        } else if (scheme === 'provider') {
                            schemeButton.textContent = 'Provider';
                        } else if (scheme === 'segment_type') {
                            schemeButton.textContent = 'Segment Type';
                        }
                        
                        // Update legend
                        updateLegend();
                        
                        // Reload segments with new colors
                        loadSegmentsWithOverlapHandling();
                    }

                    
                    // Function to show segment info in the info panel under the map
                    function showSegmentInfo(segment) {
                        const infoPanel = document.getElementById('segmentInfo');
                        const infoContent = document.getElementById('segmentInfoContent');

                        const pathDataBadge = getPathDataBadge(segment);
                        
                        const badgeColor = getStatusBadgeColor(segment);
                        
                        infoContent.innerHTML = `
                            <div class="row">
                                <div class="col-md-6">
                                    <h4>${segment.name}</h4>
                                    <p><strong>Provider:</strong> ${segment.provider || 'N/A'}</p>
                                    <p><strong>Status:</strong> <span class="badge text-bg-${badgeColor}">${segment.status}</span></p>
                                    <p><strong>Path Data:</strong> ${pathDataBadge}</p>
                                </div>
                                <div class="col-md-6">
                                    <p><strong>Sites:</strong> ${segment.site_a ? segment.site_a.name : 'N/A'} ↔ ${segment.site_b ? segment.site_b.name : 'N/A'}</p>
                                    <p><strong>Length:</strong> ${segment.path_length_km ? segment.path_length_km + ' km' : 'Unknown'}</p>
                                    <div class="mt-2">
                                        <a href="${segment.url}" class="btn btn-primary btn-sm">View Details</a>
                                        <a href="/plugins/cesnet-service-path-plugin/segments/${segment.id}/map/" class="btn btn-outline-secondary btn-sm">Individual Map</a>
                                    </div>
                                </div>
                            </div>
                        `;
                        
                        infoPanel.style.display = 'block';
                    }
                    
                    // Function to hide segment info
                    function hideSegmentInfo() {
                        document.getElementById('segmentInfo').style.display = 'none';
                    }
                    
                    // Visual-based overlap detection using screen coordinates
                    function handleSegmentClick(e) {
                        e.originalEvent.preventDefault();
                        const clickPoint = e.latlng;
                        const clickScreenPoint = map.latLngToContainerPoint(clickPoint);
                        
                        // Find all segments that are visually close to the click
                        const visuallyOverlappingSegments = [];
                        const screenTolerance = 10; // pixels
                        
                        segmentLayers.forEach((layer, segmentId) => {
                            const segment = segmentsData.find(s => s.id.toString() === segmentId.toString());
                            if (!segment) return;
                            
                            let isVisuallyNear = false;
                            
                            // Check if layer is visually near the click point
                            if (layer instanceof L.Polyline) {
                                isVisuallyNear = checkPolylineVisualProximity(layer, clickScreenPoint, screenTolerance);
                            } else if (layer.eachLayer) {
                                // Handle GeoJSON layers
                                layer.eachLayer(function(subLayer) {
                                    if (subLayer instanceof L.Polyline && !isVisuallyNear) {
                                        isVisuallyNear = checkPolylineVisualProximity(subLayer, clickScreenPoint, screenTolerance);
                                    }
                                });
                            }
                            
                            if (isVisuallyNear) {
                                visuallyOverlappingSegments.push({
                                    layer: layer,
                                    segment: segment
                                });
                            }
                        });
                        
                        // Now find which segments are truly overlapping (sharing visual space)
                        const trueOverlaps = findVisualOverlaps(visuallyOverlappingSegments, clickScreenPoint, screenTolerance);
                        
                        if (trueOverlaps.length === 1) {
                            showSingleSegmentPopup(trueOverlaps[0].segment, clickPoint);
                            showSegmentInfo(trueOverlaps[0].segment);
                        } else if (trueOverlaps.length > 1) {
                            showOverlappingSegmentsPopup(trueOverlaps, clickPoint);
                            showSegmentInfo(trueOverlaps[0].segment);
                        }
                    }

                    function checkPolylineVisualProximity(polyline, clickScreenPoint, tolerance) {
                        const latlngs = polyline.getLatLngs();
                        const flatLatLngs = Array.isArray(latlngs[0]) ? latlngs.flat() : latlngs;
                        
                        for (let i = 0; i < flatLatLngs.length - 1; i++) {
                            const point1 = map.latLngToContainerPoint(flatLatLngs[i]);
                            const point2 = map.latLngToContainerPoint(flatLatLngs[i + 1]);
                            
                            const distance = distanceToLineSegmentScreen(clickScreenPoint, point1, point2);
                            if (distance <= tolerance) {
                                return true;
                            }
                        }
                        return false;
                    }

                    function distanceToLineSegmentScreen(point, lineStart, lineEnd) {
                        const A = point.x - lineStart.x;
                        const B = point.y - lineStart.y;
                        const C = lineEnd.x - lineStart.x;
                        const D = lineEnd.y - lineStart.y;

                        const dot = A * C + B * D;
                        const lenSq = C * C + D * D;
                        let param = -1;
                        if (lenSq !== 0) param = dot / lenSq;

                        let xx, yy;
                        if (param < 0) {
                            xx = lineStart.x;
                            yy = lineStart.y;
                        } else if (param > 1) {
                            xx = lineEnd.x;
                            yy = lineEnd.y;
                        } else {
                            xx = lineStart.x + param * C;
                            yy = lineStart.y + param * D;
                        }

                        const dx = point.x - xx;
                        const dy = point.y - yy;
                        return Math.sqrt(dx * dx + dy * dy);
                    }

                    function findVisualOverlaps(segments, clickScreenPoint, tolerance) {
                        if (segments.length <= 1) return segments;
                        
                        // Group segments that share similar screen coordinates
                        const groups = [];
                        
                        for (const segmentInfo of segments) {
                            let addedToGroup = false;
                            
                            for (const group of groups) {
                                // Check if this segment visually overlaps with segments in this group
                                if (checkSegmentGroupOverlap(segmentInfo, group, tolerance)) {
                                    group.push(segmentInfo);
                                    addedToGroup = true;
                                    break;
                                }
                            }
                            
                            if (!addedToGroup) {
                                groups.push([segmentInfo]);
                            }
                        }
                        
                        // Return the group that contains the most segments near the click point
                        let bestGroup = groups[0];
                        let bestScore = 0;
                        
                        for (const group of groups) {
                            let score = 0;
                            for (const segmentInfo of group) {
                                // Check how close this segment is to the click point
                                const layer = segmentInfo.layer;
                                if (layer instanceof L.Polyline) {
                                    if (checkPolylineVisualProximity(layer, clickScreenPoint, tolerance)) {
                                        score += 1;
                                    }
                                } else if (layer.eachLayer) {
                                    layer.eachLayer(function(subLayer) {
                                        if (subLayer instanceof L.Polyline) {
                                            if (checkPolylineVisualProximity(subLayer, clickScreenPoint, tolerance)) {
                                                score += 1;
                                            }
                                        }
                                    });
                                }
                            }
                            
                            if (score > bestScore) {
                                bestScore = score;
                                bestGroup = group;
                            }
                        }
                        
                        return bestGroup;
                    }

                    function checkSegmentGroupOverlap(segmentInfo, group, tolerance) {
                        // Simplified check - compare with first segment in group
                        if (group.length === 0) return false;
                        
                        const firstSegment = group[0];
                        
                        const segment1 = segmentInfo.segment;
                        const segment2 = firstSegment.segment;
                        
                        // If both segments don't have path data, check if they share endpoints
                        if (!segment1.has_path_data && !segment2.has_path_data) {
                            if (segment1.site_a && segment1.site_b && segment2.site_a && segment2.site_b) {
                                const tolerance_deg = 0.001;
                                const sameEndpoints = (
                                    Math.abs(segment1.site_a.lat - segment2.site_a.lat) < tolerance_deg &&
                                    Math.abs(segment1.site_a.lng - segment2.site_a.lng) < tolerance_deg &&
                                    Math.abs(segment1.site_b.lat - segment2.site_b.lat) < tolerance_deg &&
                                    Math.abs(segment1.site_b.lng - segment2.site_b.lng) < tolerance_deg
                                ) || (
                                    Math.abs(segment1.site_a.lat - segment2.site_b.lat) < tolerance_deg &&
                                    Math.abs(segment1.site_a.lng - segment2.site_b.lng) < tolerance_deg &&
                                    Math.abs(segment1.site_b.lat - segment2.site_a.lat) < tolerance_deg &&
                                    Math.abs(segment1.site_b.lng - segment2.site_a.lng) < tolerance_deg
                                );
                                return sameEndpoints;
                            }
                            return false;
                        }
                        
                        // If both have path data, they could be truly overlapping routes
                        if (segment1.has_path_data && segment2.has_path_data) {
                            return true; // Let visual proximity determine this
                        }
                        
                        // Mixed case - probably not overlapping
                        return false;
                    }

                    
                    // Show popup for single segment
                    function showSingleSegmentPopup(segment, clickPoint) {
                        const badgeColor = getStatusBadgeColor(segment);
                        const pathDataBadge = getPathDataBadge(segment);
                        
                        const popupContent = `
                            <div class="single-segment-popup">
                                <h4 class="mt-4">${segment.name}</h4>
                                <p class="mb-1"><strong>Provider:</strong> ${segment.provider || 'N/A'}</p>
                                <p class="mb-1"><strong>Status:</strong> <span class="badge text-bg-${badgeColor}">${segment.status}</span></p>
                                <p class="mb-1"><strong>Path Data:</strong> ${pathDataBadge}</p>
                                <p class="mb-1"><strong>Route:</strong> ${segment.site_a ? segment.site_a.name : 'N/A'} ↔ ${segment.site_b ? segment.site_b.name : 'N/A'}</p>
                                <p class="mb-2"><strong>Length:</strong> ${segment.path_length_km ? segment.path_length_km + ' km' : 'Unknown'}</p>
                                <div class="text-center">
                                    <small class="text-muted">See detailed info below ↓</small>
                                </div>
                            </div>
                        `;
                        
                        L.popup({
                            maxWidth: 300,
                            className: 'single-segment-popup'
                        })
                        .setLatLng(clickPoint)
                        .setContent(popupContent)
                        .openOn(map);
                    }

                    // Show popup for overlapping segments
                    function showOverlappingSegmentsPopup(overlappingLayers, clickPoint) {
                        const popupContent = createOverlappingSegmentsContent(overlappingLayers);
                        
                        L.popup({
                            maxWidth: 400,
                            className: 'overlapping-segments-popup'
                        })
                        .setLatLng(clickPoint)
                        .setContent(popupContent)
                        .openOn(map);
                    }

                    // Create content for overlapping segments popup
                    function createOverlappingSegmentsContent(overlappingLayers) {
                        let content = `
                            <div class="overlapping-segments">
                                <h4><i class="mdi mdi-layers"></i> Multiple Segments (${overlappingLayers.length})</h4>
                        `;
                        
                        overlappingLayers.forEach((layerInfo, index) => {
                            const segment = layerInfo.segment;
                            const badgeColor = getStatusBadgeColor(segment);
                            const displayValue = segment.status;
                            const pathDataBadge = getPathDataBadge(segment);

                            content += `
                                <div class="segment-option border-bottom border-dark border-1 pb-2 mb-2" style="cursor: pointer;" 
                                    onclick="selectOverlappingSegment('${segment.id}')">
                                    <div>
                                        <p class="mb-1">
                                        <strong>${segment.name}</strong>
                                        </p>
                                        <ul class="list-unstyled mb-0">
                                            <li><strong>Sites:</strong> ${segment.site_a ? segment.site_a.name : 'N/A'} ↔ ${segment.site_b ? segment.site_b.name : 'N/A'}</li>
                                            <li><strong>Status:</strong> <span class="badge text-bg-${badgeColor}">${displayValue}</span></li>
                                            <li><strong>Path Data:</strong> ${pathDataBadge}</li>
                                            <li><strong>Length:</strong> ${segment.path_length_km ? segment.path_length_km + ' km' : 'Unknown'}</li>
                                        </ul>
                                    
                                    </div>
                                </div>
                            `;
                        });
                        
                        content += `
                                <div class="text-center mt-2">
                                    <small class="text-muted">Click on a segment above to view details</small>
                                </div>
                            </div>
                        `;
                        
                        return content;
                    }

                    // Handle selection from overlapping segments popup
                    function selectOverlappingSegment(segmentId) {
                        const segment = segmentsData.find(s => s.id.toString() === segmentId.toString());
                        if (segment) {
                            showSegmentInfo(segment);
                        }
                    }

                    // Enhanced loadSegments function with overlap handling
                    function loadSegmentsWithOverlapHandling() {
                        // Clear existing layers and tracking
                        pathLayers.clearLayers();
                        siteLayers.clearLayers();
                        segmentLayers.clear();
                        
                        // Add site markers and fallback lines
                        segmentsData.forEach(segment => {
                            const color = getSegmentColor(segment);
                            
                            // Add site markers
                            if (segment.site_a) {
                                const markerA = L.circleMarker([segment.site_a.lat, segment.site_a.lng], {
                                    radius: 6,
                                    fillColor: '#007bff',
                                    color: '#ffffff',
                                    weight: 2,
                                    opacity: 1,
                                    fillOpacity: 0.8
                                });
                                
                                markerA.bindPopup(`<strong>Site A:</strong> ${segment.site_a.name}<br><strong>Segment:</strong> ${segment.name}`);
                                siteLayers.addLayer(markerA);
                            }
                            
                            if (segment.site_b) {
                                const markerB = L.circleMarker([segment.site_b.lat, segment.site_b.lng], {
                                    radius: 6,
                                    fillColor: '#28a745',
                                    color: '#ffffff',
                                    weight: 2,
                                    opacity: 1,
                                    fillOpacity: 0.8
                                });
                                
                                markerB.bindPopup(`<strong>Site B:</strong> ${segment.site_b.name}<br><strong>Segment:</strong> ${segment.name}`);
                                siteLayers.addLayer(markerB);
                            }
                            
                            // Add fallback line if no path data but both sites have coordinates
                            if (!segment.has_path_data && segment.site_a && segment.site_b) {
                                const fallbackLine = L.polyline([
                                    [segment.site_a.lat, segment.site_a.lng],
                                    [segment.site_b.lat, segment.site_b.lng]
                                ], {
                                    color: color,
                                    weight: 3,
                                    opacity: 0.7,
                                    dashArray: '5, 10'
                                });
                                
                                // Use enhanced click handler and disable default popup
                                fallbackLine.on('click', handleSegmentClick);
                                
                                pathLayers.addLayer(fallbackLine);
                                segmentLayers.set(segment.id.toString(), fallbackLine);
                            }
                        });
                        
                        // Load actual path data via API
                        const currentUrl = new URL(window.location);
                        const apiUrlWithParams = apiUrl + currentUrl.search;
                        
                        fetch(apiUrlWithParams)
                            .then(response => response.json())
                            .then(data => {
                                if (data.features && data.features.length > 0) {
                                    data.features.forEach(feature => {
                                        if (feature.properties.type === 'path') {
                                            // Find segment to get current color
                                            const segment = segmentsData.find(s => s.id === feature.properties.id);
                                            const color = segment ? getSegmentColor(segment) : '#dc3545';
                                            
                                            // Actual path data
                                            const pathLayer = L.geoJSON(feature, {
                                                style: {
                                                    color: color,
                                                    weight: 4,
                                                    opacity: 0.8
                                                }
                                            });
                                            
                                            // Use enhanced click handler and disable default popup
                                            pathLayer.on('click', handleSegmentClick);
                                            
                                            pathLayers.addLayer(pathLayer);
                                            segmentLayers.set(feature.properties.id.toString(), pathLayer);
                                        }
                                    });
                                }
                                
                                // Fit map to show all segments
                                setTimeout(fitMapToSegments, 100);
                            })
                            .catch(error => {
                                console.error('Error loading segment paths:', error);
                                setTimeout(fitMapToSegments, 100);
                            });
                    }
                    
                    // Function to fit map to all segments
                    function fitMapToSegments() {
                        if (mapBounds.minLat !== null && mapBounds.maxLat !== null) {
                            const bounds = L.latLngBounds(
                                [mapBounds.minLat, mapBounds.minLng],
                                [mapBounds.maxLat, mapBounds.maxLng]
                            );
                            map.fitBounds(bounds, {padding: [20, 20]});
                        }
                    }
                    
                    // Make functions global
                    window.hideSegmentInfo = hideSegmentInfo;
                    window.selectOverlappingSegment = selectOverlappingSegment;
                    
                    // Control handlers
                    document.getElementById('fitBounds').onclick = function() {
                        fitMapToSegments();
                    };
                    
                    // Color scheme switching
                    document.addEventListener('DOMContentLoaded', function() {
                        document.querySelectorAll('[data-scheme]').forEach(item => {
                            item.addEventListener('click', function(e) {
                                e.preventDefault();
                                const scheme = this.getAttribute('data-scheme');
                                switchColorScheme(scheme);
                            });
                        });
                    });

                    // Initialize layer switching functionality
                    initializeLayerSwitching(map);

                    // Initialize legend
                    updateLegend();

                    // Load segments on page load with overlap handling
                    loadSegmentsWithOverlapHandling();
                    </script>
                {% endif %}
            </div>
        </div>
    </div>
</div>
{# /Objects table #}

          {# Form buttons #}
          <div class="btn-list d-print-none">
            {% block bulk_buttons %}
              <div class="bulk-action-buttons">
                {% if 'bulk_edit' in actions %}
                  {% bulk_edit_button model query_params=request.GET %}
                {% endif %}
                {% if 'bulk_delete' in actions %}
                  {% bulk_delete_button model query_params=request.GET %}
                {% endif %}
              </div>
            {% endblock %}
          </div>
          {# /Form buttons #}

        </div>
      </form>
    </div>
    {# /Object list tab #}

    {# Filters tab #}
    {% if filter_form %}
      <div class="tab-pane show" id="filters-form" role="tabpanel" aria-labelledby="filters-form-tab">
        {% include 'inc/filter_list.html' %}
      </div>
    {% endif %}
    {# /Filters tab #}

{% endblock content %}