
// Helper starts here.

/**
 * Retrieves a popup configuration object by its unique identifier.
 *
 * @param {string} id - The unique identifier of the popup.
 * @returns {Object|null} - Returns the popup configuration object if found, otherwise returns null.
 */
function getWingPopup(id) {
	return wdpop__cred.popups.find((d) => d.id == id) || null;
}
/**
 * Converts a given time value to seconds based on the unit provided.
 *
 * @param {number} showAgain - The numeric value representing the amount of time.
 * @param {string} showAgainUnit - The unit of time (Minute(s), Hour(s), Day(s), Week(s), Month(s)).
 * @returns {number} The total time in seconds.
 * @throws {Error} If the provided unit is invalid.
 */
function wingConvertToSeconds(showAgain, showAgainUnit) {
	// Mapping of time units to their equivalent in seconds
	const unitsInSeconds = {
		"Minute": 60,
		"Hour": 3600,
		"Day": 86400,
		"Week": 604800,
		"Month": 2592000 // Approximation assuming 30 days in a month
	};

	// Check if the unit exists in the unitsInSeconds object
	if (!unitsInSeconds[showAgainUnit]) {
		throw new Error("Invalid unit");
	}

	// Calculate the total time in seconds
	let totalTimeInSeconds = showAgain * unitsInSeconds[showAgainUnit];
	
	return totalTimeInSeconds;
}
/**
 * Checks whether the popup should be shown based on the last display time stored in local storage.
 *
 * @param {number} showAgainInSeconds - The time interval in seconds after which the popup should be shown again.
 * @param {string} id - The unique identifier of the popup.
 * @returns {boolean} - Returns true if the popup should be shown, false otherwise.
 */
function wingShouldShowPopup(showAgainInSeconds, id) {
	// Retrieve the last popup display time from local storage
	const wingLastPopupTime = localStorage.getItem(`wingLastPopupTime_${id}`);
	
	// If there's no record of the last popup display time, it means the popup should be shown
	if (!wingLastPopupTime) {
		return true;
	}
	
	// Calculate the elapsed time in seconds since the last popup was shown
	const elapsedTime = (Date.now() - wingLastPopupTime) / 1000;
	
	// Check if the elapsed time is greater than or equal to the specified interval
	return elapsedTime >= showAgainInSeconds;
}
function WingIsEmail(email) {
  // A regular expression for validating email addresses
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  
  // Use the test() method of the regex to check if the email matches the pattern
  return emailRegex.test(email);
}
// Helper ends here.


document.addEventListener("DOMContentLoaded", function() {
	
	// wing-modal--item is the class name for all the modals
	const WingModals = document.querySelectorAll('.wing-modal--item');
	// Return if modal is not found
	if(WingModals.length == 0) return;

	WingModals.forEach(popup => {
		const myModal = new bootstrap.Modal(popup)
		const thisId = popup.getAttribute('wing-popup-id');
		const { page_load_events, on_click_events } = getWingPopup(thisId);
		
		popup.addEventListener('show.bs.modal', () => {
			popup.classList.remove('hide');
		});
		popup.addEventListener('hide.bs.modal', () => {
			popup.classList.add('hide');
		});
		
		
		// Handle Page load events
		const {page_load_status, popup_delay, popup_show_again} = page_load_events;
		if (page_load_status === '1') {
			const delayTime = popup_delay * 1000; // Convert seconds to milliseconds
			const { width: showAgain, unit: showAgainUnit } = popup_show_again;
			const cleanUnit = showAgainUnit.replace("(s)", ""); // Clean up the unit string
			const realTime = wingConvertToSeconds(showAgain, cleanUnit);

			// Show Modal
			if (wingShouldShowPopup(realTime, thisId)) {
				setTimeout(() => {
					myModal.show();
					localStorage.setItem(`wingLastPopupTime_${thisId}`, Date.now());
				}, delayTime);
			}
		}
		
		// Handle on click events
		const { on_click_status, popup_css_selectors, prevent_default } = on_click_events;
		if (on_click_status === '1' && popup_css_selectors != '') {
			const selectors = popup_css_selectors.split(',');
			selectors.forEach(selector => {
				document.querySelector(selector)?.addEventListener('click', (e) => {
					if (prevent_default === '1') {
						e.preventDefault();
					}
					myModal.show();
				});
			});
		}
		
	});

});


// Popup Script
const mcSubmitButton = document.querySelector('.wing-popup-mc-form-submit');

mcSubmitButton?.addEventListener('click', (e) => {
	e.preventDefault();
	let form = mcSubmitButton.closest('form.wing-popup-mc-form');
	let message = form.querySelector('.wing-popup-mc-message');
	const invalidmail = form.dataset.invalidMail;
	const redirect_url = form.dataset.redirect_url;
	const hide_form = form.dataset.hide_form;
	const hideDelay = 500;
	const redirectDelay = 1000;
	let email = form.querySelector('.wing-popup-mc-form-email');
	if(email.value == '' || !WingIsEmail(email.value)) {
		message.textContent = invalidmail;
		message.style.color = 'red';
		return;
	}else{
		message.textContent = '';
	}
	
	let data = new FormData(form);
	data.append('action', 'wing_popup_mc_subscribe');
	data.append('form_id', form.dataset.formId);
	data.append('nonce', wdpop__cred.nonce);
	
	message.textContent = 'Working on the request...';
	
	fetch(wdpop__cred.ajax_url, {
		method: 'POST',
		credentials: 'same-origin',
		body: data
	})
	.then(res => res.json())
	.then(json => {
	
	if (json.success) {
		message.textContent = json.data.message;
		message.style.color = 'green';
		form.reset();
		
		setTimeout(function () {
			if(hide_form){
				// form.remove();
				form.innerHTML = json.data.message;
				form.style.color = 'green';
			}
		}, hideDelay);
		
		setTimeout(function () {
			if(redirect_url){
				window.location.href = redirect_url;
			}
		}, redirectDelay);
		
	} else {
		message.textContent = json.data.message;
		message.style.color = 'red';
	}
	});
	
	
});



document.querySelectorAll('.wing-popup-mc-form-submit').forEach((mcSubmitButton) => {
	mcSubmitButton.addEventListener('click', (e) => {
		e.preventDefault();

		let form = mcSubmitButton.closest('form.wing-popup-mc-form');
		if (!form) return;

		let message = form.querySelector('.wing-popup-mc-message');
		let email = form.querySelector('.wing-popup-mc-form-email');

		const invalidmail = form.dataset.invalidMail;
		const redirect_url = form.dataset.redirect_url;
		const hide_form = form.dataset.hide_form;
		const hideDelay = 500;
		const redirectDelay = 1000;

		if (email.value === '' || !WingIsEmail(email.value)) {
			message.textContent = invalidmail;
			message.style.color = 'red';
			return;
		} else {
			message.textContent = '';
		}

		let data = new FormData(form);
		data.append('action', 'wing_popup_mc_subscribe');
		data.append('form_id', form.dataset.formId);
		data.append('nonce', wdpop__cred.nonce);

		message.textContent = 'Working on the request...';
		message.style.color = '';

		fetch(wdpop__cred.ajax_url, {
			method: 'POST',
			credentials: 'same-origin',
			body: data
		})
		.then(res => res.json())
		.then(json => {
			if (json.success) {
				message.textContent = json.data.message;
				message.style.color = 'green';
				form.reset();

				setTimeout(() => {
					if (hide_form) {
						form.innerHTML = json.data.message;
						form.style.color = 'green';
					}
				}, hideDelay);

				setTimeout(() => {
					if (redirect_url) {
						window.location.href = redirect_url;
					}
				}, redirectDelay);
			} else {
				message.textContent = json.data.message;
				message.style.color = 'red';
			}
		})
		.catch(() => {
			message.textContent = 'Something went wrong. Please try again.';
			message.style.color = 'red';
		});
	});
});



