// Add subscriber form submission
jQuery(document).on('submit', '#ipb_add_subscriber_form', function(e) {
e.preventDefault();

if (!validateSubscriberForm('ipb_add_subscriber_form')) {
	return false;
}

var form = jQuery(this);
var submitBtn = form.find('button[type="submit"]');
var originalText = submitBtn.html();

// Show loading state
submitBtn.prop('disabled', true).html('<i class="fa-solid fa-spinner fa-spin"></i> Adding...');

// Prepare form data
var formData = {
	action: 'ipb_add_subscriber',
	sub_firstname: jQuery('#add_firstname').val(),
	sub_lastname: jQuery('#add_lastname').val(),
	email: jQuery('#add_emailaddress').val(),
	ipb_sub_campaign: jQuery('#add_campaign').val(),
	popup_status_toggle: jQuery('#add_status_toggle').val(),
	popup_privacy_toggle: jQuery('#add_privacy_toggle').val(),
	ipb_subscriber_nonce: ipb_ajax_vars.nonce
};

console.log('Sending add subscriber data:', formData);

// Submit via AJAX
jQuery.post(ipb_ajax_vars.ajaxurl, formData, function(response) {
	console.log('Add subscriber response:', response);
	try {
		// Handle both JSON string and object responses
		var result = typeof response === 'string' ? JSON.parse(response) : response;
		if (result.success) {
			// Close modal and refresh page
			jQuery.modal.close();
			location.reload();
		} else {
			// Show error message in the form instead of alert
			var errorMsg = result.data || 'Failed to add subscriber';
			jQuery('#ipb_add_subscriber_form').prepend('<div class="ipb_message ipb_message_error"><div class="message-text">' + errorMsg + '</div></div>');
			jQuery('html, body').animate({
				scrollTop: jQuery('#ipb_add_subscriber_form').offset().top - 100
			}, 500);
		}
	} catch (e) {
		console.error('Parse error:', e, response);
		jQuery('#ipb_add_subscriber_form').prepend('<div class="ipb_message ipb_message_error"><div class="message-text">Error: Invalid response from server</div></div>');
	}
}).fail(function(xhr, status, error) {
	console.error('AJAX failed:', xhr, status, error);
	jQuery('#ipb_add_subscriber_form').prepend('<div class="ipb_message ipb_message_error"><div class="message-text">Error: Failed to add subscriber. Please try again. (' + error + ')</div></div>');
}).always(function() {
	submitBtn.prop('disabled', false).html(originalText);
});
});

	// Edit subscriber form submission
jQuery(document).on('submit', '#ipb_edit_subscriber_form', function(e) {
	e.preventDefault();

	if (!validateSubscriberForm('ipb_edit_subscriber_form')) {
		return false;
	}

	var form = jQuery(this);
	var submitBtn = form.find('button[type="submit"]');
	var originalText = submitBtn.html();

	// Show loading state
	submitBtn.prop('disabled', true).html('<i class="fa-solid fa-spinner fa-spin"></i> Updating...');

	// Prepare form data
	var formData = {
		action: 'ipb_edit_subscriber',
		sub_edit: 'sub-edit',
		sub_edit_id: jQuery('#edit_hidden_id').val(),
		sub_firstname: jQuery('#edit_firstname').val(),
		sub_lastname: jQuery('#edit_lastname').val(),
		sub_emailaddress: jQuery('#edit_emailaddress').val(),
		ipb_sub_campaign: jQuery('#edit_campaign').val(),
		popup_status_toggle: jQuery('#edit_status_toggle').val(),
		popup_privacy_toggle: jQuery('#edit_privacy_toggle').val(),
		ipb_subscriber_nonce: ipb_ajax_vars.nonce
	};

	console.log('Sending edit subscriber data:', formData);

	// Submit via AJAX
	jQuery.post(ipb_ajax_vars.ajaxurl, formData, function(response) {
		console.log('Edit subscriber response:', response);
		try {
			// Handle both JSON string and object responses
			var result = typeof response === 'string' ? JSON.parse(response) : response;
			if (result.success) {
				// Close modal and refresh page
				jQuery.modal.close();
				location.reload();
			} else {
				alert('Error: ' + (result.data || 'Failed to update subscriber'));
			}
		} catch (e) {
			console.error('Parse error:', e, response);
			alert('Error: Invalid response from server');
		}
	}).fail(function(xhr, status, error) {
		console.error('AJAX failed:', xhr, status, error);
		alert('Error: Failed to update subscriber. Please try again. (' + error + ')');
	}).always(function() {
		submitBtn.prop('disabled', false).html(originalText);
	});
});
// Form validation
	function validateSubscriberForm(formId) {
		var isValid = true;
		var form = jQuery('#' + formId);

		// Clear previous errors
		form.find('.ipb_field_error').hide();
		form.find('.ipb_form_input, .ipb_form_select').removeClass('ipb_field_invalid');

		// Validate required fields
		form.find('input[required], select[required]').each(function() {
			var field = jQuery(this);
			var value = field.val().trim();
			var fieldName = field.attr('name');
			var errorElement = field.siblings('.ipb_field_error');

			if (!value) {
				field.addClass('ipb_field_invalid');
				errorElement.text('This field is required').show();
				isValid = false;
			} else if (fieldName === 'sub_emailaddress' && !isValidEmail(value)) {
				field.addClass('ipb_field_invalid');
				errorElement.text('Please enter a valid email address').show();
				isValid = false;
			}
		});

		return isValid;
	}
// Email validation helper
function isValidEmail(email) {
	var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
	return re.test(email);
}
// chart js
jQuery('#trigger_option').on('change',function(){
   var SltVal =  jQuery(this).val();

if(SltVal == 'exit-intent'){

 jQuery('.exit_intent').show();
}else{
    jQuery('.exit_intent').hide();
}
});
// Background selection handler - updated for new structure
jQuery('[name="background_selection"]').on('change', function(){
   var bgvalue = jQuery(this).val();
   var $colorSection = jQuery("#ipb_background_color_section");
   var $imageSection = jQuery("#ipb_background_image_section");
   
   // Also handle old structure for backward compatibility
   if(bgvalue == 'color'){
       $colorSection.show();
       $imageSection.hide();
       jQuery('.background_color').addClass('show');
       jQuery('.background_image').removeClass('show');
   }
   if(bgvalue == 'image'){
       $colorSection.hide();
       $imageSection.show();
       jQuery('.background_color').removeClass('show');
       jQuery('.background_image').addClass('show');
   }
});

// Initialize background selection on page load
jQuery(document).ready(function() {
    var initialBgValue = jQuery('[name="background_selection"]').val();
    var $colorSection = jQuery("#ipb_background_color_section");
    var $imageSection = jQuery("#ipb_background_image_section");
    
    if(initialBgValue == 'color'){
        $colorSection.show();
        $imageSection.hide();
        jQuery('.background_color').addClass('show');
        jQuery('.background_image').removeClass('show');
    }
    if(initialBgValue == 'image'){
        $colorSection.hide();
        $imageSection.show();
        jQuery('.background_color').removeClass('show');
        jQuery('.background_image').addClass('show');
    }
});
jQuery('.image_gallery:not(.active)').each(function(){
    jQuery('#image_gallery').removeClass('active');
});
jQuery(document).ready(function() {

		console.log('Subscription modal script loaded');

		// Handle subscription popup clicks to open modal
		jQuery(document).on("click", ".ipb_installed_popup .popup_subscription[data-type='subscription']", function(e) {
			e.preventDefault();
			//e.stopPropagation();

			console.log('Subscription popup clicked, opening modal...');

			// Open the template selection modal
			openTemplateSelectionModal();
		});

		// Close modal functionality
		jQuery(document).on('click', '.close-modal', function() {
			closeTemplateSelectionModal();
		});

		// Close modal when clicking outside - disabled since no background overlay
		// $(document).on('click', '#subscription-template-modal', function(e) {
		// 	if (e.target === this) {
		// 		closeTemplateSelectionModal();
		// 	}
		// });

		// Close modal with ESC key
		jQuery(document).on('keydown', function(e) {
			if (e.keyCode === 27 && $('#subscription-template-modal').is(':visible')) {
				closeTemplateSelectionModal();
			}
		});

		// Handle template selection from modal
		jQuery(document).on('click', '#template-selection-content .select_btn', function(e) {
			e.preventDefault();
			e.stopPropagation();

			const template = $(this).data('template');
			selectTemplateFromModal(template);
		});

		// Listen for template selection event from the template selection script
		jQuery(document).on('template-selected', '#subscription-template-modal', function(e, template) {
			selectTemplateFromModal(template);
		});

		// Handle preview from modal
		jQuery(document).on('click', '#template-selection-content .preview_btn', function(e) {
			e.preventDefault();
			e.stopPropagation();

			const template = $(this).data('template');
			// The preview functionality is already handled in the template-selection.php
		});

	});
function openTemplateSelectionModal() {
		console.log('Opening template selection modal...');

		// Show the modal immediately with loading content
		jQuery('#template-selection-content').html('<div style="text-align: center; padding: 50px;"><i class="fa fa-spinner fa-spin"></i> Loading templates...</div>');
		jQuery('#subscription-template-modal').css('display', 'block').addClass('show');

		// Load template selection content via AJAX
		jQuery.ajax({
			url: instnat_ajax_handler.ajaxurl,
			type: 'POST',
			data: {
				action: 'ipb_load_subscription_popups_templates',
				nonce: instnat_ajax_handler.display_nonce
			},
			success: function(response) {
				console.log('AJAX response received:', response);
				if (response.success) {
					jQuery('#template-selection-content').html(response.data);
					console.log('Template content loaded successfully');
				} else {
					jQuery('#template-selection-content').html('<div style="text-align: center; padding: 50px; color: #d63638;"><i class="fa fa-exclamation-triangle"></i> Failed to load templates. Please try again.</div>');
					console.error('Failed to load template selection content:', response);
				}
			},
			error: function(xhr, status, error) {
				jQuery('#template-selection-content').html('<div style="text-align: center; padding: 50px; color: #d63638;"><i class="fa fa-exclamation-triangle"></i> Connection error. Please try again.</div>');
				console.error('AJAX request failed:', status, error);
			}
		});
	}
	function closeTemplateSelectionModal() {
		console.log('Closing template selection modal...');
		jQuery('#subscription-template-modal').removeClass('show');

		// Hide the modal after animation completes
		setTimeout(function() {
			jQuery('#subscription-template-modal').css('display', 'none');
			jQuery('#template-selection-content').html('');
		}, 300);
	}

	function selectTemplateFromModal(template) {
		// Close the modal
		closeTemplateSelectionModal();

		// Redirect to the template creation page with the selected template
		const url = new URL(window.location.href);
		url.searchParams.set('type', 'subscription');
		url.searchParams.set('template', template);

		window.location.href = url.toString();
	}
document.addEventListener('DOMContentLoaded', function () {
	if (typeof Chart !== 'undefined') {
		const chartElement = document.getElementById('myChart');
		if (!chartElement) {
			return; // Chart element doesn't exist on this page
		}

		const ctx = chartElement.getContext('2d');
		var counts = instnat_ajax_handler.chart_titles.count;
		var titles = instnat_ajax_handler.chart_titles.title;
		const myChart = new Chart(ctx, {
			type: 'bar',
			data: {
				labels: titles,
				datasets: [{
					label: 'Clicks',
					backgroundColor: 'rgba(75, 192, 192, 0.2)',
					borderColor: 'rgba(75, 192, 192, 1)',
					data: counts,
					fill: false,
				}]
			},
			options: {
				responsive: true,
				title: {
					display: true,
					text: 'Analytics'
				},
				tooltips: {
					mode: 'index',
					intersect: false,
				},
				hover: {
					mode: 'nearest',
					intersect: true
				},
				scales: {
					xAxes: [{
						display: true,
						scaleLabel: {
							display: true,
							labelString: 'Title'
						}
					}],
					yAxes: [{
						display: true,
						scaleLabel: {
							display: true,
							labelString: 'Value'
						}
					}]
				}
			}
		});
	}

	// Unified tooltip handler for all info icons
	// Handle SVG image icons with .info wrapper
	document.querySelectorAll(".info img").forEach(function (img) {
		var infoWrapper = img.closest(".info");
		if (infoWrapper) {
			var detail = infoWrapper.querySelector(".detail");
			if (detail) {
				img.addEventListener("mouseenter", function () {
					detail.style.display = "block";
				});
				img.addEventListener("mouseleave", function () {
					detail.style.display = "none";
				});
			}
		}
	});

	// Handle ipb-info-icon with SVG images
	document.querySelectorAll(".ipb-info-icon img").forEach(function (img) {
		var infoWrapper = img.closest(".ipb-info-icon");
		if (infoWrapper) {
			var tooltip = infoWrapper.querySelector(".ipb-info-tooltip");
			if (tooltip) {
				img.addEventListener("mouseenter", function () {
					tooltip.style.display = "block";
				});
				img.addEventListener("mouseleave", function () {
					tooltip.style.display = "none";
				});
			}
		}
	});

	// Handle FontAwesome icons with title attribute (convert to tooltip on hover)
	document.querySelectorAll(".ipb-info-icon i.fa-info-circle[title]").forEach(function (icon) {
		var title = icon.getAttribute("title");
		var infoWrapper = icon.closest(".ipb-info-icon");
		if (title && infoWrapper) {
			// Create tooltip element if it doesn't exist
			var tooltip = infoWrapper.querySelector(".ipb-info-tooltip");
			if (!tooltip) {
				tooltip = document.createElement("div");
				tooltip.className = "ipb-info-tooltip";
				tooltip.textContent = title;
				infoWrapper.appendChild(tooltip);
			}

			icon.addEventListener("mouseenter", function () {
				tooltip.style.display = "block";
			});
			icon.addEventListener("mouseleave", function () {
				tooltip.style.display = "none";
			});
		}
	});

});

// Ace editor

//For HTML Editor
const url = window.location.href;
const url_html = url.split('?')[1];
if (url_html) {
	let params = url_html.split('&');
	let typeValue = null;
	params.forEach(function (param) {
		let pair = param.split('=');
		if (pair[0] === 'type') {
			typeValue = pair[1];
		}
	});
	if (typeValue == 'html') {

		var editor = ace.edit("editor");
		editor.setTheme("ace/theme/textmate");
		editor.session.setMode("ace/mode/html");
		editor.setOptions({
			autoScrollEditorIntoView: true,
			copyWithEmptySelection: true,
		});

		var htmlContent = jQuery("#popup_type_value").val();
		// htmlContent= htmlContent.replace(/\s+/g, '');
		editor.setValue(htmlContent, -1);
		editor.getSession().on('change', function () {
			var htmlCode = editor.getValue();
			console.log(htmlCode);
			jQuery('#popup_type_value').val(htmlCode);

			// Enhanced preview handles this automatically
		});

		jQuery('.ipb_submit').click(function () {
			var editor_val = editor.getValue();
			jQuery("#popup_type_value").val(editor_val);
		});
	}
}

(function ($) {
	'use strict';

	/**
	 * All of the code for your admin-facing JavaScript source
	 * should reside in this file.
	 *
	 * Note: It has been assumed you will write jQuery code here, so the
	 * $ function reference has been prepared for usage within the scope
	 * of this function.
	 *
	 * This enables you to define handlers, for when the DOM is ready:
	 *
	 * $(function() {
	 *
	 * });
	 *
	 * When the window is loaded:
	 *
	 * $( window ).load(function() {
	 *
	 * });
	 *
	 * ...and/or other possibilities.
	 *
	 * Ideally, it is not considered best practise to attach more than a
	 * single DOM-ready or window-load handler for a particular page.
	 * Although scripts in the WordPress core, Plugins and Themes may be
	 * practising this, we should strive to set a better example in our own work.
	 */

	$(function () {
		// (Cards view removed) Ensure table list is visible if any residual classes exist
		$('.instant_popup_wrapper .popup_lists').show();

		// Bulk actions: read selection and submit via existing AJAX (ipb_bulk_action)
		// Copy class button handler (on click / on hover)
		$(document).on('click', '.ipb-copy-class', function(){
			var $wrap = $(this).closest('.fields');
			var $input = $wrap.find('#trigger_class');
			if($input.length){
				var val = $input.val();
				try{
					navigator.clipboard.writeText('.' + val).then(function(){
						// Optional: small visual confirmation
					});
				}catch(e){
					// Fallback
					var temp = $('<textarea style="position:absolute;left:-9999px;top:-9999px;"></textarea>').appendTo('body');
					temp.val('.' + val).select();
					document.execCommand('copy');
					temp.remove();
				}
			}
		});
		$(document).on('click', '#popup_bulk_search_', function (e) {
			e.preventDefault();
			var status = $('#ipb_bulk_action').val();
			var popup_ids = [];
			var count = 0;
			if (!status) { alert('Please choose a bulk action'); return; }
			$('.popup_lists tbody tr').each(function () {
				var $row = $(this);
				var $cb = $row.find('.popu_check');
				if ($cb.length && $cb.is(':checked')) {
					popup_ids.push(parseInt($cb.val(), 10));
					count++;
				}
			});
			if (count === 0) { alert('Please select at least one popup'); return; }
			$.ajax({
				type: 'POST',
				url: instnat_ajax_handler.ajaxurl,
				data: { action: 'ipb_bulk_action', status: status, popup_ids: popup_ids, file_nonce: instnat_ajax_handler.file_nonce },
				success: function (response) {
					location.reload();
				}
			});
		});

	// Initialize Actions & Events section state
	var $actionClick = $(document).find("#action_click");
	if ($actionClick.length) {
		var $contentWrapper = $("#ipb_actions_content");
		var $controlDiv = $actionClick.closest(".ipb-actions-control");
		var $helperText = $controlDiv.find(".ipb-actions-helper");
		
		if ($actionClick.is(":checked")) {
			// Show content wrapper and hide helper text
			$contentWrapper.show();
			if ($helperText.length) {
				$helperText.hide();
			}
			
			$(document).find("#action_type_wrapper").show();
			// Show the appropriate section based on current action type
			var actionType = $("#action_type").val();
			if (actionType === 'redirect') {
				$(document).find("#action_redirect").show();
				$(document).find("#action_popup_selector").hide();
			} else if (actionType === 'open_popup') {
				$(document).find("#action_redirect").hide();
				$(document).find("#action_popup_selector").show();
			}
		} else {
			// Ensure helper text is shown when toggle is off
			if ($helperText.length) {
				$helperText.show();
			}
		}
	}
		if ($(document).find("#sound_open").val() == 'yes') {

			$(document).find("#sound_opening_file").show();

		}
		if ($(document).find("#sound_close").val() == 'yes') {

			$(document).find("#sound_close_file").show();

		}

		// TinyMCE automatically syncs content, but we ensure it's saved before preview/submit
		// The sync handlers are defined above in the TinyMCE section

		// $(".ql-editor").on("keyup", function () {

		// 	$("#popup_type_value").val(jQuery(this).html());
		// 	$("#preview_popup").html(jQuery(this).html())
		// 	console.log(jQuery(this).html());
		// 	setTimeout(function () {

		// 		$(".preview_link a").show();

		// 	}, 4000)
		// })

		// close select

		jQuery(".open_option").on("click", function (e) {

			e.preventDefault();

			jQuery(this).closest(".inp_field").find(".options").fadeIn();

		})

		jQuery(document).on("click", "#close", function (e) {

			e.preventDefault();
			jQuery(this).closest(".inp_field").find("label .status").text(jQuery(".inp_field #status").val());
			jQuery(this).closest(".inp_field .options").hide();

		})

		jQuery(document).on("change", "#trigger_option", function () {
			if (jQuery(this).val() === "exit_intent") {
				window.open("https://instantpopupbuilder.com/extensions/exit-intent-popup-for-wordpress/", '_blank');
				jQuery(this).find("option[value='exit_intent']").prop("disabled", true);
			}
		});

		jQuery(document).on("change", "#trigger_option", function () {
			if (jQuery(this).val() === "scroll_trigger") {
				window.open("https://instantpopupbuilder.com/extensions/scroll-trigger/", '_blank');
				jQuery(this).find("option[value='scroll_trigger']").prop("disabled", true);
			}
	    });

		jQuery(document).on("change", "#trigger_option", function () {
			if (jQuery(this).val() === "woo_disable") {
				window.open("https://instantpopupbuilder.com/extensions/woocommerce-popup/", '_blank');
				jQuery(this).find("option[value='woo_disable']").prop("disabled", true);
			}
	    });

		jQuery(document).on("change", "#page", function () {
			if (jQuery(this).val() === "woo_disable") {
				window.open("https://instantpopupbuilder.com/extensions/woocommerce-popup/", '_blank');
				jQuery(this).find("option[value='woo_disable']").prop("disabled", true);
			}
	    });

		jQuery(document).on("change", "#trigger_option", function () {
			if (jQuery(this).val() === "trigger_adblock") {
				window.open("https://instantpopupbuilder.com/extensions/adblock/", '_blank');
				jQuery(this).find("option[value='trigger_adblock']").prop("disabled", true);
			}
	    });

		jQuery(document).on("change", "#trigger_option", function () {
			if (jQuery(this).val() === "inactivity_trigger") {
				window.open("https://instantpopupbuilder.com/extensions/inactivity-trigger/", '_blank');
				jQuery(this).find("option[value='inactivity_trigger']").prop("disabled", true);
			}
	    });

		// Advanced Triggers upsell redirects
		jQuery(document).on("change", "#trigger_option", function () {
			var val = jQuery(this).val();
			if (val === 'page_depth_pro' || val === 'element_visibility_pro' || val === 'referrer_pro' || val === 'form_abandonment_pro' || val === 'returning_visitor_pro') {
				window.open("https://instantpopupbuilder.com/extensions/advanced-triggers/", '_blank');
				jQuery(this).find("option[value='"+val+"']").prop("disabled", true);
			}
		});

		// jQuery(document).on("change", "#page", function () {
		// 	if (jQuery(this).val() === "woo_disable") {
		// 		window.open("https://instantpopupbuilder.com/extensions/", '_blank');
		// 		jQuery(this).find("option[value='woo_disable']").prop("disabled", true);
		// 	}
	    // });

		jQuery(document).on("click", "#video_disabeld", function (e) {
			e.preventDefault();
			const href = jQuery(this).find("a").attr("href");
			console.log(href);
			window.open(href, '_blank');
		});

		// WordPress Media Library handler for image popup
		var ipb_image_frame;
		jQuery(document).on('click', '#ipb_media_upload_btn', function (e) {
			e.preventDefault();

			// If the media frame already exists, reopen it
			if (ipb_image_frame) {
				ipb_image_frame.open();
				return;
			}

			// Create the media frame
			ipb_image_frame = wp.media({
				title: 'Select or Upload Image for Popup',
				button: {
					text: 'Use this image'
				},
				multiple: false,
				library: {
					type: 'image'
				}
			});

			// When an image is selected, run a callback
			ipb_image_frame.on('select', function() {
				var attachment = ipb_image_frame.state().get('selection').first().toJSON();
				var fileUrl = attachment.url;

				jQuery("#popu_image_url").val(fileUrl);
				jQuery('#ipb_img_front').attr('src', fileUrl);
				jQuery('#ipb_img_front').show();
				jQuery('#ipb_remove_image').show();
				jQuery(".preview_link a").show();
				jQuery(".preview_link a").css("pointer-events", "auto");

				// Enhanced preview handles this automatically
			});

			// Open the media frame
			ipb_image_frame.open();
		});

		// Remove image handler
		jQuery(document).on('click', '#ipb_remove_image button', function (e) {
			e.preventDefault();
			jQuery("#popu_image_url").val('');
			jQuery('#ipb_img_front').attr('src', '').hide();
			jQuery('#ipb_remove_image').hide();
		});

		jQuery(document).on('change', '#sub_popup_image', function (e) {
			var $this = jQuery(this);
			var file_data = jQuery(this).prop('files')[0];
			var form_data = new FormData();
			form_data.append('file', file_data);
			form_data.append('action', 'ipb_file_upload');
			form_data.append('file_nonce', instnat_ajax_handler.file_nonce);

			jQuery.ajax({
				type: 'POST',
				url: instnat_ajax_handler.ajaxurl,
				contentType: false,
				processData: false,
				data: form_data,
				dataType: 'json',
				success: function (response) {
					if (response && response.success && response.data && response.data.url) {
						var fileUrl = response.data.url;
						$this.val('');
						jQuery("#popu_image_url").val(fileUrl);
						jQuery('#ipb_img_front').attr('src', fileUrl);
						jQuery('#ipb_img_front').show();
						jQuery(".preview_link a ").show();
						jQuery(".preview_link a").css("pointer-events", "auto");
						jQuery("#preview_popup #sub_right_col").html(`<img src="${fileUrl}" style="width:100%;" />`)
						jQuery('.back i').show();
					} else {
						var errorMsg = (response && response.data && response.data.message) ? response.data.message : 'File upload failed. Please try again.';
						alert(errorMsg);
					}
				},
				error: function() {
					alert('An error occurred during file upload. Please try again.');
				}
			});
		});

		// jQuery(document).on('change', '#popup_image', function (e) {
		// 	var $this = jQuery(this);
		// 	var file_data = jQuery(this).prop('files')[0];
		// 	var form_data = new FormData();
		// 	form_data.append('file', file_data);
		// 	form_data.append('action', 'ipb_file_upload');
		// 	form_data.append('file_nonce', instnat_ajax_handler.file_nonce);
		// 	// form_data.append('security', blog.security);

		// 	jQuery.ajax({
		// 		type: 'POST',
		// 		url: instnat_ajax_handler.ajaxurl,
		// 		contentType: false,
		// 		processData: false,
		// 		data: form_data,
		// 		success: function (response) {
		// 			$this.val('');
		// 			jQuery("#popup_image_url").val(response);
		// 			jQuery('#ipb_img_front').attr('src', response);
		// 			jQuery('#ipb_img_front').show();
		// 			jQuery(".preview_link a ").show();
		// 			// jQuery("#preview_popup").html(`<img src="${response}" style="width:100%;" />`)

		// 		}
		// 	});
		// });

		setTimeout(function () {

			jQuery(document).find(".update_messsage").hide();

		}, 5000)

		// Design tab: popup background image via WordPress Media Library
		var ipb_background_frame;
		function ipbUpdateDesignBackgroundPreview(fileUrl, filenameHint) {
			var $section = jQuery('#ipb_background_image_section');
			var $img = $section.length ? $section.find('.ipb_back_img') : jQuery('.ipb_back_img');
			var $sum = jQuery('#ipb_background_selected_summary');
			var name = filenameHint || '';
			if (!name && fileUrl) {
				try {
					var parts = fileUrl.split('/');
					name = parts[parts.length - 1] || fileUrl;
					name = name.split('?')[0];
				} catch (err) {
					name = fileUrl;
				}
			}
			if (fileUrl) {
				$img.attr('src', fileUrl).show();
				$sum.removeClass('is-empty').text('Selected: ' + name);
				jQuery('#ipb_background_remove_btn').show();
			} else {
				$img.attr('src', '').hide();
				$sum.addClass('is-empty').text('');
				jQuery('#ipb_background_remove_btn').hide();
			}
		}
		jQuery(document).on('click', '#ipb_background_media_btn', function (e) {
			e.preventDefault();
			if (typeof wp === 'undefined' || typeof wp.media === 'undefined') {
				alert('WordPress Media Library is not available. Please refresh the page or contact your administrator.');
				return;
			}
			if (ipb_background_frame) {
				ipb_background_frame.open();
				return;
			}
			ipb_background_frame = wp.media({
				title: 'Select or Upload Background Image',
				button: { text: 'Use this image' },
				multiple: false,
				library: { type: 'image' }
			});
			ipb_background_frame.on('select', function () {
				var attachment = ipb_background_frame.state().get('selection').first().toJSON();
				var fileUrl = attachment.url;
				var fname = attachment.filename || attachment.title || '';
				jQuery('#background_image_url').val(fileUrl).trigger('change');
				ipbUpdateDesignBackgroundPreview(fileUrl, fname);
			});
			ipb_background_frame.open();
		});
		jQuery(document).on('click', '#ipb_background_remove_btn', function (e) {
			e.preventDefault();
			jQuery('#background_image_url').val('').trigger('change');
			ipbUpdateDesignBackgroundPreview('');
		});

		// Enhanced text preview event - only use enhanced preview
		$(document).on("change", "#popup_type_value", function () {
			var text = $(this).val();
			console.log("Enhanced preview triggered");
			setTimeout(function () {
				$(".preview_links a").show();
				$(".preview_links a").css("pointer-events", "auto");
				// Enhanced preview handles this automatically
			}, 2000);
		})

		// select all checkbox

		$("#popu_all").on("change", function () {

			var is_checked = $(this).is(":checked");
			if (is_checked) {

				console.log("checked");
				$(this).closest("table").find("tbody tr").each(function () {

					$(this).find(".popu_check").prop("checked", true);
				})

			} else {
				console.log("unchecked");
				$(this).closest("table").find("tbody tr").each(function () {

					$(this).find(".popu_check").prop("checked", false);
				})
			}
		})

		// background toggle ;
		$(document).on("change", ".switch input", function () {
			if ($(this).is(":checked")) {

				$(this).val("yes");

			} else {
				$(this).val("no");
			}
		});

		// background opacity range;
		$(".input input[type='range']").on("change", function () {

			var val = $(this).val();
			jQuery(this).siblings(".range_val").html(val);
		})

	})

	var popup_ids = [];
	var count = 0;
	$(document).on("click", "#popup_bulk_search_", function (e) {

		e.preventDefault();
		var status = jQuery("#bulk_val").val();
		if (status == 'active') status = 'yes';
		if (status == 'inactive') status = 'no';

		if (status != null) {

			$(".popup_lists tbody tr").each(function ($index) {

				if ($(this).find(".popu_check").is(":checked")) {

					popup_ids.push($(this).find(".popu_check").val());
					count = count + 1;
				}
			});

			if (count > 0) {

				$.ajax({
					type: 'POST',
					url: instnat_ajax_handler.ajaxurl,
					data: {
						action: 'ipb_bulk_action',
						status: status,
						popup_ids: popup_ids,
						file_nonce: instnat_ajax_handler.file_nonce
					},
					success: function (response) {

						if (count == response) {

							location.href = location.href;
						} else {

							console.log(response);
						}
					}
				});
				location.href;

			} else {

				alert("Please Checked Popup");
			}

		}
		else {

			$(".popup_lists tbody tr").each(function ($index) {

				if ($(this).find(".popu_check").is(":checked")) {

					var url = $(this).find(".edit_btn").attr("href");
					setTimeout(function () {

						$(this).find(".edit_btn").trigger("click");

					}, $index * 1000);
					// window.open(url, '_blank');
				}
			});

		}
	});

	// tabs jquery
	function toggleEverywhereDisplayRuleUI($ruleRow) {
		if (!$ruleRow || !$ruleRow.length) {
			return;
		}

		var isEverywhere = $ruleRow.find(".selected_option").val() === "everywhere";
		var $isDisplayField = $ruleRow.find(".is_display").closest(".fields");
		var $specValueField = $ruleRow.find(".spec_val").closest(".fields");
		var $deleteIcon = $ruleRow.find(".fa-trash");

		if (isEverywhere) {
			$isDisplayField.hide();
			$specValueField.hide();
			$deleteIcon.hide();
		} else {
			$isDisplayField.show();
			$specValueField.show();
			$deleteIcon.show();
		}
	}

	function syncEverywhereDisplayRulesUI() {
		jQuery("#display .input_fields_wrap").each(function () {
			toggleEverywhereDisplayRuleUI(jQuery(this));
		});
	}

	function showEverywhereDisplayNotice() {
		var $helper = jQuery(".ipb-display-helper");
		if (!$helper.length) {
			return;
		}

		var $notice = jQuery("#ipb-display-everywhere-notice");
		if (!$notice.length) {
			$notice = jQuery('<span id="ipb-display-everywhere-notice" style="margin-left:8px;color:#1d2327;font-weight:600;">Popup will show everywhere.</span>');
			$helper.append($notice);
		}

		$notice.stop(true, true).show().delay(2200).fadeOut(300);
	}

	syncEverywhereDisplayRulesUI();

	$(document).on("click", ".plus", function () {

		var val = jQuery("#page").val();
		if (val === 'everywhere') {
			showEverywhereDisplayNotice();
			return;
		}
		var infoUrl = jQuery(this).closest(".rules").find(".info img").attr("src");
		console.log(infoUrl);
		var object = instnat_ajax_handler.display_setting;
		var selectObject;
		var $html = ''

		if (val == 'everywhere') {

			selectObject = object.everywhere;

		} else if (val == 'post') {

			selectObject = object.post;

		} else if (val == 'tags') {

			selectObject = object.tags;

		} else if (val == 'page') {

			selectObject = object.page;

		} else {
			console.log("Invalid value for #page");
			return;
		}
		console.log(selectObject);

		for (var key in selectObject) {

			$html += "<option value=" + key + ">" + selectObject[key] + "</option>";

		}
		if ($html) {

			var n_html = displayAppend($html, val, infoUrl);

			if ($("#display .initial_trigger").length > 0 || val == 'everywhere') {

				$("#display .form_fields").html(n_html);

			}
			else {

				if ($("#display .form_fields .input_fields_wrap:nth-child(1) .selected_option").val() == 'everywhere') {

					$("#display .form_fields .input_fields_wrap:nth-child(1)").remove();
				}
				$("#display .form_fields > input[type='hidden']").remove();
				$("#display .form_fields").append(n_html);
			}
			if (jQuery.fn.select2) {
				jQuery('.instant_popup_setting .spec_val').select2();
			}
			syncEverywhereDisplayRulesUI();


			// if (val == 'everywhere') {

			// 	// $(".plus").hide();

			// } else {

			// 	$("#display .form_fields").append(n_html);
			// 	// $(".plus").show();
			// }

		}

	})

	// Trigger append

	// tabs jquery
	jQuery(document).on("change", "#trigger_option", function () {

		var val = jQuery(this).val();
		var info_image = jQuery(document).find("#info_img").attr("src");
		var $html = ''

		if (val) {

			if (val != 'exit-intent') {

				var n_html = displayTrigger(val, info_image);
				jQuery("#trigger .trigger_options").removeClass("exit_trigger");
				jQuery("#trigger .trigger_options").html(n_html);
				jQuery("#exit_intent").fadeOut(300);
				// jQuery(document).find("#exit_intent").html('');
			}

			// if($("#trigger .form_fields .input_fields_wrap").length < 1){

			if (val == 'exit-intent') {

				// var html = '<div class="fields ex_del">' +
				// 	'<input type="number"  name="trigger_delay[]" id="trigger_delay" value="1" /></div></div>';

				// html += `<div class='display_option'><div class='trigger_dispaly'>
				// 	<label>Device Targeting</label>
				// 	<div class='d_opt'>
				// 	<label><input type="checkbox" name="display_option[]" value="desktop" /> Show On Desktop</label>
				// 	<label><input type="checkbox" name="display_option[]"  value="tablet"  /> Show On Tablet</label>
				// 	<label><input type="checkbox" name="display_option[]"  value="mobile"  /> Show On Mobile</label>
				// 	</div>
				// 	</div>
				// 	<div class='sens_options'>
				// 	<label>Sensitivity Level: ( Min:1 & Max:10 )</label>
				// 	<div class='sens_opt'>
				// 	<input type="range" id="exit_sensivity" name="exit_sensivity" min="1" max="10" value="5" step="1">
				// 	</div>
				// 	</div>`;

				jQuery("#exit_intent").fadeIn(300);
				// jQuery(document).find("#exit_intent").html(html);
				jQuery("#trigger .trigger_options").addClass("exit_trigger");
				jQuery("#trigger .trigger_options").html('');
				// }
			}
		}

	})

	// Animation Speed - Sync slider with numeric input
	jQuery(document).on("input change", "#speed_range", function () {
		var range = jQuery(this).val();
		jQuery("#animate_speed").val(range);
	})

	jQuery(document).on("input change", "#animate_speed", function () {
		var value = parseInt(jQuery(this).val());
		if (!isNaN(value) && value >= 0 && value <= 1000) {
			jQuery("#speed_range").val(value);
		}
	})

	// Initialize Animation Speed sync on page load
	jQuery(document).ready(function() {
		var initialSpeed = jQuery("#animate_speed").val();
		if (initialSpeed && jQuery("#speed_range").length) {
			jQuery("#speed_range").val(initialSpeed);
		} else if (!initialSpeed && jQuery("#speed_range").length) {
			// If no value, set default and sync
			var defaultSpeed = jQuery("#speed_range").val() || '500';
			jQuery("#animate_speed").val(defaultSpeed);
		}
	})

	// jQuery('body #spec_val').mobiscroll().select({
	// 	inputElement: document.getElementById('my-input'),
	// 	touchUi: false
	// });
	// jQuery(document).on("change","#page",function(){

	// 	var val = jQuery(this).val();

	// 	if($(".form_fields .input_fields_wrap").length > 0){

	// 		if(val == 'everywhere'){

	// 			$(".plus").hide();

	// 		}else{

	// 			$(".plus").show();
	// 		}
	// 	}
	// })

	// get selected value and call ajax function

	jQuery(document).on("change", ".selected_option", function () {
		var $html = '';
		var $this = jQuery(this);
		var val = jQuery(this).val();
		var nonce = instnat_ajax_handler.display_nonce
		var $currentRow = $this.closest(".input_fields_wrap");

		toggleEverywhereDisplayRuleUI($currentRow);

		if (val === 'everywhere') {
			$currentRow.find(".spec_val").html('<option value="everywhere" selected>Everywhere</option>');
			return;
		}

		if (val) {

			var formData = {

				action: 'ipb_display_ajax',
				value: val,
				nonce: nonce
			}

			$.ajax({
				type: 'POST',
				url: instnat_ajax_handler.ajaxurl,
				data: formData,
				success: function (response) {

					console.log(response);
					for (var key in response) {

						$html += "<option value=" + key + ">" + response[key] + "</option>";
					}

					console.log($html);
					$this.closest(".input_fields_wrap").find(".spec_val").html($html);
					// $this.closest(".input_fields_wrap").find(".spec_val").css("background-color","red");

				}
			});

		}
	})

	// delete element

	jQuery(document).on("click", ".fa-trash", function () {

		jQuery(this).closest(".input_fields_wrap").remove();
		if (jQuery("#display .form_fields .input_fields_wrap").length === 0 && jQuery("#display .form_fields > input[type='hidden']").length === 0) {
			jQuery("#display .form_fields").html(
				'<input type="hidden" name="selected_option[]" value="everywhere">' +
				'<input type="hidden" name="is_display[]" value="yes">' +
				'<input type="hidden" name="spec_val[0][]" value="everywhere">'
			);
		}
	})

	// Setting tabs css
	jQuery(document).on("click", ".tabs_list li", function () {
		jQuery(".tabs_list li").removeClass("active");
		jQuery(this).addClass("active");
		var tabClass = jQuery(this).data("id");
		jQuery(".tabs_content .tab_content").removeClass("active");
		jQuery(".tabs_content #" + tabClass).addClass("active");
	});

	// Vertical Tabs
	jQuery(document).on("click", ".v_tabs_list li", function () {
		jQuery(".v_tabs_list li").removeClass("active");
		jQuery(this).addClass("active");
		var tabClass = jQuery(this).data("id");
		jQuery(".v_tabs_content .v_tab_content").removeClass("active");
		jQuery(".v_tabs_content #" + tabClass).addClass("active");
	});

	// Action Tabs

	jQuery(document).on("click", "#action_click", function () {
		var $toggle = jQuery(this);
		var $contentWrapper = jQuery("#ipb_actions_content");
		var $controlDiv = $toggle.closest(".ipb-actions-control");
		var $helperText = $controlDiv.find(".ipb-actions-helper");

		if ($toggle.is(":checked")) {
			// Show content wrapper and hide helper text
			$contentWrapper.show();
			if ($helperText.length) {
				$helperText.hide();
			}
			$toggle.val("yes");
			
			// Show action type wrapper (now inside content wrapper)
			jQuery(document).find("#action_type_wrapper").show();
			
			// Show the appropriate section based on current action type
			var actionType = jQuery("#action_type").val();
			if (actionType === 'redirect') {
				jQuery(document).find("#action_redirect").show();
				jQuery(document).find("#action_popup_selector").hide();
			} else if (actionType === 'open_popup') {
				jQuery(document).find("#action_redirect").hide();
				jQuery(document).find("#action_popup_selector").show();
			}
		} else {
			// Hide content wrapper and show helper text
			$contentWrapper.hide();
			if ($helperText.length) {
				$helperText.show();
			}
			$toggle.val("no");
			
			// Hide all action-related sections
			jQuery(document).find("#action_type_wrapper").hide();
			jQuery(document).find("#action_redirect").hide();
			jQuery(document).find("#action_popup_selector").hide();
		}
	})

	// Handle action type change
	jQuery(document).on("change", "#action_type", function () {
		var actionType = jQuery(this).val();

		if (actionType === 'redirect') {
			jQuery(document).find("#action_redirect").show();
			jQuery(document).find("#action_popup_selector").hide();
		} else if (actionType === 'open_popup') {
			jQuery(document).find("#action_redirect").hide();
			jQuery(document).find("#action_popup_selector").show();
		}
	})

	jQuery(document).on("click", "#action_new_tab", function () {

		if (jQuery(this).is(":checked")) {

			jQuery(this).val("yes");

		} else {

			jQuery(this).val("no");
			jQuery(this).prop('checked', false);
		}
	})

	// Background Settings - Master Toggle
	jQuery(document).on("click", "#background_enabled", function () {
		var $toggle = jQuery(this);
		var $contentWrapper = jQuery("#ipb_background_content");
		var $controlDiv = $toggle.closest(".ipb-background-control");
		var $helperText = $controlDiv.find(".ipb-background-helper");
		var $backgroundSelection = jQuery("#background_selection");

		if ($toggle.is(":checked")) {
			// Show content wrapper and hide helper text
			$contentWrapper.show();
			if ($helperText.length) {
				$helperText.hide();
			}
			$toggle.val("yes");
			
			// Set default to "color" if no selection
			if (!$backgroundSelection.val() || $backgroundSelection.val() === '') {
				$backgroundSelection.val("color").trigger('change');
			} else {
				$backgroundSelection.trigger('change');
			}
		} else {
			// Hide content wrapper and show helper text
			$contentWrapper.hide();
			if ($helperText.length) {
				$helperText.show();
			}
			$toggle.val("no");
		}
	})

	// Background Settings - Selection Dropdown Change
	jQuery(document).on("change", "#background_selection", function () {
		var selection = jQuery(this).val();
		var $colorSection = jQuery("#ipb_background_color_section");
		var $imageSection = jQuery("#ipb_background_image_section");

		if (selection === 'color') {
			$colorSection.show();
			$imageSection.hide();
		} else if (selection === 'image') {
			$colorSection.hide();
			$imageSection.show();
		}
	})

	// Background Settings - Opacity Slider Sync
	jQuery(document).on("input change", "#backcolor_opacity", function () {
		var value = jQuery(this).val();
		jQuery("#backcolor_opacity_value").val(value);
	})

	jQuery(document).on("input change", "#backcolor_opacity_value", function () {
		var value = parseFloat(jQuery(this).val());
		if (!isNaN(value) && value >= 0 && value <= 1) {
			jQuery("#backcolor_opacity").val(value);
		}
	})

	jQuery(document).on("input change", "#backimage_opacity", function () {
		var value = jQuery(this).val();
		jQuery("#backimage_opacity_value").val(value);
	})

	jQuery(document).on("input change", "#backimage_opacity_value", function () {
		var value = parseFloat(jQuery(this).val());
		if (!isNaN(value) && value >= 0 && value <= 1) {
			jQuery("#backimage_opacity").val(value);
		}
	})

	// Initialize Background Settings state
	var $backgroundEnabled = jQuery("#background_enabled");
	if ($backgroundEnabled.length && $backgroundEnabled.is(":checked")) {
		var $contentWrapper = jQuery("#ipb_background_content");
		var $controlDiv = $backgroundEnabled.closest(".ipb-background-control");
		var $helperText = $controlDiv.find(".ipb-background-helper");
		
		$contentWrapper.show();
		if ($helperText.length) {
			$helperText.hide();
		}
		
		// Trigger selection change to show correct section
		jQuery("#background_selection").trigger('change');
	}

	// Sound tab
	jQuery(document).on("click", "#sound_open", function () {

		if (jQuery(this).is(":checked")) {

			jQuery(document).find("#sound_opening_file").show();
			jQuery(document).find("#sound_close_file").hide();
			jQuery(this).val("yes");
		} else {

			jQuery(document).find("#sound_opening_file").hide();
			jQuery(this).val("no");
		}
	})
	jQuery(document).on("click", "#sound_close", function () {

		if (jQuery(this).is(":checked")) {

			jQuery(document).find("#sound_close_file").show();
			jQuery(document).find("#sound_opening_file").hide();
			jQuery(this).val("yes");
		} else {

			jQuery(document).find("#sound_closing_file").hide();
			jQuery(this).val("no");
		}
	})

	// Handle sound file uploads (keep existing functionality)
	$(document).on("click", ".sound_fields i", function () {
		$(this).siblings("input[type='file']").click();
	});

	// Note: Image popup media upload is now handled by #ipb_media_upload_btn click handler above
	// This prevents the old file input click for image popups

	$(document).on('change', '#sound_open_file,#sound_closing_file', function (e) {
		var $this = $(this);
		var file_data = $(this).prop('files')[0];
		var form_data = new FormData();
		form_data.append('file', file_data);
		form_data.append('action', 'ipb_file_sound_upload');
		form_data.append('file_nonce', instnat_ajax_handler.file_nonce);

		$.ajax({
			type: 'POST',
			url: instnat_ajax_handler.ajaxurl,
			contentType: false,
			processData: false,
			data: form_data,
			dataType: 'json',
			success: function (response) {
				if (response && response.success && response.data && response.data.url) {
					var fileUrl = response.data.url;
					$this.siblings(".sound_hidden").val(fileUrl);
					var audio = $this.closest(".sound_fields").find(".audio_file");
					var source = audio.find("source");

					source.attr("src", fileUrl);
					audio[0].load();
					audio.show();
				} else {
					var errorMsg = (response && response.data && response.data.message) ? response.data.message : 'File upload failed. Please try again.';
					alert(errorMsg);
				}
			},
			error: function() {
				alert('An error occurred during file upload. Please try again.');
			}
		});
	});

	// play sound
	$(document).on("click", ".sound_fields .fa-play", function (e) {
		e.preventDefault();
		var audio = $(this).closest('.sound_fields').find('.audio_file')[0];
		audio.play();
		$(this).removeClass('fa-play');
		$(this).addClass("fa-pause");
	})
	$(document).on("click", ".sound_fields .fa-pause", function (e) {
		e.preventDefault();
		var audio = $(this).closest('.sound_fields').find('.audio_file')[0];
		audio.pause();
		$(this).removeClass('fa-pause');
		$(this).addClass("fa-play");
	})

	// Active/Inactive popup

	// Hide show size on toggle

	jQuery(document).on("change", ".popup_active .ipb_popup_active_toggle", function () {

		var $this = jQuery(this);
		// Do not allow activation when toggle is disabled (required extension not active).
		if ($this.prop("disabled")) {
			$this.prop("checked", false);
			return;
		}
		setTimeout(function () {

			var val = $this.val();
			var popup_id = $this.data('id');
			var nonce = instnat_ajax_handler.display_nonce
			if (val == 'yes') {

				$this.closest(".popup_active").find("label").html("Active");
			}
			else {

				$this.closest(".popup_active").find("label").html("Inactive");

			}
			var formData = {

				action: 'ipb_popup_status_ajax',
				value: val,
				nonce: nonce,
				id: popup_id
			}

			$.ajax({
				type: 'POST',
				url: instnat_ajax_handler.ajaxurl,
				data: formData,
				success: function (response) {

					console.log(response);

				}
			});

		}, 2000);
	})

	// Duplicate popups
	jQuery(document).on("click", ".dup_btn", function (e) {

		e.preventDefault();
		var $this = jQuery(this);
		var id= jQuery(this).data('id');
		var nonce = instnat_ajax_handler.display_nonce;
		var formData = {

				action: 'ipb_popup_duplicate',
				nonce: nonce,
				id: id
			}

			$.ajax({
				type: 'POST',
				url: instnat_ajax_handler.ajaxurl,
				beforeSend:function(){

					$this.closest(".popup_lists").find(".popup_loader").css("display", "flex");
				},
				data: formData,
				success: function (response) {

					$this.closest(".popup_lists").find(".popup_loader").css("display", "none");
					location.reload();
					// console.log(response);

				}
			});
	})

	// popup type screen

	jQuery(document).on("click", ".ipb_installed_popup .ipb_install", function () {

		var type = jQuery(this).data("type");
		// Get current URL
		if(type === 'subscription'){
          return false;
		}else{
		var currentUrl = new URL(window.location.href);
	     }

		// Set or update the 'type' parameter
		currentUrl.searchParams.set("type", type);

		// Redirect to the new URL with updated param
		window.location.href = currentUrl.toString();

	})

	// Pro extension search

	jQuery(document).on('input', '#search_ipb_extension', function () {
		var input = jQuery(this).val();

		// Normalize and validate input
		input = input ? input.toLowerCase().trim() : '';

		// If input is null, empty, or less than 2 characters, show all
		if (!input || input.length < 2) {
			jQuery('.pro_ext .ipb_grid').show();
			return;
		}

		jQuery('.pro_ext .ipb_grid').each(function () {
			var extType = jQuery(this).data('ext-type').toLowerCase();
			var matchCount = 0;

			// Count how many input characters exist in extType
			for (var i = 0; i < input.length; i++) {
				if (extType.includes(input[i])) {
					matchCount++;
				}
			}

			// Show if at least 2 characters match
			if (matchCount > 2) {
				jQuery(this).show();
			} else {
				jQuery(this).hide();
			}
		});
	});

	// Display 4 grid of the popup type and click display all

	// Initially show only the first 4
	// var allGrids = jQuery('.ipb_installed_popup .ipb_install');
	// allGrids.hide();
	// allGrids.slice(0, 4).show();

	// Show all on button click
	// jQuery(document).on('click', ".ipb_show_more p", function () {
	// 	var hiddenGrids = allGrids.filter(':hidden');
	// 	hiddenGrids.slideDown(300); // Slide down hidden grids
	// 	// jQuery(this).hide(); // Hide the "Show All" button
	// });

	// Change text on license grid
	jQuery(".ipb_license .ipb_license_active").hover(

		function () {
			// Mouse enter
			jQuery(this).text("Remove");
		},
		function () {
			// Mouse leave
			jQuery(this).text("Active");
		}
	)

	jQuery(".ipb_license .ipb_inactive_license").hover(

		function () {
			// Mouse enter
			jQuery(this).text("Active");
		},
		function () {
			// Mouse leave
			jQuery(this).text("Inactive");
		}
	)

	jQuery(document).find(".instant_popup_setting .info img").hover(

		function () {
			// Mouse enter
			jQuery(this).closest(".info").find(".detail").show();
		},
		function () {
			// Mouse leave
			jQuery(this).closest(".info").find(".detail").hide();
		}
	)

	jQuery(document).find(".input_fields_wrap .info img").hover(

		function () {
			// Mouse enter
			jQuery(this).closest(".info").find(".detail").show();
		},
		function () {
			// Mouse leave
			jQuery(this).closest(".info").find(".detail").hide();
		}
	)

	// Percentage Size - Sync slider with numeric input
	jQuery(document).on("input change", "#design_percentage", function () {
		var value = jQuery(this).val();
		jQuery("#design_percentage_value").val(value);
		// Also update old structure for backward compatibility
		jQuery(".design_percent .perc_count span").text(value);
	})

	jQuery(document).on("input change", "#design_percentage_value", function () {
		var value = parseInt(jQuery(this).val());
		if (!isNaN(value) && value >= 0 && value <= 100) {
			jQuery("#design_percentage").val(value);
			// Also update old structure for backward compatibility
			jQuery(".design_percent .perc_count span").text(value);
		}
	})

        // Text Styling Range Sliders
        jQuery(document).on("input change", "#text_border_radius", function () {
            jQuery(this).closest(".background_field").find(".range_val").text(jQuery(this).val() + "px")
        })

        jQuery(document).on("input change", "#text_font_size", function () {
            jQuery(this).closest(".background_field").find(".range_val").text(jQuery(this).val() + "px")
        })

        jQuery(document).on("input change", "#text_line_height", function () {
            jQuery(this).closest(".background_field").find(".range_val").text(jQuery(this).val())
        })

	// Detect actual popup size from rendered content
	function detectPopupSize() {
		let detectedWidth = 0;
		let detectedHeight = 0;

		// Try to find popup content in preview modal or page
		let $popupContent = jQuery('.instant-popup-content:visible').first();

		if ($popupContent.length === 0) {
			// Try enhanced preview modal
			$popupContent = jQuery('.enhanced-preview-modal .instant-popup-content').first();
		}

		if ($popupContent.length === 0) {
			// Try regular modal preview
			$popupContent = jQuery('.modal:visible .instant-popup-content').first();
		}

		if ($popupContent.length > 0) {
			// Get computed dimensions
			detectedWidth = Math.round($popupContent.outerWidth());
			detectedHeight = Math.round($popupContent.outerHeight());
		}

		// Fallback: estimate based on content type if no preview available
		if (detectedWidth === 0) {
			let popupType = jQuery('[name="popup_temp_type"]').val();
			switch(popupType) {
				case 'popup_text':
				case 'popup_html':
					detectedWidth = 600;
					detectedHeight = 400;
					break;
				case 'popup_image':
					detectedWidth = 500;
					detectedHeight = 400;
					break;
				case 'popup_subscription':
					detectedWidth = 700;
					detectedHeight = 500;
					break;
			case 'video':
				detectedWidth = 800;
				detectedHeight = 450;
				break;
			case 'contact':
				detectedWidth = 500;
				detectedHeight = 600;
				break;
			default:
				detectedWidth = 600;
				detectedHeight = 400;
		}
		}

		return { width: detectedWidth, height: detectedHeight };
	}

	// Hide show size on dropdown change with dynamic size detection
	function toggleSizeMode() {
		let is_percentage = jQuery("#design_percentage_toggle").val();
		let previous_mode = jQuery("#design_percentage_toggle").data('previous-mode');
		var $fixedSection = jQuery("#ipb_size_fixed_section");
		var $percentageSection = jQuery("#ipb_size_percentage_section");

		if (is_percentage == 'yes') {
			// Show percentage section, hide fixed section
			$percentageSection.show();
			$fixedSection.hide();
			
			// Also update old structure for backward compatibility
			jQuery("body .limit_option .design_percent").show();
			jQuery("body .limit_option .size_fields").hide();

			// If switching from fixed to percentage, calculate percentage from fixed size
			if (previous_mode == 'no') {
				let fixedWidth = parseInt(jQuery("#design_width").val()) || 0;
				if (fixedWidth > 0) {
					let viewportWidth = jQuery(window).width();
					let percentage = Math.round((fixedWidth / viewportWidth) * 100);
					percentage = Math.min(100, Math.max(10, percentage)); // Clamp between 10-100
					jQuery("#design_percentage").val(percentage);
					jQuery("#design_percentage_value").val(percentage);
					jQuery(".design_percent .perc_count span").text(percentage);
				}
			}
		}
		else {
			// Show fixed section, hide percentage section
			$fixedSection.show();
			$percentageSection.hide();
			
			// Also update old structure for backward compatibility
			jQuery("body .limit_option .design_percent").hide();
			jQuery("body .limit_option .size_fields").show();

			// If switching from percentage to fixed or initializing with 0 values, detect actual popup size
			let currentWidth = parseInt(jQuery("#design_width").val()) || 0;
			let currentHeight = parseInt(jQuery("#design_height").val()) || 0;

			if (currentWidth === 0 || currentHeight === 0 || previous_mode == 'yes') {
				let detectedSize = detectPopupSize();

				// Only populate if current value is 0 or switching from percentage
				if (currentWidth === 0) {
					jQuery("#design_width").val(detectedSize.width);
				}
				if (currentHeight === 0) {
					jQuery("#design_height").val(detectedSize.height);
				}
			}
		}

		// Store current mode for next change
		jQuery("#design_percentage_toggle").data('previous-mode', is_percentage);
	}

	jQuery(document).on("change", "#design_percentage_toggle", function () {
		toggleSizeMode();
	});

	// Initialize on page load
	if (jQuery("#design_percentage_toggle").length) {
		// Store initial mode
		jQuery("#design_percentage_toggle").data('previous-mode', jQuery("#design_percentage_toggle").val());
		toggleSizeMode();
		
		// Sync percentage slider with numeric input on load
		var initialPercentage = jQuery("#design_percentage").val();
		if (initialPercentage && jQuery("#design_percentage_value").length) {
			jQuery("#design_percentage_value").val(initialPercentage);
		}
	}

	// Re-detect size when preview is opened/closed
	jQuery(document).on('click', '.preview_btn, .enhanced-preview-trigger', function() {
		setTimeout(function() {
			if (jQuery("#design_percentage_toggle").val() == 'no') {
				let detectedSize = detectPopupSize();
				if (parseInt(jQuery("#design_width").val()) === 0) {
					jQuery("#design_width").val(detectedSize.width);
				}
				if (parseInt(jQuery("#design_height").val()) === 0) {
					jQuery("#design_height").val(detectedSize.height);
				}
			}
		}, 500); // Wait for preview to render
	});

	// Manual size detection button
	jQuery(document).on('click', '#detect_popup_size_btn', function(e) {
		e.preventDefault();

		let detectedSize = detectPopupSize();
		jQuery("#design_width").val(detectedSize.width);
		jQuery("#design_height").val(detectedSize.height);

		// Update aspect ratio if locked
		if (jQuery("#aspect_ratio_locked").val() == '1') {
			updateAspectRatio();
		}

		// Show success message
		jQuery("#detect_size_status").fadeIn(200).delay(2000).fadeOut(200);
	});

	// Lock/Unlock aspect ratio
	jQuery(document).on('click', '#lock_aspect_ratio_btn', function(e) {
		e.preventDefault();

		let isLocked = jQuery("#aspect_ratio_locked").val();
		let $icon = jQuery(this).find('i');

		if (isLocked == '0') {
			// Lock the aspect ratio
			jQuery("#aspect_ratio_locked").val('1');
			$icon.removeClass('fa-lock-open').addClass('fa-lock');
			$icon.css('color', '#1A73E8');
			jQuery(this).css('background', '#E3F2FD');
			jQuery(this).attr('title', 'Unlock aspect ratio');

			// Calculate and store current aspect ratio
			updateAspectRatio();
		} else {
			// Unlock the aspect ratio
			jQuery("#aspect_ratio_locked").val('0');
			$icon.removeClass('fa-lock').addClass('fa-lock-open');
			$icon.css('color', '#666');
			jQuery(this).css('background', '#f9f9f9');
			jQuery(this).attr('title', 'Lock aspect ratio');
		}
	});

	// Calculate and store aspect ratio
	function updateAspectRatio() {
		let width = parseFloat(jQuery("#design_width").val()) || 0;
		let height = parseFloat(jQuery("#design_height").val()) || 0;

		if (width > 0 && height > 0) {
			let aspectRatio = width / height;
			jQuery("#aspect_ratio_value").val(aspectRatio);
		}
	}

	// Width change handler - adjust height if locked
	jQuery(document).on('input change', '#design_width', function() {
		if (jQuery("#aspect_ratio_locked").val() == '1') {
			let width = parseFloat(jQuery(this).val()) || 0;
			let aspectRatio = parseFloat(jQuery("#aspect_ratio_value").val()) || 0;

			if (width > 0 && aspectRatio > 0) {
				let newHeight = Math.round(width / aspectRatio);

				// Check max constraint
				if (newHeight > 1500) {
					newHeight = 1500;
					let constrainedWidth = Math.round(newHeight * aspectRatio);
					jQuery("#design_width").val(constrainedWidth);
				}

				jQuery("#design_height").val(newHeight);
			}
		}
	});

	// Height change handler - adjust width if locked
	jQuery(document).on('input change', '#design_height', function() {
		if (jQuery("#aspect_ratio_locked").val() == '1') {
			let height = parseFloat(jQuery(this).val()) || 0;
			let aspectRatio = parseFloat(jQuery("#aspect_ratio_value").val()) || 0;

			if (height > 0 && aspectRatio > 0) {
				let newWidth = Math.round(height * aspectRatio);

				// Check max constraint
				if (newWidth > 2000) {
					newWidth = 2000;
					let constrainedHeight = Math.round(newWidth / aspectRatio);
					jQuery("#design_height").val(constrainedHeight);
				}

				jQuery("#design_width").val(newWidth);
			}
		}
	});

	// selelect2
	if (jQuery.fn.select2) {
		jQuery(document).find('.instant_popup_setting .spec_val').select2();
	}

	/** Hide "Close button position" while "Hide close button" is checked (position is irrelevant without an X). */
	function ipbSyncClosePositionRowVisibility() {
		jQuery('.closing_option').each(function () {
			var $block = jQuery(this);
			var $hide = $block.find('input[name="ipb_close_hide"]');
			var $row = $block.find('.ipb-close-position-row');
			if (!$hide.length || !$row.length) {
				return;
			}
			$row.toggle(!$hide.is(':checked'));
		});
	}

	jQuery(function () {
		ipbSyncClosePositionRowVisibility();
	});
	jQuery(document).on('change', '.closing_option input[name="ipb_close_hide"]', function () {
		ipbSyncClosePositionRowVisibility();
	});

	// WordPress TinyMCE editor sync for text popups
	// TinyMCE automatically handles content, but we need to ensure it's synced before form submission
	jQuery(document).on('submit', 'form', function() {
		// Sync TinyMCE content to textarea before form submission
		if (typeof tinyMCE !== 'undefined' && tinyMCE.get('popup_type_value')) {
			tinyMCE.get('popup_type_value').save();
		}
		
		// Sync Background Settings - if background is disabled, clear background_selection
		var $backgroundEnabled = jQuery("#background_enabled");
		var $backgroundSelection = jQuery("#background_selection");
		if ($backgroundEnabled.length && $backgroundSelection.length) {
			if (!$backgroundEnabled.is(":checked")) {
				// Background disabled - clear selection so backend doesn't apply background
				$backgroundSelection.val('');
			} else if (!$backgroundSelection.val() || $backgroundSelection.val() === '') {
				// Background enabled but no selection - default to color
				$backgroundSelection.val('color');
			}
		}
	});

	// Also sync on preview trigger
	jQuery(document).on('click', '.enhanced-preview-trigger', function(e) {
		// Sync TinyMCE content before preview
		if (typeof tinyMCE !== 'undefined' && tinyMCE.get('popup_type_value')) {
			tinyMCE.get('popup_type_value').save();
		}
	});

})(jQuery);

function displayAppend(select, val, infoUrl) {

	var length = jQuery("#display .input_fields_wrap").length;
	var ev_class = (val == 'everywhere' ? 'initial_trigger' : '');
	const parser = new DOMParser();
	const doc = parser.parseFromString(select, 'text/html');
	const hasAllPosts = doc.querySelector('option[value="all-posts"]') !== null;
	const hasAllPages = doc.querySelector('option[value="all-pages"]') !== null;
	console.log(hasAllPosts);
	var def_opt = hasAllPosts ? "All Post" : "Select Option";
	def_opt = hasAllPages ? "All Pages" : def_opt;
	var def_val = hasAllPosts ? "all-posts" : 'everywhere';
	def_val = hasAllPages ? "all-pages" : def_val;
	if (jQuery("#display .initial_trigger").length == 1 || val == 'everywhere') {

		length = 0;
	}
	console.log(length);
	var html = '<div class="input_fields_wrap ' + ev_class + '"><div class="fields">' +
		'<select name="selected_option[]" class="selected_option">' +
		select +
		'</select>' +
		'</div>' +
		'<div class="fields">' +
		'<select name="is_display[]" class="is_display" required>' +
		'<option value="yes" selected>Is</option>' +
		'<option value="no">Is not</option>' +
		'</select>' +
		'</div>' +
		'<div class="fields">' +
		'<select name="spec_val[' + (length) + '][]" class="spec_val"  multiple>' +
		'<option value="' + def_val + '" selected>' + def_opt + '</option>' +
		'</select>' +
		'</div>' +
		'<i class="fa-solid fa-trash"></i></div>';

	return html;

}

function displayTrigger(value, InfoImg) {

	var html = '';

	if (value == 'onload') {

		html += '<div class="fields">' +
			'<input type="number"  name="trigger_delay[]" placeholder="Delay" id="trigger_delay" /></div><i class="fa-solid fa-trash"></i>';
	}

	// if (value == 'exit-intent') {

	// 	html += '<div class="fields ex_del">' +
	// 		'<input type="number"  name="trigger_delay[]" id="trigger_delay" value="1" /></div><i class="fa-solid fa-trash"></i><div class="info"><img src="'+InfoImg+'" alt=""><div class="detail" style="display: none;">Info</div></div></div>';

	// 	html += `<div class='display_option'><div class='trigger_dispaly'>
	// 		<label>Device Targeting</label>
	// 		<div class='d_opt'>
	// 		<label><input type="checkbox" name="display_option[]" value="desktop" /> Show On Desktop</label>
	// 		<label><input type="checkbox" name="display_option[]"  value="tablet"  /> Show On Tablet</label>
	// 		<label><input type="checkbox" name="display_option[]"  value="mobile"  /> Show On Mobile</label>
	// 		</div>
	// 		</div>
	// 		<div class='sens_options'>
	// 		<label>Sensitivity Level: ( Min:1 & Max:10 )</label>
	// 		<div class='sens_opt'>
	// 		<input type="range" id="exit_sensivity" name="exit_sensivity" min="1" max="10" value="5" step="1">
	// 		</div>
	// 		</div>`;

	// }
	if (value == 'onclick') {

		html += '<div class="fields">' +
			'<input type="hidden"  value="0" name="trigger_delay[]" id="trigger_delay" />' +
			'<input type="text" value="instant-popup-trigger-' + Math.round(Math.random() * 1000) + '" name="trigger_class_click[]" id="trigger_class" readonly />' +
			'<i class="fa-solid fa-copy ipb-copy-class" title="Copy CSS class" style="margin-left:6px;cursor:pointer;"></i>' +
			'</div><i class="fa-solid fa-trash"></i>';
	}
	if (value == 'onhover') {

		html += '<div class="fields">' +
			'<input type="hidden"  value="0" name="trigger_delay[]" id="trigger_delay" />' +
			'<input type="text" value="instant-popup-trigger-' + Math.round(Math.random() * 1000) + '" name="trigger_class[]" id="trigger_class" readonly />' +
			'<i class="fa-solid fa-copy ipb-copy-class" title="Copy CSS class" style="margin-left:6px;cursor:pointer;"></i>' +
			'</div><i class="fa-solid fa-trash"></i>';
	}

	// html += "</div>";
	return html;

}
