window.phMap = {
    initMap: function (mapId, lat, lng, zoom) {
        const map = L.map(mapId).setView([lat, lng], zoom);

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; OpenStreetMap contributors'
        }).addTo(map);

        const marker = L.marker([lat, lng]).addTo(map)
            .bindPopup('Ubicación inicial')
            .openPopup();

        // Guardamos el mapa y el marcador
        window._phMaps = window._phMaps || {};
        window._phMaps[mapId] = { map, marker };

        map.on('click', function (e) {
            const newLat = e.latlng.lat;
            const newLng = e.latlng.lng;

            // Mover el marcador existente
            window._phMaps[mapId].marker.setLatLng([newLat, newLng]);
            window._phMaps[mapId].marker.getPopup().setContent('Nueva ubicación').openOn(map);

            // Llamar al método en Blazor
            DotNet.invokeMethodAsync('phronCare.UIBlazor', 'NotifyLocationChanged', newLat, newLng);
        });

    },
    searchAddress: async function (mapId, address) {
        const response = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(address)}`);
        const data = await response.json();

        if (data.length === 0) {
            alert("Dirección no encontrada.");
            return;
        }

        const lat = parseFloat(data[0].lat);
        const lon = parseFloat(data[0].lon);

        const mapData = window._phMaps[mapId];
        if (!mapData) return;

        mapData.map.setView([lat, lon], 15);
        mapData.marker.setLatLng([lat, lon]);
        mapData.marker.getPopup().setContent(address.toUpperCase()).openOn(mapData.map);

        DotNet.invokeMethodAsync('phronCare.UIBlazor', 'NotifyLocationChanged', lat, lon);
    }
};
