// source --> https://cerincomune.it/wp-content/plugins/ricerca-cer-join4green/public/js/public.js?ver=1.0.0 
/**
 * Public JavaScript for Ricerca CER Join4green plugin.
 *
 * @package    RicercaCERJoin4green
 * @subpackage RicercaCERJoin4green\public\js
 */

(function( $ ) {
	'use strict';

	$( document ).ready( function() {
		// Initialize Google Places Autocomplete if API is loaded.
		if ( typeof google !== 'undefined' && google.maps && google.maps.places ) {
			initGooglePlacesAutocomplete();
		} else {
			// Wait for Google Maps API to load if not yet available.
			$( window ).on( 'load', function() {
				if ( typeof google !== 'undefined' && google.maps && google.maps.places ) {
					initGooglePlacesAutocomplete();
				}
			});
		}
	});

	/**
	 * Initialize Google Places Autocomplete on the address input field.
	 */
	function initGooglePlacesAutocomplete() {
		var addressInput = document.getElementById( 'ricerca-cer-address-input' );

		if ( ! addressInput ) {
			return;
		}

		// Create Autocomplete instance.
		var autocomplete = new google.maps.places.Autocomplete( addressInput, {
			types: [ 'address' ],
		});

		// Listen for place selection.
		autocomplete.addListener( 'place_changed', function() {
			var place = autocomplete.getPlace();

			if ( ! place.geometry || ! place.geometry.location ) {
				console.warn( 'Nessun dettaglio di posizione disponibile per il luogo selezionato.' );
				return;
			}

			// Extract latitude and longitude.
			var latitude  = place.geometry.location.lat();
			var longitude = place.geometry.location.lng();

			// Fetch CER data.
			fetchCERData( latitude, longitude );
		});
	}

	/**
	 * Fetch CER data from the API.
	 *
	 * @param {number} latitude  The latitude value.
	 * @param {number} longitude The longitude value.
	 */
	function fetchCERData( latitude, longitude ) {
		var dataContainer = $( '#ricerca-cer-data' );
		var loadingDiv    = $( '.ricerca-cer-loading' );
		var errorDiv      = $( '.ricerca-cer-error' );
		var resultsDiv    = $( '.ricerca-cer-results' );

		if ( ! dataContainer.length ) {
			return;
		}

		// Check if AJAX data is available.
		if ( typeof ricercaCerAjax === 'undefined' ) {
			displayError( 'Configurazione AJAX non disponibile.' );
			return;
		}

		// Show container and loading state.
		dataContainer.show();
		loadingDiv.show();
		errorDiv.hide();
		resultsDiv.empty();

		// Make AJAX request.
		$.ajax({
			url: ricercaCerAjax.ajaxUrl,
			type: 'POST',
			data: {
				action: ricercaCerAjax.action,
				nonce: ricercaCerAjax.nonce,
				latitude: latitude,
				longitude: longitude
			},
			success: function( response ) {
				loadingDiv.hide();

				if ( response.success && response.data && response.data.cer ) {
					displayCERData( response.data.cer );
				} else {
					var errorMessage = response.data && response.data.message
						? response.data.message
						: 'Nessun dato CER disponibile per questa posizione.';
					displayError( errorMessage );
				}
			},
			error: function( xhr, status, error ) {
				loadingDiv.hide();
				displayError( 'Errore durante il caricamento dei dati. Riprova più tardi.' );
				console.error( 'AJAX Error:', status, error );
			}
		});
	}

	/**
	 * Check if a string is a valid email address.
	 *
	 * @param {string} email The string to validate.
	 * @return {boolean} True if valid email, false otherwise.
	 */
	function isValidEmail( email ) {
		var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
		return emailRegex.test( email );
	}

	/**
	 * Escape HTML to prevent XSS attacks.
	 *
	 * @param {string} text The text to escape.
	 * @return {string} Escaped HTML string.
	 */
	function escapeHtml( text ) {
		var map = {
			'&': '&amp;',
			'<': '&lt;',
			'>': '&gt;',
			'"': '&quot;',
			"'": '&#039;'
		};
		return text.replace( /[&<>"']/g, function( m ) { return map[ m ]; } );
	}

	/**
	 * Display CER data.
	 *
	 * @param {Array} cerArray Array of CER objects.
	 */
	function displayCERData( cerArray ) {
		var resultsDiv = $( '.ricerca-cer-results' );
		var errorDiv   = $( '.ricerca-cer-error' );

		if ( ! resultsDiv.length ) {
			return;
		}

		errorDiv.hide();
		resultsDiv.empty();

		if ( ! cerArray || cerArray.length === 0 ) {
			displayError( 'Nessuna CER trovata per questa posizione.' );
			return;
		}

		// Iterate through CER array and display each one.
		$.each( cerArray, function( index, cer ) {
			var cerItem = $( '<div class="ricerca-cer-item"></div>' );

			// Add alias.
			if ( cer.alias ) {
				var aliasDiv = $( '<h3 class="ricerca-cer-alias"></h3>' ).text( cer.alias );
				cerItem.append( aliasDiv );
			}

			// Add description.
			if ( cer.descrizione ) {
				// Replace &nbsp; with standard spaces.
				var cleanDescription = cer.descrizione.replace( /&nbsp;/g, ' ' );
				var descDiv = $( '<div class="ricerca-cer-description"></div>' ).html( cleanDescription );
				cerItem.append( descDiv );
			}

			// Add contacts.
			if ( cer.contatti && cer.contatti.length > 0 ) {
				var contactsDiv = $( '<div class="ricerca-cer-contacts"></div>' );
				var contactsList = $( '<ul></ul>' );

				$.each( cer.contatti, function( contactIndex, contatto ) {
					if ( contatto.contatto && contatto.contatto.tipo_contatto && contatto.contatto.value ) {
						var label = contatto.contatto.tipo_contatto.label || 'Contatto';
						var value = contatto.contatto.value.trim();
						var isEmail = label.toLowerCase() === 'email' || isValidEmail( value );
						
						var listItem = $( '<li></li>' );
						var labelSpan = $( '<strong></strong>' ).text( label + ':' );
						listItem.append( labelSpan ).append( ' ' );
						
						if ( isEmail ) {
							// Create clickable mailto link.
							var emailLink = $( '<a></a>' )
								.attr( 'href', 'mailto:' + value )
								.text( value );
							listItem.append( emailLink );
						} else {
							// Display as plain text.
							listItem.append( document.createTextNode( value ) );
						}
						
						contactsList.append( listItem );
					}
				});

				if ( contactsList.children().length > 0 ) {
					contactsDiv.append( contactsList );
					cerItem.append( contactsDiv );
				}
			}

			// Add action buttons (Dettagli, Aderisci).
			var dettagliHrefRaw = cer.sito && cer.sito[0] && cer.sito[0].contatto && typeof cer.sito[0].contatto.value === 'string' ? cer.sito[0].contatto.value.trim() : '';
			var isSafeUrl = dettagliHrefRaw.indexOf( 'http://' ) === 0 || dettagliHrefRaw.indexOf( 'https://' ) === 0;
			var hasDettagli = dettagliHrefRaw !== '' && isSafeUrl;
			var configReferral = typeof ricercaCerAjax !== 'undefined' && ricercaCerAjax.referral ? String( ricercaCerAjax.referral ).trim() : '';
			var cerReferral = cer.referral && typeof cer.referral === 'string' ? cer.referral.trim() : '';
			var hasAderisci = configReferral !== '' && cerReferral !== '';

			if ( hasDettagli || hasAderisci ) {
				var actionsDiv = $( '<div class="ricerca-cer-actions"></div>' );

				if ( hasDettagli ) {
					var dettagliTitle = ( typeof ricercaCerAjax !== 'undefined' && ricercaCerAjax.buttonTitleDettagli ) ? ricercaCerAjax.buttonTitleDettagli : 'Dettagli';
					var dettagliLink = $( '<a></a>' )
						.attr( 'href', dettagliHrefRaw )
						.attr( 'target', '_blank' )
						.attr( 'rel', 'noopener noreferrer' )
						.addClass( 'ricerca-cer-action-link ricerca-cer-action-link-dettagli' )
						.text( dettagliTitle );
					actionsDiv.append( dettagliLink );
				}

				if ( hasAderisci ) {
					var baseHost = ( typeof ricercaCerAjax !== 'undefined' && ricercaCerAjax.endpointType === 'production' )
						? configReferral + '.join4green.com'
						: configReferral + '.dev.join4green.com';
					var aderisciUrl = 'https://' + baseHost + '/private?r=' + encodeURIComponent( cerReferral );
					var aderisciTitle = ( typeof ricercaCerAjax !== 'undefined' && ricercaCerAjax.buttonTitleAderisci ) ? ricercaCerAjax.buttonTitleAderisci : 'Aderisci';
					var aderisciLink = $( '<a></a>' )
						.attr( 'href', aderisciUrl )
						.attr( 'target', '_blank' )
						.attr( 'rel', 'noopener noreferrer' )
						.addClass( 'ricerca-cer-action-link ricerca-cer-action-link-aderisci' )
						.text( aderisciTitle );
					actionsDiv.append( aderisciLink );
				}

				cerItem.append( actionsDiv );
			}

			resultsDiv.append( cerItem );
		});
	}

	/**
	 * Display error message.
	 *
	 * @param {string} message The error message to display.
	 */
	function displayError( message ) {
		var errorDiv        = $( '.ricerca-cer-error' );
		var errorMessageDiv = $( '.ricerca-cer-error-message' );
		var resultsDiv      = $( '.ricerca-cer-results' );

		if ( errorDiv.length && errorMessageDiv.length ) {
			errorMessageDiv.text( message );
			errorDiv.show();
			resultsDiv.empty();
		}
	}

})( jQuery );