{% extends 'base.html' %}

{% block content %}
        <div id="map" style="height: 100%; position: static;"></div>
        <script>
        // document.addEventListener('DOMContentLoaded', function() {
            var map = new L.map('map', {center: [20.57, -100.38], zoom:16, zoomControl: false });
            console.warn("Mapa creado");
            // Initialize user_marker with a default position
            var user_marker = new L.marker([20.57, -100.38]).addTo(map);
            document.addEventListener('DOMContentLoaded', function() {
                getLocation();
            });
            var user_radial = new L.circle([20.57, -100.38], {radius:200}).addTo(map);
            console.warn("Mapa cargado");
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '© OpenStreetMap contributors',
                detectRetina: true,
                tileSize: 256,
                maxZoom: 20,
                maxNativeZoom: 18,
                //zoomOffset: 1,
            }).addTo(map);
            //types of markers
            var iconTypes = {
                'bache': '<i class="indicator fas fa-exclamation-triangle"></i>',
                'coladera': '<i class="indicator fas fa-ring"></i>',
                'obra sin terminar': '<i class="indicator fas fa-wrench"></i>',
                'escombro': '<i class="indicator far fa-trash-alt"></i>',
                'robo-asalto': '<i class="indicator fas fa-skull"></i>',
                'biciestacionamiento': '<i class="indicator fas fa-flag-checkered"></i>',
                'mala iluminación': '<i class="indicator far fa-lightbulb"></i>',
                'bici blanca': '<i style="color:white" class="indicator fas fa-bicycle"></i>',
                'zapato blanco': '<i style="color:white" class="indicator fas fa-shoe-prints"></i>',
            };
            
            
            // Improved geolocation using direct browser API
            function getLocation() {
                if (navigator.geolocation) {
                    console.warn("Geolocalización soportada en este navegador.", navigator.geolocation);
                    navigator.geolocation.getCurrentPosition(
                        onLocationFound,
                        onLocationError,
                        {
                            enableHighAccuracy: true,
                            timeout: 10000,
                            maximumAge: 0
                        }
                    );
                } else {
                    alert("La geolocalización no está soportada en este navegador.");
                    map.setView([20.57, -100.38], 13);  // Default to Querétaro's coordinates
                }
            }

            // Geolocation function
            function onLocationFound(position) {
                console.warn("Geolocalización exitosa:", position);
                let lat = position.coords.latitude.toFixed(6);
                let lng = position.coords.longitude.toFixed(6);
                let fullCoords = position.coords;
                console.warn("Ubicación detectada:", fullCoords);
                console.warn("Latitud:", lat, "Longitud:", lng);
                let latlng = L.latLng(parseFloat(lat), parseFloat(lng));
                console.warn("Ubicación detectada:", latlng);
                let radius = position.coords.accuracy / 2;  // Accuracy of the location
                
                // Add a pin (marker) at the user's location
                user_marker.setLatLng(latlng).bindPopup("Te detectamos en un radio de " + parseInt(radius) + " metros de este punto").openPopup();
                
                // Add a circle around the user's location
                user_radial.remove(); // Remove existing radius
                user_radial = L.circle(latlng, radius).addTo(map);
                console.warn("latlng:", latlng, "radio:", radius);
                // Center the map on the user's location
                map.setView(latlng, 16);  // Adjust zoom level as needed
            }

            // Error handling for geolocation
            function onLocationError(error) {
                let errorMsg;
                switch(error.code) {
                    case error.PERMISSION_DENIED:
                        errorMsg = "Usuario denegó la solicitud de geolocalización.";
                        break;
                    case error.POSITION_UNAVAILABLE:
                        errorMsg = "La información de ubicación no está disponible.";
                        break;
                    case error.TIMEOUT:
                        errorMsg = "Se agotó el tiempo de espera para la solicitud de ubicación.";
                        break;
                    default:
                        errorMsg = "Ocurrió un error desconocido al obtener tu ubicación.";
                }
                console.error("Error de geolocalización:", errorMsg);
                alert(errorMsg);
                map.setView([20.57, -100.38], 13);  // Default to Querétaro's coordinates
            }

            // Start location detection
            map.on('click', function(e) {
                console.warn("Click detectado en el mapa:", e);
                let latlng = e.latlng;
                // Check if elements exist before accessing
                if (document.getElementById('lat') && document.getElementById('lng')) {
                    document.getElementById('lat').value = latlng.lat;
                    document.getElementById('lng').value = latlng.lng;
                }
                latlng.lat = parseFloat(latlng.lat).toFixed(6);
                latlng.lng = parseFloat(latlng.lng).toFixed(6);
                console.warn("Latitud:", latlng.lat, "Longitud:", latlng.lng);

                // Calculate the vertical offset (25% of the map's height)
                let offset = map.getSize().y * 0.25;
                // Convert the clicked location to container point
                let containerPoint = map.latLngToContainerPoint(latlng);
                // Adjust the container point upward by the offset
                let targetCenterPoint = L.point(containerPoint.x, containerPoint.y - offset);
                // Convert the adjusted point back to geographical coordinates
                let targetLatLng = map.containerPointToLatLng(targetCenterPoint);
                
                // Fly to the adjusted center so the marker appears 25% lower from the center
                map.flyTo(latlng, 18, { duration: 0.7 });
                map.once('moveend', function() {
                    user_marker.setLatLng(latlng).bindPopup('<button id="pinner-pop">Agregar bache-o-cosa</button>').openPopup();
                });
                user_radial.remove();
            });
        // });

        </script>
        
<script>
    console.log("Pins data:", {{ pins | tojson }});
    let markerCluster = L.markerClusterGroup();
    {% for pin in pins %}
    var icon = L.divIcon({
        className: '{{pin.typeofpin}}',
        html: iconTypes['{{pin.typeofpin}}'],
        iconSize: [10,10],
        iconAnchor: [5,5]
    });
    let p{{ pin._id }} = L.marker([{{ pin.lat }}, {{ pin.lng }}], { icon: icon })
        .bindPopup("<b>{{ pin.description }}</b><p>Fecha del reporte: {{pin.time}}</p><br><img src='{{ pin.photo }}'>");
    markerCluster.addLayer(p{{ pin._id }});
    {% endfor %}
    map.addLayer(markerCluster);
</script>
</script>
        {% if current_user.is_authenticated %}
        <div style="position: absolute; bottom: 1rem; left: 50%; transform: translateX(-50%); z-index: 999">
            <button class="control-button" onclick="window.location.href='/camera'"><i class="fas fa-camera"></i></button>
        </div>
        {% endif %}
{% endblock %}