const NOMINATIM_ENDPOINT = 'https://nominatim.openstreetmap.org/search';

/**
 * Resolve a typed address through the public fallback geocoder.
 *
 * Returns null when the address is empty, the request fails, or the response
 * does not contain a usable location.
 */
export const geocodeAddress = async ( term, country = '' ) => {
	const query = String( term || '' ).trim();
	if ( ! query ) return null;

	const countryCode = String( country || '' ).trim();
	const countryParam = countryCode
		? `&countrycodes=${ encodeURIComponent( countryCode ) }`
		: '';

	try {
		const response = await fetch(
			`${ NOMINATIM_ENDPOINT }?format=json&limit=1&q=${ encodeURIComponent( query ) }${ countryParam }`
		);
		const rows = await response.json();
		const lat = Number.parseFloat( rows?.[ 0 ]?.lat );
		const lng = Number.parseFloat( rows?.[ 0 ]?.lon );
		return Number.isFinite( lat ) && Number.isFinite( lng ) ? { lat, lng } : null;
	} catch ( error ) {
		return null;
	}
};
