<template>
    <div class="relative w-full h-full rounded-2xl overflow-hidden shadow-md">
        <div class="absolute inset-0 transition-all duration-300 h-full">
            <div id="map" ref="mapContainer" class="w-full h-full"></div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onBeforeUnmount, defineExpose } from 'vue';
import L from 'leaflet';

// Sobrescribir el ícono predeterminado de Leaflet
delete L.Icon.Default.prototype._getIconUrl;

L.Icon.Default.mergeOptions({
    iconRetinaUrl: 'https://unpkg.com/leaflet@1.7.1/dist/images/marker-icon-2x.png',
    iconUrl: 'https://unpkg.com/leaflet@1.7.1/dist/images/marker-icon.png',
    shadowUrl: 'https://unpkg.com/leaflet@1.7.1/dist/images/marker-shadow.png',
});

const props = defineProps({
    origen: { type: Object, required: true },
    destino: { type: Object, required: true },
    apiKey: { type: String, required: true },
    baseUrl: { type: String, required: true }
});

const mapContainer = ref(null);
const map = ref(null);
const markerOrigen = ref(null);
const markerDestino = ref(null);
const routeLine = ref(null);

const drawRoute = () => {
    if (!props.origen || !props.destino) return;

    const origin = [props.origen.lat, props.origen.lon];
    const destination = [props.destino.lat, props.destino.lon];

    // Si ya hay una ruta dibujada, la eliminamos
    if (routeLine.value) {
        map.value.removeLayer(routeLine.value);
    }

    const url = `${props.baseUrl}/v2/directions/driving-car?api_key=${props.apiKey}&start=${origin[1]},${origin[0]}&end=${destination[1]},${destination[0]}`;

    fetch(url)
        .then(response => response.json())
        .then(data => {
            const coordinates = data.features[0].geometry.coordinates;
            routeLine.value = L.polyline(coordinates.map(coord => [coord[1], coord[0]]), {
                color: 'blue',
                weight: 4,
                opacity: 0.7
            }).addTo(map.value);
            map.value.fitBounds(routeLine.value.getBounds());
        })
        .catch(error => {
            console.error("Error al calcular la ruta:", error);
        });
};

// Función expuesta para que el padre la llame
const calcularRuta = () => {
    drawRoute();
};

onMounted(() => {
    nextTick(() => {
        const mapContainerEl = mapContainer.value;

        if (mapContainerEl && mapContainerEl.offsetHeight > 0) {
            const startLatLng = [4.81309565, -75.69949999];

            const bounds = [
                [4.65, -75.90], // Suroeste (La Virginia)
                [4.95, -75.50]  // Noreste (Santa Rosa de Cabal y Dosquebradas)
            ];

            map.value = L.map(mapContainerEl, {
                center: startLatLng,
                zoom: 13,
                minZoom: 12,
                maxBounds: bounds,
                maxBoundsViscosity: 1.0
            });

            L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
                maxZoom: 19,
                attribution: '© OpenStreetMap'
            }).addTo(map.value);

            // Agregamos los marcadores sin dibujar la ruta
            markerOrigen.value = L.marker([props.origen.lat, props.origen.lon]).addTo(map.value);
            markerDestino.value = L.marker([props.destino.lat, props.destino.lon]).addTo(map.value);

            map.value.invalidateSize();
        } else {
            console.error("El contenedor del mapa no está disponible o tiene altura cero");
        }
    });
});

// Exponemos la función para que el padre pueda llamarla
defineExpose({
    calcularRuta
});

onBeforeUnmount(() => {
    if (map.value) {
        map.value.remove();
    }
});
</script>

<style scoped>
#map {
    height: 100%;
    width: 100%;
    z-index: 1;
}
</style>
