let occurrenceMap = null;
let occurrenceMarker = null;
let occurrenceCategorySelect = null;

function createCategoryIcon(color) {
    const finalColor = color || '#1351b4';
    return L.divIcon({
        className: 'custom-category-marker',
        html: '<span style="background:' + finalColor + ';"></span>',
        iconSize: [26, 26],
        iconAnchor: [13, 26],
        popupAnchor: [0, -24]
    });
}

function getSelectedCategoryColor() {
    if (!occurrenceCategorySelect) return '#1351b4';
    const option = occurrenceCategorySelect.options[occurrenceCategorySelect.selectedIndex];
    if (!option) return '#1351b4';
    return option.getAttribute('data-color') || '#1351b4';
}

function initOccurrenceMap(containerId, latInputId, lngInputId, categorySelectId) {
    if (typeof L === 'undefined') return;

    const container = document.getElementById(containerId);
    if (!container) return;

    const latInput = document.getElementById(latInputId);
    const lngInput = document.getElementById(lngInputId);
    const initialLat = parseFloat(latInput && latInput.value ? latInput.value : '-20.5833');
    const initialLng = parseFloat(lngInput && lngInput.value ? lngInput.value : '-46.9219');
    occurrenceCategorySelect = categorySelectId ? document.getElementById(categorySelectId) : null;

    occurrenceMap = L.map(containerId).setView([initialLat, initialLng], 15);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: '&copy; OpenStreetMap contributors'
    }).addTo(occurrenceMap);

    occurrenceMarker = L.marker([initialLat, initialLng], { draggable: true, icon: createCategoryIcon(getSelectedCategoryColor()) }).addTo(occurrenceMap);

    if (occurrenceCategorySelect) {
        occurrenceCategorySelect.addEventListener('change', function () {
            if (occurrenceMarker) {
                occurrenceMarker.setIcon(createCategoryIcon(getSelectedCategoryColor()));
            }
        });
    }

    occurrenceMarker.on('dragend', function (e) {
        const pos = e.target.getLatLng();
        syncLatLng(pos.lat, pos.lng, latInput, lngInput);
    });

    occurrenceMap.on('click', function (e) {
        updateOccurrenceMarker(e.latlng.lat, e.latlng.lng);
    });

    syncLatLng(initialLat, initialLng, latInput, lngInput);
}

function syncLatLng(lat, lng, latInput, lngInput) {
    if (latInput) latInput.value = Number(lat).toFixed(8);
    if (lngInput) lngInput.value = Number(lng).toFixed(8);
    if (occurrenceMap && occurrenceMarker) {
        occurrenceMarker.setLatLng([lat, lng]);
    }
}

function updateOccurrenceMarker(lat, lng) {
    if (!occurrenceMap || !occurrenceMarker) return;

    occurrenceMarker.setLatLng([lat, lng]);
    occurrenceMap.setView([lat, lng], 17);
    const latInput = document.getElementById('latitude');
    const lngInput = document.getElementById('longitude');
    syncLatLng(lat, lng, latInput, lngInput);
}

function renderReadonlyMap(containerId, lat, lng, color) {
    if (typeof L === 'undefined') return;
    const container = document.getElementById(containerId);
    if (!container) return;

    const map = L.map(containerId).setView([lat, lng], 16);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: '&copy; OpenStreetMap contributors'
    }).addTo(map);

    L.marker([lat, lng], { icon: createCategoryIcon(color) }).addTo(map);
}

function renderMultiMarkerMap(containerId, items) {
    if (typeof L === 'undefined') return;
    const container = document.getElementById(containerId);
    if (!container) return;

    const defaultCenter = [-20.5833, -46.9219];
    const map = L.map(containerId).setView(defaultCenter, 13);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: '&copy; OpenStreetMap contributors'
    }).addTo(map);

    const bounds = [];
    (items || []).forEach(function (item) {
        const lat = parseFloat(item.latitude);
        const lng = parseFloat(item.longitude);
        if (Number.isNaN(lat) || Number.isNaN(lng)) return;

        bounds.push([lat, lng]);
        const html = `
            <div style="min-width:180px">
                <strong>${item.protocolo}</strong><br>
                <span>${item.categoria_nome || ''}</span><br>
                <small>${item.status || ''}</small><br>
                ${item.endereco_referencia ? `<small>${item.endereco_referencia}</small>` : ''}
            </div>`;
        L.marker([lat, lng], { icon: createCategoryIcon(item.categoria_cor || '#1351b4') }).addTo(map).bindPopup(html);
    });

    if (bounds.length === 1) {
        map.setView(bounds[0], 16);
    } else if (bounds.length > 1) {
        map.fitBounds(bounds, { padding: [30, 30] });
    }
}

function reverseGeocodeOccurrence(lat, lng, targetInputId) {
    const target = document.getElementById(targetInputId);
    if (!target) return;

    target.value = 'Buscando endereço...';
    const url = `https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${encodeURIComponent(lat)}&lon=${encodeURIComponent(lng)}`;

    fetch(url, {
        headers: {
            'Accept': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        target.value = data.display_name || `${lat.toFixed(6)}, ${lng.toFixed(6)}`;
    })
    .catch(() => {
        target.value = `${lat.toFixed(6)}, ${lng.toFixed(6)}`;
    });
}
