(function ($) {
	'use strict';
	$(function(){

		function getModelsErrorMessage(requestData, xhr, textStatus, errorThrown) {
			var responseText = xhr && typeof xhr.responseText === 'string' ? xhr.responseText.trim() : '';
			var responseJson = xhr && xhr.responseJSON ? xhr.responseJSON : null;
			var responseData = requestData && requestData.data ? requestData.data : null;
			var errorCode = responseData && responseData.code ? responseData.code : (responseJson && responseJson.data && responseJson.data.code ? responseJson.data.code : '');
			var defaultMessage = EUROSTOCKS_TRANSLATIONS && EUROSTOCKS_TRANSLATIONS.ERROR_GENERIC
				? EUROSTOCKS_TRANSLATIONS.ERROR_GENERIC
				: 'Failed to load models';

			if (responseData && responseData.message) {
				return responseData.message;
			}

			if (responseJson && responseJson.data && responseJson.data.message) {
				return responseJson.data.message;
			}

			if (responseText === '-1' || errorCode === 'invalid_nonce') {
				return EUROSTOCKS_TRANSLATIONS && EUROSTOCKS_TRANSLATIONS.ERROR_EXPIRED
					? EUROSTOCKS_TRANSLATIONS.ERROR_EXPIRED
					: defaultMessage;
			}

			if (errorThrown && errorThrown !== 'error') {
				return errorThrown;
			}

			if (textStatus && textStatus !== 'error' && textStatus !== 'parsererror') {
				return textStatus;
			}

			return defaultMessage;
		}

		function renderModelsError(requestData, xhr, textStatus, errorThrown) {
			var errorCode = requestData && requestData.data && requestData.data.code ? requestData.data.code : '';
			var errorMessage = getModelsErrorMessage(requestData, xhr, textStatus, errorThrown);
			var $modelSelect = $("select#model-select");

			$modelSelect.html('');
			if ( errorCode === 'rate_limited' ) {
				console.error('Eurostocks API limit reached while fetching models.');
				var limitMessage = (EUROSTOCKS_TRANSLATIONS && EUROSTOCKS_TRANSLATIONS.ERROR_API_LIMIT) ? EUROSTOCKS_TRANSLATIONS.ERROR_API_LIMIT : errorMessage;
				$modelSelect.append(
					$('<option>', { value: '', selected: 'selected' }).text(limitMessage)
				);
				return;
			}

			$modelSelect.append(
				$('<option>', { value: '', selected: 'selected' }).text(errorMessage)
			);
		}

		if ($('select#make-select').data('live-models')) {
			$('select#make-select').on('change', function (e) {

				var makeSelected = $('select#make-select').val();

				var FormData = $('form').serializeArray();
				FormData.push({ name: "action", value: "eurostocks_get_models_for_make" });
				FormData.push({ name: "data-action", value: "eurostocks_get_models_for_make" });
				FormData.push({ name: "security", value: eurostocks.eurostocks_security });

				$("select#model-select").html('');
				$("select#model-select").append('<option value="" selected="selected">' + EUROSTOCKS_TRANSLATIONS.LIVE_MODELS_LOAD + '</option>');

				$.ajax({
					type: "POST",
					url: eurostocks.admin_url,
					dataType: "json",
					data: FormData,
					success: function (data) {
						$('select#model-select').removeAttr('disabled');
						$("select#model-select").html('');

						if ( !data || !data.success ) {
							renderModelsError(data);
							return;
						}

						$.each(data.data, function (index, value) {
							if (value.modelGroupKey) {
								if (!EXCLUDED_MODELS.includes(value.modelGroupKey)) {
									var newOption = '<optgroup label="' + value.modelGroupDescription + '"><option value="' + value.modelGroupKey + '|GROUP" data-make="' + makeSelected + '">' + value.modelGroupDescription + ' (' + EUROSTOCKS_TRANSLATIONS.ALL + ') </option>';

									$.each(value.Models, function (childindex, childmodel) {
										if (!EXCLUDED_MODELS.includes(childmodel.modelKey)) {
											newOption = newOption + '<option value="' + childmodel.modelKey + '" data-make="' + makeSelected + '">' + childmodel.modelDescription + '</option>';
										}
									});
									newOption = newOption + '</optgroup>';
									$("select#model-select").append(newOption);
								}
							} else {
								if (!EXCLUDED_MODELS.includes(value.modelKey)) {
									$("select#model-select").append('<option value="' + value.modelKey + '" data-make="' + makeSelected + '">' + value.modelDescription + '</option>');
								}
							}
						});

						if ($("select#model-select").data('allow-empty')) {
							$("select#model-select").prepend('<option value="" selected="selected">' + EUROSTOCKS_TRANSLATIONS.MODELS_NO_PREFERENCE + '</option>');
						}
						$("select#model-select").removeAttr('disabled');

					},
					error: function (XMLHttpRequest, textStatus, errorThrown) {
						renderModelsError(null, XMLHttpRequest, textStatus, errorThrown);
					}
				});

			});

			function liveModelCheck() {
				if ($('select#make-select').val() != null && $('select#make-select').val() != "") {
					var makeSelected = $('select#make-select').val();

					var FormData = $('form').serializeArray();
					FormData.push({ name: "action", value: "eurostocks_get_models_for_make" });
					FormData.push({ name: "data-action", value: "eurostocks_get_models_for_make" });
					FormData.push({ name: "security", value: eurostocks.eurostocks_security });

					$.ajax({
						type: "POST",
						url: eurostocks.admin_url,
						dataType: "json",
						data: FormData,
						success: function (data) {
							$("select#model-select").html('');

							if ( !data || !data.success ) {
								renderModelsError(data);
								return;
							}

							$.each(data.data, function (index, value) {

								if (value.modelGroupKey) {
									if (!EXCLUDED_MODELS.includes(value.modelGroupKey)) {
										var newOption = '<optgroup label="' + value.modelGroupDescription + '"><option value="' + value.modelGroupKey + '|GROUP" data-make="' + makeSelected + '">' + value.modelGroupDescription + ' (' + EUROSTOCKS_TRANSLATIONS.ALL + ') </option>';
										
										$.each(value.Models, function (childindex, childmodel) {
											if (!EXCLUDED_MODELS.includes(childmodel.modelKey)) {
											newOption = newOption + '<option value="' + childmodel.modelKey + '" data-make="' + makeSelected + '">' + childmodel.modelDescription + '</option>';
											}
										});
										newOption = newOption + '</optgroup>';
										$("select#model-select").append(newOption);
									}
								} else {
									if (!EXCLUDED_MODELS.includes(value.modelKey)) {
										$("select#model-select").append('<option value="' + value.modelKey + '" data-make="' + makeSelected + '">' + value.modelDescription + '</option>');
									}
								}
							});

							if ($("select#model-select").data('allow-empty')) {
								$("select#model-select").prepend('<option value="" selected="selected">' + EUROSTOCKS_TRANSLATIONS.MODELS_NO_PREFERENCE + '</option>');
							}

							var urlParams = new URLSearchParams(window.location.search);
							var modelParam = urlParams.get('model');
							if (modelParam) {
								$("select#model-select").val(modelParam);
							}else{
								if(EUROSTOCKS_TRANSLATIONS.MODEL){
									$("select#model-select").val(EUROSTOCKS_TRANSLATIONS.MODEL);
								}
							}
						},
						error: function (XMLHttpRequest, textStatus, errorThrown) {
							renderModelsError(null, XMLHttpRequest, textStatus, errorThrown);
						}
					});
					
				}else{
					$('select#model-select').attr('disabled', 'disabled');
					}
			}
			liveModelCheck();


		} else {
			var models = $("select#model-select").html();

			$('select#make-select').on('change', function (e) {
				var optionSelected = $("option:selected", this);
				var makeSelected = this.value;
				$("select#model-select").html(models);
				$("select#model-select").children().each(function () {
					if ($(this).data('make') != makeSelected) {
						$(this).remove();
					}
				});
				if ($("select#model-select").data('allow-empty')) {
					$("select#model-select").prepend('<option value="" selected="selected">' + EUROSTOCKS_TRANSLATIONS.MODELS_NO_PREFERENCE + '</option>');
				}
			});

			$('select#model-select').on('change', function (e) {
				var optionSelected = $("option:selected", this);
				var modelmakeSelected = optionSelected.data('make');
				$('select#make-select option[value="' + modelmakeSelected + '"]').prop('selected', true);

			});

			function modelCheck() {
				if ($('select#make-select').val() != null) {
					var makeSelected = $('select#make-select').val();
					if($('select#model-select').val() != null){
						var oldmodel = $("select#model-select").val();
					}
					$("select#model-select").html(models);
					$("select#model-select").children().each(function () {
						if ($(this).data('make') != makeSelected && $(this).data('make') != undefined) {
							$(this).remove();
						}
					});
					if($('select#model-select').val() != null){
						$("select#model-select").val(oldmodel)
					}
				}
			}
			modelCheck();

		}


		$('#auto_ruilen').on('change', function (e) {
			$('#kenteken').toggleClass('euro-hidden');
			$('#kilometerstand').toggleClass('euro-hidden');
		});

		$('.es-input-c').change(function () {
			$(this).parents().filter("form").submit();
		});

		$('#show-es-second-10').on('click', function (e) {
			e.preventDefault();
			$('#es-second-10').removeClass('euro-hidden');
			$(this).addClass('euro-hidden');
			$('#hide-es-second-10').removeClass('euro-hidden');
		});
		$('#hide-es-second-10').on('click', function (e) {
			e.preventDefault();
			$('#es-second-10').addClass('euro-hidden');
			$(this).addClass('euro-hidden');
			$('#show-es-second-10').removeClass('euro-hidden');
		});



		$(document).on('click', '.estocks-image-link', function (e) {
			e.preventDefault();
			var imgLink = $(this).data('src');
			$('.estocks-headimg').attr('src', imgLink);
		});

		$(document).on('click', '.es-cta-action', function (e) {
			e.preventDefault();
			var cta = $(this).data('cta');
			if (cta == "a") {
				window.open($(this).attr('href'), '_blank');
			} else if (cta == "b") {
				$('#es-contact').addClass('open');
				$('body').addClass('euro-fixed');
			}
		});

		var modals = document.querySelectorAll("a[data-modal]");
		modals.forEach(function (trigger) {
			trigger.addEventListener('click', function (event) {
				event.preventDefault();
				const modal = document.getElementById(trigger.dataset.modal);
				modal.classList.add('open');
				$('body').addClass('euro-fixed');
				const exits = modal.querySelectorAll('.euro-modal-exit');
				exits.forEach(function (exit) {
					exit.addEventListener('click', function (event) {
						event.preventDefault();
						modal.classList.remove('open');

						$('body').removeClass('euro-fixed');
					});
				});
			});
		});

		$('#show-more-options').on('click', function (e) {
			e.preventDefault();
			$('#more-5-options').removeClass('euro-hidden');
			$(this).addClass('euro-hidden');
			$('#show-less-options').removeClass('euro-hidden');
		});
		$('#show-less-options').on('click', function (e) {
			e.preventDefault();
			$('#more-5-options').addClass('euro-hidden');
			$(this).addClass('euro-hidden');
			$('#show-more-options').removeClass('euro-hidden');
		});

		$('#eurostocks-filter-toggle').on('click', function (e) {
			e.preventDefault();
			$('#extra-filters').toggleClass('es-min-hidden');
			$('#eurostocks-filter-toggle').toggleClass('es-min-show');
			$('#eurostocks-filter-toggle2').toggleClass('es-min-hidden');
			$('#eurostocks-filter-toggle2').toggleClass('es-min-show');
		});
		$('#eurostocks-filter-toggle2').on('click', function (e) {
			e.preventDefault();
			$('#extra-filters').toggleClass('es-min-hidden');
			$('#eurostocks-filter-toggle').toggleClass('es-min-show');
			$('#eurostocks-filter-toggle2').toggleClass('es-min-hidden');
			$('#eurostocks-filter-toggle2').toggleClass('es-min-show');
		});


		$(document).on('submit', '#car-contact-form', function (e) {

			e.preventDefault();
			var FormData = $('#car-contact-form').serializeArray();
			FormData.push({ name: "action", value: "eurostocks_send_form" });
			FormData.push({ name: "data-action", value: "eurostocks_send_form" });
			FormData.push({ name: "security", value: eurostocks.eurostocks_security });
			$('.euro-contactform-submit').addClass('euro-hidden');

			$.ajax({
				type: "POST",
				url: eurostocks.admin_url,
				data: FormData,
				success: function (data) {
					$('#car-contact-form').empty().append("<p>" + data.data.message + "</p>");
					if (!!data.data.redirect_url) {
						location.href = data.data.redirect_url;
					}
					$('.euro-contactform-submit').removeClass('euro-hidden');
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					console.log("Status: " + textStatus);
					console.log("Error: " + errorThrown);
					$('.euro-contactform-submit').removeClass('euro-hidden');
				}
			});
		});

		$('.owl-carousel').owlCarousel({
			loop: true,
			margin: 10,
			nav: true,
			dots: false,
			items: 1,
			center: true
		})

	});

	$('.eurostocks-list-item').on('click', function (e) {
		e.preventDefault();
		var link = $(this).data('url');
		window.location.href = link;
	});

	document.addEventListener('DOMContentLoaded', function() {
		const favButtons = document.querySelectorAll('#es-fav');
		
		updateFavoriteButtonState();
		
		favButtons.forEach(button => {
			button.addEventListener('click', function(e) {
				e.preventDefault();
				
				const vehicleId = this.getAttribute('data-id');
				
				if (vehicleId) {
					let favorites = localStorage.getItem('eurostocks_favorites');
					let favoritesArray = [];
					
					if (favorites) {
						try {
							favoritesArray = JSON.parse(favorites);
						} catch(e) {
							favoritesArray = [];
						}
					}
					
					const index = favoritesArray.indexOf(vehicleId);
					
					if (index === -1) {
						favoritesArray.push(vehicleId);
						button.classList.add('active');
						updateButtonText(button, true);
					} else {
						favoritesArray.splice(index, 1);
						button.classList.remove('active');
						updateButtonText(button, false);
					}
					
					localStorage.setItem('eurostocks_favorites', JSON.stringify(favoritesArray));
					
					console.log('Favorites updated:', favoritesArray);
				}
			});
		});
		
		function updateFavoriteButtonState() {
			const favButtons = document.querySelectorAll('#es-fav');
			let favorites = localStorage.getItem('eurostocks_favorites');
			
			if (favorites) {
				try {
					const favoritesArray = JSON.parse(favorites);
					
					favButtons.forEach(button => {
						const vehicleId = button.getAttribute('data-id');
						
						if (vehicleId && favoritesArray.includes(vehicleId)) {
							button.classList.add('active');
							updateButtonText(button, true);
						} else {
							button.classList.remove('active');
							updateButtonText(button, false);
						}
					});
				} catch(e) {
					console.error('Error parsing favorites:', e);
				}
			}
		}
		
		function updateButtonText(button, isFavorite) {
			// Find the span with class 'button-text' inside the button
			const buttonText = button.querySelector('.euro-button-text');
			
			// If there's no span with that class, try any span
			const textElement = buttonText || button.querySelector('span') || button;
			
			if (isFavorite) {
				// Store original text first if we haven't already
				if (!button.hasAttribute('data-original-text')) {
					button.setAttribute('data-original-text', textElement.innerHTML);
				}
				textElement.innerHTML = EUROSTOCKS_TRANSLATIONS.ADDED_TO_FAVORITES;
			} else {
				// unfavoriting
				if (button.hasAttribute('data-original-text')) {
					textElement.innerHTML = button.getAttribute('data-original-text');
				}
			}
		}

		function hideVerificationFields($form) {
			$form.find('.eurostocks-verification-fields').hide();
			$form.find('.eurostocks-verification-retry').show();
		}

		function showVerificationFields($form) {
			$form.find('.eurostocks-verification-fields').show();
			$form.find('.eurostocks-verification-retry').hide();
			$form.find('#eurostocks-verification-email').prop('disabled', false).val('');
			$form.find('button[type="submit"]').prop('disabled', false);
			$form.find('.eurostocks-verification-message').removeClass('error success').text('');
		}

		function lockVerificationForm($form) {
			$form.find('#eurostocks-verification-email').prop('disabled', true);
			$form.find('button[type="submit"]').prop('disabled', true);
			$form.find('.eurostocks-verification-retry').hide();
		}

		$(document).on('submit', '#eurostocks-verification-form', function (event) {
			event.preventDefault();

			var $form = $(this);
			var $message = $form.find('.eurostocks-verification-message');
			var $submitButton = $form.find('button[type="submit"]');
			var email = $.trim($form.find('input[name="email"]').val());
			var pageType = $form.find('input[name="page_type"]').val() || 'general';

			var requestData = {
				action: 'eurostocks_submit_verification_email',
				security: eurostocks.eurostocks_security,
				email: email,
				page_type: pageType,
				return_url: window.location.href
			};

			$message.removeClass('error success').text('');
			$submitButton.prop('disabled', true);

			$.post(eurostocks.admin_url, requestData)
				.done(function (response) {
					var antiSpamTexts = (typeof eurostocks !== 'undefined' && eurostocks.anti_spam_texts) ? eurostocks.anti_spam_texts : {};
					var attemptsRemainingRaw = (response && response.data && typeof response.data.attempts_remaining !== 'undefined')
						? response.data.attempts_remaining
						: null;
					var attemptsRemaining = null;
					if (attemptsRemainingRaw !== null && typeof attemptsRemainingRaw !== 'undefined') {
						var parsedAttempts = parseInt(attemptsRemainingRaw, 10);
						if (!isNaN(parsedAttempts)) {
							attemptsRemaining = parsedAttempts;
						}
					}
					if (response && response.success) {
						var successMessage = (response.data && response.data.message)
							? response.data.message
							: (antiSpamTexts.success || 'Verification email sent.');
						$message.addClass('success').text(successMessage);
						if (attemptsRemaining !== null && attemptsRemaining <= 0) {
							lockVerificationForm($form);
						} else {
							hideVerificationFields($form);
						}
					} else {
						var errorMessage = (response && response.data && response.data.message)
							? response.data.message
							: (antiSpamTexts.error || 'Unable to process your request.');
						$message.addClass('error').text(errorMessage);
						if (attemptsRemaining !== null && attemptsRemaining <= 0) {
							lockVerificationForm($form);
						}
					}
				})
				.fail(function () {
					var antiSpamTexts = (typeof eurostocks !== 'undefined' && eurostocks.anti_spam_texts) ? eurostocks.anti_spam_texts : {};
					var fallbackMessage = antiSpamTexts.error || 'Unable to process your request.';
					$message.addClass('error').text(fallbackMessage);
				})
				.always(function () {
					$submitButton.prop('disabled', false);
				});
		});

		$(document).on('click', '.eurostocks-verification-retry', function () {
			var $form = $(this).closest('#eurostocks-verification-form');
			showVerificationFields($form);
		});
	});

})(jQuery);

function goBack() {
	window.history.back();
}
