/* Wohno map layout — Leaflet + OpenStreetMap. Popups built with textContent
 * (no innerHTML) so listing fields can never inject markup. */
( function () {
	'use strict';

	function popup( p ) {
		var box = document.createElement( 'div' );
		box.className = 'wohno-map-popup';

		var a = document.createElement( 'a' );
		a.href = p.url || '#';
		a.target = '_blank';
		a.rel = 'noopener';
		a.textContent = p.title || '';
		var title = document.createElement( 'strong' );
		title.appendChild( a );
		box.appendChild( title );

		if ( p.place ) {
			var place = document.createElement( 'div' );
			place.textContent = p.place;
			box.appendChild( place );
		}
		if ( p.price ) {
			var price = document.createElement( 'div' );
			price.textContent = p.price;
			box.appendChild( price );
		}
		return box;
	}

	function init( el ) {
		if ( ! window.L ) {
			return;
		}
		var points;
		try {
			points = JSON.parse( el.getAttribute( 'data-wohno-map' ) || '[]' );
		} catch ( e ) {
			return;
		}
		if ( ! points.length ) {
			return;
		}

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

		var coords = [];
		points.forEach( function ( p ) {
			if ( 'number' !== typeof p.lat || 'number' !== typeof p.lng ) {
				return;
			}
			window.L.marker( [ p.lat, p.lng ] ).addTo( map ).bindPopup( popup( p ) );
			coords.push( [ p.lat, p.lng ] );
		} );

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

	function boot() {
		var nodes = document.querySelectorAll( '.wohno-map[data-wohno-map]' );
		Array.prototype.forEach.call( nodes, init );
	}

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