// leaflet_bridge.js
function initMap(config) {
    const { imgUrl, width, height, meta, grid_size, dots } = config;

    // Setup Coordinate XY (0,0 in alto a sinistra)
    const map = L.map('map', {
        crs: L.CRS.Simple,
        minZoom: -2,
        maxZoom: 4,
        attributionControl: false
    });

    const bounds = [[-height, 0], [0, width]];
    L.imageOverlay(imgUrl, bounds).addTo(map);
    map.fitBounds(bounds);

    // Gestione Griglia
    let gridLayer = L.layerGroup();
    if (meta.show_grid) {
        const step = meta.grid_size || 100;
        const S = meta.pixel_ratio || 1;
        for (let x = 0; x <= width; x += (step * S)) {
            L.polyline([[0, x], [-height, x]], {color: '#ccc', weight: 1, opacity: 0.5}).addTo(gridLayer);
        }
        for (let y = 0; y >= -height; y -= (step * S)) {
            L.polyline([[y, 0], [y, width]], {color: '#ccc', weight: 1, opacity: 0.5}).addTo(gridLayer);
        }
        gridLayer.addTo(map);
    }

    // Visualizzazione punti esistenti (Verdi e Blu)
    dots.forEach(dot => {
        const color = dot.status === 'completed' ? '#228B22' : '#0000FF';
        L.circleMarker([dot.y, dot.x], {
            radius: config.dot_size / 5,
            fillColor: color,
            color: 'white',
            weight: 2,
            fillOpacity: 0.8
        }).addTo(map).bindPopup(`X: ${dot.relX}, Y: ${dot.relY}`);
    });

    // Evento Click per rilievo
    map.on('click', function(e) {
        const raw_x = e.latlng.lng;
        const raw_y = e.latlng.lat; // In Leaflet Simple, Y è negativa sotto l'origine

        // Invio dati a Streamlit
        window.parent.postMessage({
            type: 'streamlit:setComponentValue',
            value: {
                x: raw_x,
                y: raw_y,
                timestamp: new Date().getTime()
            }
        }, '*');
    });
}
