{% extends "mapsapp/map2d_base.html" %}
{% load static %}
{% block title %}Карта выбранных объектов{% endblock title %}

{% block extra_js %}
<script>
    // Цвета для стандартных маркеров (из leaflet-color-markers)
    var markerColors = ['red', 'green', 'orange', 'violet', 'grey', 'black', 'blue'];
    var getColorIcon = function(color) {
        return L.icon({
            iconUrl: '{% static "leaflet-markers/img/marker-icon-" %}' + color + '.png',
            shadowUrl: '{% static "leaflet-markers/img/marker-shadow.png" %}',
            iconSize: [25, 41],
            iconAnchor: [12, 41],
            popupAnchor: [1, -34],
            shadowSize: [41, 41]
        });
    };

    var overlays = [];

    {% for group in groups %}
        var groupIndex = {{ forloop.counter0 }};
        var colorName = markerColors[groupIndex % markerColors.length];
        var groupIcon = getColorIcon(colorName);

        var groupLayer = L.layerGroup();

        var subgroup = [];
        {% for point_data in group.points %}
            var pointName = "{{ group.name|escapejs }}";

            var marker = L.marker([{{ point_data.point.1|safe }}, {{ point_data.point.0|safe }}], {
                icon: groupIcon
            }).bindPopup(pointName + '<br>' + "{{ point_data.frequency|escapejs }}");

            groupLayer.addLayer(marker);

            subgroup.push({
                label: "{{ forloop.counter }} - {{ point_data.frequency }}",
                layer: marker
            });
        {% endfor %}

        overlays.push({
            label: '{{ group.name|escapejs }}',
            selectAllCheckbox: true,
            children: subgroup,
            layer: groupLayer
        });
    {% endfor %}

    // Create the layer control with a custom container that includes a select all checkbox
    var layerControl = L.control.layers.tree(baseLayers, overlays, {
        collapsed: false,
        autoZIndex: true
    });

    // Add the layer control to the map
    layerControl.addTo(map);

    // Calculate map bounds to fit all markers
    {% if groups %}
        var groupBounds = L.featureGroup([]);
        {% for group in groups %}
            {% for point_data in group.points %}
                groupBounds.addLayer(L.marker([{{ point_data.point.1|safe }}, {{ point_data.point.0|safe }}]));
            {% endfor %}
        {% endfor %}
        map.fitBounds(groupBounds.getBounds().pad(0.1)); // Add some padding
    {% else %}
        map.setView([55.75, 37.62], 5); // Default view if no markers
    {% endif %}

    // Add a "Select All" checkbox functionality for all overlays
    setTimeout(function() {
        // Create a custom "select all" checkbox
        var selectAllContainer = document.createElement('div');
        selectAllContainer.className = 'leaflet-control-layers-select-all';
        selectAllContainer.style.padding = '5px';
        selectAllContainer.style.borderBottom = '1px solid #ccc';
        selectAllContainer.style.marginBottom = '5px';
        selectAllContainer.innerHTML = '<label><input type="checkbox" id="select-all-overlays" checked> Показать все точки</label>';
        
        // Insert the checkbox at the top of the layer control
        var layerControlContainer = document.querySelector('.leaflet-control-layers-list');
        if (layerControlContainer) {
            layerControlContainer.insertBefore(selectAllContainer, layerControlContainer.firstChild);
        }

        // Add event listener to the "select all" checkbox
        document.getElementById('select-all-overlays').addEventListener('change', function() {
            var isChecked = this.checked;
            
            // Iterate through all overlays and toggle visibility
            for (var i = 0; i < overlays.length; i++) {
                if (isChecked) {
                    map.addLayer(overlays[i].layer);
                } else {
                    map.removeLayer(overlays[i].layer);
                }
            }
        });
    }, 500); // Slight delay to ensure the tree control has been rendered
</script>
{% endblock extra_js %}