/**
 * Auto Dealer — Map provider boot script.
 *
 * Scans the page for `.trx-ad-map[data-trx-ad-map]` placeholders, parses the
 * config, and initialises Leaflet or Google Maps depending on `provider`.
 * Vanilla JS only — no jQuery, no framework.
 *
 * @package ThemeREX\AutoDealer
 */
(function () {
	'use strict';

	function initLeaflet(el, config) {
		if (typeof window.L === 'undefined') {
			return;
		}
		var center = [config.center.lat, config.center.lng];
		var map = window.L.map(el).setView(center, config.zoom);

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

		var markers = [];
		(config.pins || []).forEach(function (pin) {
			var m = window.L.marker([pin.lat, pin.lng], { title: pin.title || '' });
			var popup = '';
			if (pin.title) popup += '<strong>' + pin.title + '</strong><br>';
			if (pin.content) popup += pin.content;
			if (pin.url) popup += '<br><a href="' + pin.url + '">' + (window.trxAdMapsI18n ? window.trxAdMapsI18n.viewDetails : 'View details') + '</a>';
			if (popup) m.bindPopup(popup);
			markers.push(m);
		});

		if (config.cluster && typeof window.L.markerClusterGroup === 'function') {
			var group = window.L.markerClusterGroup();
			markers.forEach(function (m) { group.addLayer(m); });
			map.addLayer(group);
		} else {
			markers.forEach(function (m) { m.addTo(map); });
		}

		if (markers.length > 1) {
			var bounds = window.L.latLngBounds(markers.map(function (m) { return m.getLatLng(); }));
			map.fitBounds(bounds.pad(0.2));
		}
	}

	function initGoogle(el, config) {
		if (typeof window.google === 'undefined' || !window.google.maps) {
			return;
		}
		var map = new window.google.maps.Map(el, {
			center: config.center,
			zoom: config.zoom,
			mapTypeControl: false
		});

		var infoWindow = new window.google.maps.InfoWindow();
		var markers = (config.pins || []).map(function (pin) {
			var marker = new window.google.maps.Marker({
				position: { lat: pin.lat, lng: pin.lng },
				title: pin.title || '',
				map: (config.cluster && window.markerClusterer) ? null : map
			});
			marker.addListener('click', function () {
				var html = '';
				if (pin.title) html += '<strong>' + pin.title + '</strong><br>';
				if (pin.content) html += pin.content;
				if (pin.url) html += '<br><a href="' + pin.url + '">' + (window.trxAdMapsI18n ? window.trxAdMapsI18n.viewDetails : 'View details') + '</a>';
				infoWindow.setContent(html);
				infoWindow.open(map, marker);
			});
			return marker;
		});

		if (config.cluster && window.markerClusterer && window.markerClusterer.MarkerClusterer) {
			new window.markerClusterer.MarkerClusterer({ map: map, markers: markers });
		}

		if (markers.length > 1) {
			var bounds = new window.google.maps.LatLngBounds();
			markers.forEach(function (m) { bounds.extend(m.getPosition()); });
			map.fitBounds(bounds);
		}
	}

	function bootElement(el) {
		if (el.dataset.trxAdMapBooted === '1') {
			return;
		}
		var raw = el.getAttribute('data-trx-ad-map');
		if (!raw) {
			return;
		}
		var config;
		try {
			config = JSON.parse(raw);
		} catch (_) {
			return;
		}
		el.dataset.trxAdMapBooted = '1';

		if (config.provider === 'leaflet') {
			initLeaflet(el, config);
		} else if (config.provider === 'google') {
			// Google's API loads async. Poll briefly until window.google is
			// available, then init.
			var tries = 0;
			(function wait() {
				if (typeof window.google !== 'undefined' && window.google.maps) {
					initGoogle(el, config);
					return;
				}
				tries++;
				if (tries < 100) { // ~10 seconds
					setTimeout(wait, 100);
				}
			})();
		}
	}

	function bootAll() {
		var nodes = document.querySelectorAll('.trx-ad-map[data-trx-ad-map]');
		Array.prototype.forEach.call(nodes, bootElement);
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', bootAll);
	} else {
		bootAll();
	}
})();
