import {
	PIXELIOCARTABANDONRECOVERYMOREHIDEIT
} from "../../../../frontend/assets/js/var/pixelio_cart_abandon_recovery_more_variable";
import DOMPurify from 'dompurify';
import {PixelioCartAbandonRecoveryMoreSlider} from "../components/pixelio_cart_abandon_recovery_more_slider";
import {
	PixelioCartAbandonRecoveryMoreLoaderSpinner
} from "../components/pixelio_cart_abandon_recovery_more_loader_spinner";
import {
	PixelioCartAbandonRecoveryMoreUpdate
} from "../components/pixelio_cart_abandon_recovery_more_update_popup";

// === To declare them globally in order to be called by multi tab switcher component ===
export function show_email_tab() {
	// === Gestion des onglets ===
	document.querySelectorAll(".pixelio-cart-abandon-recovery-more-card-email, .pixelio-cart-abandon-recovery-more-card-template")
		.forEach(el => el.classList.remove(PIXELIOCARTABANDONRECOVERYMOREHIDEIT));
	document.querySelectorAll(".pixelio-cart-abandon-recovery-more-card-logs-email")
		.forEach(el => el.classList.add(PIXELIOCARTABANDONRECOVERYMOREHIDEIT));
}

window.show_email_tab = show_email_tab;

export function show_email_logs_tab() {
	closeEditor();
	document.querySelectorAll(".pixelio-cart-abandon-recovery-more-card-email, .pixelio-cart-abandon-recovery-more-card-template")
		.forEach(el => el.classList.add(PIXELIOCARTABANDONRECOVERYMOREHIDEIT));
	document.querySelectorAll(".pixelio-cart-abandon-recovery-more-card-logs-email")
		.forEach(el => el.classList.remove(PIXELIOCARTABANDONRECOVERYMOREHIDEIT));

}
let pixelioQuillEditor = null;

function initPixelioQuillEditor() {
	console.log('initPixelioQuillEditor');
	const editor = document.querySelector(
		'#pixelio-cart-abandon-recovery-more-email-preview-content'
	);

	if (!editor) {
		pixelioQuillEditor = null;
		return null;
	}

	if (pixelioQuillEditor) {
		return pixelioQuillEditor;
	}

	pixelioQuillEditor = new Quill(editor, {
		theme: 'snow',
		placeholder: 'Write your email...',
		modules: {
			toolbar: [
				['bold', 'italic', 'underline'],
				[{ header: [1, 2, 3, false] }],
				[{ list: 'ordered' }, { list: 'bullet' }],
				['link'],
				['clean']
			]
		}
	});

	return pixelioQuillEditor;
}

function setEditorHtml(html) {
	var quill = initPixelioQuillEditor();

	const cleanHTML = DOMPurify.sanitize(html || '', {
		ALLOWED_TAGS: ['b', 'i', 'br', 'em', 'strong', 'a', 'p', 'div', 'span', 'ul', 'ol', 'li', 'h1', 'h2', 'h3'],
		ALLOWED_ATTR: ['href', 'class', 'target', 'rel']
	});

	quill.root.innerHTML = cleanHTML;
}

function getEditorHtml() {
	var quill  = pixelioQuillEditor

	if (!quill) {
		quill = initPixelioQuillEditor();
	}

	return quill.root.innerHTML || '';
}

function insertEditorText(text) {
	const quill = initPixelioQuillEditor();
	const range = quill.getSelection(true);
	const index = range ? range.index : quill.getLength();

	quill.insertText(index, text);
	quill.setSelection(index + text.length, 0);
}
window.pixelioAction2Callback = function pixelio_remove_email_template(id) {
	var loadSpinner1 = new PixelioCartAbandonRecoveryMoreLoaderSpinner();
	loadSpinner1.showPixelioLoader();
	if (pixelioData.apiKey) {
		jQuery.ajax({
			url: pixelioData.apiUrl + 'remove_email_template/' + id,
			type: 'DELETE',
			headers: {
				'x-api-key': pixelioData.apiKey
			},
			success: function (response) {
				if (response.status === 200) {
					$('#row-' + id).remove();

				}
				loadSpinner1.hidePixelioLoader();
			},
			error: function (xhr) {
				loadSpinner1.hidePixelioLoader();
			}
		});
	} else {
		jQuery.ajax({
			url: pixelioData.ajaxurl, // admin-ajax.php
			method: 'POST',
			data: {
				action: 'pixelio_cart_abandon_recovery_more_remove_email_template', // hook PHP
				nonce: pixelioData.nonce,
				id: id
			},
			success: function (response) {
				if (response.success) {
					// Supprime la ligne du tableau
					jQuery('#row-' + id).remove();
				} else {
					console.error('Error:', response.data.message);
				}
				loadSpinner1.hidePixelioLoader();
			},
			error: function (xhr, status, error) {
				console.error('AJAX Error:', status, error, xhr.responseText);
				loadSpinner1.hidePixelioLoader();
			}
		});

	}

};

window.show_email_logs_tab = show_email_logs_tab;
jQuery(function ($) {

	const languageMap = {
		en: ['en', 'eng', 'english', 'anglais', 'en-us', 'en_gb'],
		fr: ['fr', 'fra', 'french', 'français', 'francais', 'fr-fr'],
		nl: ['nl', 'dut', 'dutch', 'néerlandais', 'nederlands'],
		de: ['de', 'ger', 'german', 'allemand'],
		es: ['es', 'spa', 'spanish', 'espagnol'],
	};

	var pixelioCartAbandonRecoveryMoreSlider = new PixelioCartAbandonRecoveryMoreSlider();
	const templates = pixelioData.templates;

	const dummyData = pixelioData.dummyData;
	var loadSpinner = new PixelioCartAbandonRecoveryMoreLoaderSpinner();

	// === Variables globales ===
	var pixelioEditId = 0;
	var is_ia = 0;


	// === Initialisation ===
	$(".pixelio-cart-abandon-recovery-more-card-logs-email, .pixelio-cart-abandon-recovery-more-card-create-email").addClass(PIXELIOCARTABANDONRECOVERYMOREHIDEIT);

	// Initialise DataTable
	var table = new DataTable('#pixelio-cart-abandon-recovery-more-table', {
		paging: false,
		searching: true,
		rowReorder: true,
		ordering: true,
		responsive: true,
		info: false,
		language: {
			search: "Search:",
			lengthMenu: "Show _MENU_ entries",
			info: "Showing _START_ to _END_ of _TOTAL_ entries"
		}
	});

	// === Afficher le formulaire d'édition ===
	function hideOrShowForm() {
		editorOpen = true;
		editorOpenedState();
		$(".pixelio-cart-abandon-recovery-more-card-template").addClass(PIXELIOCARTABANDONRECOVERYMOREHIDEIT);
		$(".pixelio-cart-abandon-recovery-more-card-create-email").removeClass(PIXELIOCARTABANDONRECOVERYMOREHIDEIT);
	}

	// Création d'un nouveau template
	$('.pixelio-cart-abandon-recovery-more-create-email').on('click', function () {
		pixelioEditId = 0;
		hideOrShowForm.call(this);
		initTemplate(pixelioEditId);
	});

	function showValidateTemplateButton() {
		let showValidateButton = false;

		$("tr").each(function () {
			const isIA = $(this).attr("is_ia") == 1;
			const validated = $(this).attr("document_status");
			if (isIA && validated !== "validated") {
				showValidateButton = true;
			}
		});

		return showValidateButton;
	}

	// Edition d'un template existant
	$('#pixelio-cart-abandon-recovery-more-table tbody').on('click', '.pixelio-cart-abandon-recovery-more-edit-button', function () {
		pixelioEditId = $(this).data('template-id');
		is_ia = $(this).data('is_ia');
		hideOrShowForm.call(this);
		editTemplate(pixelioEditId);
	});


	let editorOpen = false;


	function closeEditor() {
		editorOpen = false;
		$(".pixelio-cart-abandon-recovery-more-card-template").removeClass(PIXELIOCARTABANDONRECOVERYMOREHIDEIT);
		$(".pixelio-cart-abandon-recovery-more-card-create-email").addClass(PIXELIOCARTABANDONRECOVERYMOREHIDEIT);
	}

	window.closeEditor = closeEditor

	window.addEventListener('popstate', (event) => {
		if (editorOpen) {
			closeEditor();
			// Empêcher le navigateur de revenir en arrière
			history.pushState(null, document.title, location.href);
		}
	});

	function editorOpenedState() {
		history.pushState({editor: true}, document.title, location.href);
	}

	function chooseLang(template, $card) {
		const rawLang = (template.language || '').toString().toLowerCase().trim();
		const $select = $card.find('#pixelio-cart-abandon-recovery-more-template-lang');
		let normalizedLang = 'en'; // fallback par défaut

		Object.entries(languageMap).some(([key, aliases]) => {
			if (aliases.includes(rawLang)) {
				normalizedLang = key;
				return true; // stop loop
			}
			return false;
		});

		$select.val(normalizedLang);
	}

// === Fonction d'édition ===
	function editTemplate(templateId) {
		destroyPixelioQuillEditor();
		var template = templates.find(t => parseInt(t.id) === parseInt(templateId));
		if (!template) return;
		var $card = $('.pixelio-cart-abandon-recovery-more-card-create-email');

		$card.find('#pixelio-cart-abandon-recovery-more-template-name').val(template.template_name);
		chooseLang(template, $card);
		chooseEmailType(template, $card);
		$card.find('#pixelio-cart-abandon-recovery-more-template-subject').val(template.subject);
		$card.find('#pixelio-subject').text(template.subject);


		const cleanHTML = DOMPurify.sanitize(template.body_html, {
			ALLOWED_TAGS: ['b', 'i', 'br', 'em', 'strong', 'a', 'p', 'div', 'button'],
			ALLOWED_ATTR: ["href", "class"]
		});

		setEditorHtml(template.body_html || '');

		if (template) {
			$card.find('#pixelio-cart-abandon-recovery-more-enable-send').prop('checked', template.is_active && template.is_active !== "0" || false).trigger('change');
			$card.find('[name="delay_value"]').val(template.send_after || '').trigger('change');
			$card.find('[name="enable_coupon"]').prop('checked', !!template.discount && parseFloat(template.discount) > 0).trigger('change');
			$card.find('[name="coupon_value"]').val(template.discount || '').trigger('change');
			$card.find('[name="coupon_type"]').val(template.discount_type).trigger('change');
			$card.find('[name="coupon_expire_value"]').val(template.discount_expiration_time || '').trigger('change');
			$card.find('input[name="type_of_email[]"]').each(function () {
				$(this).prop('checked', vars.email_type?.includes($(this).val()) || false).trigger('change');
			});
			$card.find('#pixelio-cart-abandon-recovery-more-placeholder-product').val(template.selected_product || '').trigger('change');
		}

		$card.show();
		pixelioReplaceVariables();
	}
	function chooseEmailType(template, $card) {
		const rawType = (template.type_of_email || '').toString().trim();

		const $select = $card.find('#pixelio-cart-abandon-recovery-more-email-type');

		const emailTypeMap = {
			'1': 'abandoned_cart',
			'2': 'review_cart'
		};

		$select.val(emailTypeMap[rawType] || 'abandoned_cart');
	}
	function destroyPixelioQuillEditor() {
		if (!pixelioQuillEditor) {
			return;
		}

		const editor = document.querySelector(
			'#pixelio-cart-abandon-recovery-more-email-preview-content'
		);

		if (!editor) {
			pixelioQuillEditor = null;
			return;
		}

		const parent = editor.parentNode;
		const clone = editor.cloneNode(false);

		parent.replaceChild(clone, editor);

		jQuery('.ql-toolbar').remove();

		pixelioQuillEditor = null;
	}
	// === Fonction d'initialisation ===
	function initTemplate(templateId) {
		destroyPixelioQuillEditor();
		var template = templates.find(t => t.id === templateId) || {};

		var $card = $('.pixelio-cart-abandon-recovery-more-card-create-email');

		$card.find('#pixelio-cart-abandon-recovery-more-template-name').val("");
		$card.find('#pixelio-cart-abandon-recovery-more-template-lang').val("fr");
		$card.find('#pixelio-cart-abandon-recovery-more-template-subject').val("");
		$card.find('#pixelio-cart-abandon-recovery-more-email-preview-content').html("");

		$card.find('#pixelio-cart-abandon-recovery-more-enable-send').prop('checked', template.enable_send || false).trigger('change');
		$card.find('#pixelio-cart-abandon-recovery-more-enable-coupon').prop('checked', template.enable_coupon || false).trigger('change');
		$card.find('#pixelio-subject').text(template.subject);
		$card.find('[name="delay_value"]').val(template.delay_value || '').trigger('change');
		$card.find('[name="delay_unit"]').val(template.delay_unit || '').trigger('change');
		$card.find('[name="coupon_value"]').val(template.discount || '').trigger('change');
		$card.find('[name="coupon_type"]').val(template.discount_type || '').trigger('change');
		$card.find('[name="coupon_expire_value"]').val(template.discount_expiration_time || '').trigger('change');

		$card.find('input[name="type_of_email[]"]').each(function () {
			$(this).prop('checked', (template.email_type || []).includes($(this).val())).trigger('change');
		});

		$card.find('#pixelio-cart-abandon-recovery-more-placeholder-product').val(template.selected_product || '').trigger('change');

		setEditorHtml(template.body_html || '');
		pixelioReplaceVariables();
	}

	// === Fermeture du formulaire ===
	$('.pixelio-cart-abandon-recovery-more-card-create-email-close').on('click', function () {
		closeEditor();
	});


	function pixelioReplaceVariables() {
		let content = getEditorHtml();
		let subject = $('#pixelio-cart-abandon-recovery-more-template-subject').val() || '';

		$.each(dummyData, function (key, val) {
			const regex = new RegExp(`{{\\s*${key}\\s*}}`, 'g');

			subject = subject.replace(regex, val);
			content = content.replace(regex, val);
		});

		$('#pixelio-cart-abandon-recovery-more-pixelio-subject').text(subject);
	}

	$('#type_of_email').on('change', function () {
		const selectedType = $(this).val();

		if (selectedType === 'abandoned_cart') {
			$('[data-key="firstname"], [data-key="lastname"]').hide();
			$('[data-key="recover_link"]').show();
		} else if (selectedType === 'review_cart') {
			$('[data-key="firstname"], [data-key="lastname"]').show();
			$('[data-key="recover_link"]').hide();
		} else {
			$('[data-key="firstname"], [data-key="lastname"], [data-key="recover_link"]').show();
		}
	}).trigger('change');

	$('.pixelio-cart-abandon-recovery-more-send-email').on('click', function (e) {
		e.preventDefault();
		const $recipient = $("#pixelio-cart-abandon-recovery-more-email-recipient");
		const value = $recipient.val();

		if (value === undefined || value === null || value.trim() === '') {
			alert('Please enter a valid email address');
			return false;
		}
		const emailTypes = $('#pixelio-cart-abandon-recovery-more-email-type')
			.val();
		loadSpinner.showPixelioLoader();
		const data = {
			action: 'pixelio_send_email',
			recipient: $('#pixelio-cart-abandon-recovery-more-email-recipient').val(),
			subject: $('#pixelio-cart-abandon-recovery-more-template-subject').val(),
			content: $('#pixelio-cart-abandon-recovery-more-email-preview-content').html(),
			type_of_email: emailTypes,
			coupon: {},
			id: pixelioEditId,
			nonce: pixelioData.nonce
		};

		if ($('#pixelio-cart-abandon-recovery-more-enable-coupon').is(':checked')) {
			data.coupon = {
				value: $('[name="coupon_value"]').val(),
				type: $('[name="coupon_type"]').val(),
				expire_value: $('[name="coupon_expire_value"]').val(),
			};
		}

		$.ajax({
			url: pixelioData.ajaxurl,
			method: 'POST',
			data: data,
			success: function (response) {
				if (response.success) alert(pixelioData.emailSent);
				else alert(pixelioData.ajaxError + ' ' + response.data);
				loadSpinner.hidePixelioLoader();
			},
			error: function (xhr, status, error) {
				alert(pixelioData.ajaxError + ' ' + error);
				loadSpinner.hidePixelioLoader();
			}
		});
	});

	$('#pixelio-cart-abandon-recovery-more-enable-send').on('change', function () {
		$('#pixelio-cart-abandon-recovery-more-send-delay').toggle(this.checked);
	});
	$('#pixelio-cart-abandon-recovery-more-template-subject').on('change', function () {
		$('#pixelio-subject').text($('#pixelio-cart-abandon-recovery-more-template-subject').val());
	});

	$('#pixelio-cart-abandon-recovery-more-enable-coupon').on('change', function () {
		$('#pixelio-cart-abandon-recovery-more-coupon-settings').toggle(this.checked);
	});

	// Gestion des placeholders
	function pixelioInsertPlaceholder(html) {
		const $container = jQuery("#pixelio-cart-abandon-recovery-more-email-preview-content")[0];
		if (!$container) return;

		let sel = window.getSelection();

		// Vérifie si la sélection est DANS le conteneur, sinon force la fin du conteneur
		let range;
		if (sel.rangeCount > 0 && $container.contains(sel.anchorNode)) {
			range = sel.getRangeAt(0);
		} else {
			// Force l'insertion à la fin du conteneur
			range = document.createRange();
			range.selectNodeContents($container);
			range.collapse(false);
		}

		// Conversion HTML en nodes
		let el = document.createElement('div');
		el.innerHTML = html;

		let frag = document.createDocumentFragment(), node, lastNode;
		while ((node = el.firstChild)) lastNode = frag.appendChild(node);

		// Insertion
		range.insertNode(frag);

		// Replace le curseur après l'insertion
		if (lastNode) {
			range = range.cloneRange();
			range.setStartAfter(lastNode);
			range.collapse(true);

			sel.removeAllRanges();
			sel.addRange(range);
		}
	}

	$('.pixelio-cart-abandon-recovery-more-insert-placeholder')
		.not('#pixelio-cart-abandon-recovery-more-insert-product-placeholder')
		.on('click', function () {
			const key = $(this).data('key');

			if (!key) {
				return;
			}

			if (key.includes('recover_link')) {
				insertEditorText('{{recover_link}}');
			} else {
				insertEditorText(`{{${key}}}`);
			}

			if (key.includes('discount')) {
				alert(pixelioData.enableCoupon);
			}
		});

	$('#pixelio-cart-abandon-recovery-more-insert-product-placeholder').on('click', function () {
		const productId = $('#pixelio-cart-abandon-recovery-more-placeholder-product').val();
		const productName = $('#pixelio-cart-abandon-recovery-more-placeholder-product option:selected').text();
		if (productId) {
			const html = `<div class="pixelio-cart-abandon-recovery-more-placeholder-product" data-id="${productId}" style="display:inline-block;border:1px dashed #ccc;padding:10px;border-radius:5px;">${productName}</div>`;
			pixelioInsertPlaceholder(html);
		} else alert(pixelioData.selectProduct);


		toggleAutoMode(pixelioData.autoModeChecked);

	});
	$('#pixelio-cart-abandon-recovery-more-email-logs-table').DataTable({
		order: [[5, 'desc']],
		stripeClasses: [],
		paging: true,
		pageLength: 10,
		info: false,
		columnDefs: [{"orderable": false, "targets": []}]
	});
	$('.pixelio-cart-abandon-recovery-more-validate-email').on('click', function () {
		var loadSpinner1 = new PixelioCartAbandonRecoveryMoreLoaderSpinner();
		if (pixelioData.apiKey) {
			loadSpinner1.showPixelioLoader();
			$.ajax({
				url: pixelioData.validateEmailTemplate,
				method: 'POST',
				contentType: 'application/json',
				headers: {'x-api-key': pixelioData.apiKey},
				success: function (response) {
					if (response.success) {
						location.reload();
					} else {
						console.error('Error:', response);
						alert(pixelioData.activateTemplateError);
					}
					loadSpinner1.hidePixelioLoader();
				},
				error: function (xhr) {
					console.error('Error:', xhr.responseText);
					alert(pixelioData.activateTemplateError);
					loadSpinner1.hidePixelioLoader();
				}
			});
		} else {
			alert(pixelioData.activate);

		}
		loadSpinner1.hidePixelioLoader();
	});

	function convertLegacyHtmlToSchema(html) {

		return {
			version: 1,
			subject: $('#pixelio-cart-abandon-recovery-more-template-subject').val(),
			blocks: [
				{
					type: 'text',
					content: html
				}
			]
		};
	}
	$('#pixelio-cart-abandon-recovery-more-save-email-content').on('click', function () {
		const $card = $('.pixelio-cart-abandon-recovery-more-card-create-email');

		const emailTypes = $card
			.find('#pixelio-cart-abandon-recovery-more-email-type')
			.val();

		const $content = $card.find('#pixelio-cart-abandon-recovery-more-email-preview-content');

		let rawText = getEditorHtml();

		const emailSchema = convertLegacyHtmlToSchema(rawText);

		const data = {
			id: pixelioEditId,
			template_name: $card.find('#pixelio-cart-abandon-recovery-more-template-name').val(),
			language: $card.find('#pixelio-cart-abandon-recovery-more-template-lang').val(),
			subject: $card.find('#pixelio-cart-abandon-recovery-more-template-subject').val(),

			body_html: rawText,
			body_json: JSON.stringify(emailSchema),

			is_active: $card.find('[name="enable_send"]').prop('checked'),
			send_after: $card.find('[name="delay_value"]').val(),
			discount: $card.find('[name="enable_coupon"]').prop('checked') ? $card.find('[name="coupon_value"]').val() : null,
			discount_type: $card.find('[name="enable_coupon"]').prop('checked') ?  $card.find('[name="coupon_type"]').val() : null,
			discount_expiration_time: $card.find('[name="enable_coupon"]').prop('checked') ?  $card.find('[name="coupon_expire_value"]').val() :null,
			type_of_email: emailTypes,
			is_ia: is_ia,
			synced: pixelioData.apiKey ? 1 : 0
		};

		if (typeof pixelioEditId !== 'undefined' && pixelioEditId !== 0) {
			data.id = pixelioEditId;
		}

		if (pixelioData.apiKey) {
			$.ajax({
				url: pixelioData.saveEmailTemplate,
				method: 'POST',
				contentType: 'application/json',
				headers: {
					'x-api-key': pixelioData.apiKey
				},
				data: JSON.stringify(data),
				success: function (response) {
					if (is_ia === 0) {
						$.ajax({
							url: pixelioData.ajaxurl,
							method: 'POST',
							data: $.extend({}, data, {
								action: 'pixelio_cart_abandon_recovery_more_save_email_template',
								nonce: pixelioData.nonce
							}),
							success: function (response) {
								if (response.success) {
									location.reload();
								} else {
									console.error('Error:', response.data.message);
									alert(pixelioData.saveTemplateError);
								}
							},
							error: function (xhr, status, error) {
								console.error('AJAX Error:', status, error, xhr.responseText);
								alert(pixelioData.saveTemplateError);
							}
						});
					} else {
						if (response.success) {
							location.reload();
						} else {
							console.error('Error:', response);
							alert(pixelioData.saveTemplateError);
						}
					}
				},
				error: function (xhr) {
					console.error('Error:', xhr.responseText);
					alert(pixelioData.saveTemplateError);
				}
			});
		} else {
			$.ajax({
				url: pixelioData.ajaxurl,
				method: 'POST',
				data: $.extend({}, data, {
					action: 'pixelio_cart_abandon_recovery_more_save_email_template',
					nonce: pixelioData.nonce
				}),
				success: function (response) {
					if (response.success) {
						location.reload();
					} else {
						console.error('Error:', response.data.message);
						alert(pixelioData.saveTemplateError);
					}
				},
				error: function (xhr, status, error) {
					console.error('AJAX Error:', status, error, xhr.responseText);
					alert(pixelioData.saveTemplateError);
				}
			});
		}
	});
	canShowValidateEmailButton();
	function canShowValidateEmailButton() {
		const hasApiKey = !!pixelioData.apiKey;
		const isAutoMode = $("input[name=ia-setup-mode]").val() === "on";
		if(!hasApiKey || !isAutoMode){
			$('.pixelio-cart-abandon-recovery-more-validate-email').hide();
		}


	}
	function toggleAutoMode(isAuto) {
		$('#pixelio-cart-abandon-recovery-more-auto-mode-banner').toggle(isAuto);
		$('.pixelio-cart-abandon-recovery-more-validate-email').toggle(isAuto);
		if(isAuto){ //means ia mode is activated
			$('.pixelio-cart-abandon-recovery-more-validate-email').toggle(showValidateTemplateButton());
			$('#pixelio-cart-abandon-recovery-more-auto-mode-banner-validation-required').toggle(showValidateTemplateButton());
			$(".ia-setup-mode .pixelio-cart-abandon-recovery-more-checkbox-yes").removeClass("pixelio-cart-abandon-recovery-more-hide-it");
			$(".ia-setup-mode .pixelio-cart-abandon-recovery-more-checkbox-no").addClass("pixelio-cart-abandon-recovery-more-hide-it");
			$(".pixelio-cart-abandon-recovery-more-create-email").addClass("pixelio-cart-abandon-recovery-more-hide-it");
		}else{
			$(".ia-setup-mode .pixelio-cart-abandon-recovery-more-checkbox-yes").addClass("pixelio-cart-abandon-recovery-more-hide-it");
			$(".ia-setup-mode .pixelio-cart-abandon-recovery-more-checkbox-no").removeClass("pixelio-cart-abandon-recovery-more-hide-it");
			$(".pixelio-cart-abandon-recovery-more-create-email").removeClass("pixelio-cart-abandon-recovery-more-hide-it");

		}
		$('.pixelio-cart-abandon-recovery-more-remove-button').prop('disabled', isAuto).toggle(!isAuto);
		$('.pixelio-cart-abandon-recovery-more-create-email').prop('disabled', isAuto).toggle(!isAuto);
		$('tr[is_ia="1"]').toggle(isAuto);
		$('tr[is_ia="0"]').toggle(!isAuto);
		$('tr[is_ia=""]').toggle(!isAuto);
	}

	if (pixelioData.apiKey) {
		const isAuto = $("input[name=ia-setup-mode]").val() === "on";
		jQuery(".pixelio-cart-abandon-recovery-more-opt-in-checkbox").prop("checked", isAuto);
		toggleAutoMode(isAuto);
	}
	$('.pixelio-cart-abandon-recovery-more-opt-in-checkbox-ia-setup-mode').on('change', function () {
		if (pixelioData.apiKey) {
			const isAuto = $("input[name=ia-setup-mode]").val() === "on";
			toggleAutoMode(isAuto);
			$.post(pixelioData.ajaxurl, {
				action: 'pixelio_toggle_auto_mode',
				enabled: isAuto,
				nonce: pixelioData.nonce
			});
		} else if ($(this).is(':checked')) {
			alert(pixelioData.activate);
			const isAuto = false;
			jQuery(".pixelio-cart-abandon-recovery-more-opt-in-checkbox-ia-setup-mode").prop("checked", isAuto);
			toggleAutoMode(isAuto);
		}
	});
});
