
/**
 * SET LOCATION: Admin Map Picker
 * jQuery + Leaflet + OpenStreetMap
 */
(function($) {
	'use strict';

	$(document).ready(function() {
		const $mapContainer = $('#set-location-map');
		if (!$mapContainer.length) return;

		// Elementos do formulário
		const $latHidden   = $('#sl_lat');
		const $lngHidden   = $('#sl_lng');
		const $zoomHidden  = $('#sl_zoom');
		const $latDisplay  = $('#sl_lat_display');
		const $lngDisplay  = $('#sl_lng_display');
		const $zoomInput   = $('#sl_zoom_input');

		// Valores iniciais (do post ou padrão global)
		const initLat = parseFloat($latHidden.val()) || parseFloat(setLocationData.default_lat);
		const initLng = parseFloat($lngHidden.val()) || parseFloat(setLocationData.default_lng);
		const initZoom = parseInt($zoomHidden.val()) || parseInt(setLocationData.default_zoom) || 8;

		// Corrige ícones do Leaflet para uso local/offline
        delete L.Icon.Default.prototype._getIconUrl;
        L.Icon.Default.mergeOptions({
            iconRetinaUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png',
            iconUrl:       'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png',
            shadowUrl:     'https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png',
        });

		// Inicializa o mapa
		const map = L.map('set-location-map', {
			zoomControl: true,
			scrollWheelZoom: true
		}).setView([initLat, initLng], initZoom);

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

		let marker = null;
		if (initLat && initLng) {
			marker = L.marker([initLat, initLng]).addTo(map);
		}

		// Sincroniza inputs ao clicar/mover marcador
		function syncFields(lat, lng, zoom) {
			const latFixed = lat.toFixed(6);
			const lngFixed = lng.toFixed(6);
			const zoomInt = parseInt(zoom);

			$latHidden.val(latFixed);
			$lngHidden.val(lngFixed);
			$zoomHidden.val(zoomInt);
			$latDisplay.val(latFixed);
			$lngDisplay.val(lngFixed);
			$zoomInput.val(zoomInt);
		}

		// Clique no mapa define nova posição
		map.on('click', function(e) {
			const { lat, lng } = e.latlng;
			if (marker) map.removeLayer(marker);
			marker = L.marker([lat, lng]).addTo(map);
			syncFields(lat, lng, map.getZoom());
		});

		// Arrastar marcador atualiza posição
		if (marker) {
			marker.on('dragend', function(e) {
				const { lat, lng } = e.target.getLatLng();
				syncFields(lat, lng, map.getZoom());
			});
		}

		// Zoom do mapa (roda do mouse ou controles) atualiza campo
		map.on('zoomend', function() {
			const zoom = map.getZoom();
			$zoomHidden.val(zoom);
			$zoomInput.val(zoom);
		});

		// Input de zoom na sidebar ajusta o mapa
		$zoomInput.on('change input', function() {
			const zoom = parseInt($(this).val());
			if (zoom >= 1 && zoom <= 18) {
				map.setZoom(zoom);
				$zoomHidden.val(zoom);
			}
		});

		// Se os campos de lat/lng forem editados manualmente (raro), centraliza o mapa
		$latDisplay.add($lngDisplay).on('change', function() {
			const lat = parseFloat($latDisplay.val());
			const lng = parseFloat($lngDisplay.val());
			if (lat && lng) {
				map.setView([lat, lng], map.getZoom());
				if (marker) marker.setLatLng([lat, lng]);
				syncFields(lat, lng, map.getZoom());
			}
		});
	});
})(jQuery);