(function ($) {
	'use strict';

	/**
	 * All of the code for your public-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.
	 */

	// jQuery(".instant_popup-front").hide();
	// $(window).load(function(){

	// 	jQuery(".instant_popup-front").fadeIn();
	// 	jQuery(".instant-cross").on("click",function(e){

	// 		jQuery(this).closest(".instant_popup-front").fadeOut();
	// 	})

	// })

	jQuery(".instant_popup-front").hide();

	var ipbLastPointerX, ipbLastPointerY;
	jQuery(document).on('click touchend', function (e) {
		var ev = e.originalEvent;
		if (ev.changedTouches && ev.changedTouches.length) {
			ipbLastPointerX = ev.changedTouches[0].clientX;
			ipbLastPointerY = ev.changedTouches[0].clientY;
		} else {
			ipbLastPointerX = e.clientX;
			ipbLastPointerY = e.clientY;
		}
	});

	$(function () {

		/**
		 * Spin-to-Win: when visitor already played and mode is hide/normal/close,
		 * core must not open the popup — a programmatic close on DOM ready races
		 * the onload timer and can leave the dark overlay visible (broken page).
		 */
		function ipbIsStwSilentBlocked($popup) {
			return $popup.length && $popup.attr('data-stw-silent-dismiss') === '1';
		}
		window.ipbIsStwSilentBlocked = ipbIsStwSilentBlocked;

		function ipbCircularReveal($popup, durationSec) {
			var $content = $popup.find(".instant-popup-content");
			var el = $content[0];
			if (!el) return;

			$popup.fadeIn(0);

			var rect = el.getBoundingClientRect();
			var cx, cy;
			if (ipbLastPointerX !== undefined && ipbLastPointerY !== undefined) {
				cx = ipbLastPointerX - rect.left;
				cy = ipbLastPointerY - rect.top;
			} else {
				cx = rect.width / 2;
				cy = rect.height / 2;
			}

			var maxX = Math.max(cx, rect.width - cx);
			var maxY = Math.max(cy, rect.height - cy);
			var endRadius = Math.ceil(Math.sqrt(maxX * maxX + maxY * maxY));

			el.animate([
				{ clipPath: 'circle(0px at ' + cx + 'px ' + cy + 'px)' },
				{ clipPath: 'circle(' + endRadius + 'px at ' + cx + 'px ' + cy + 'px)' }
			], {
				duration: durationSec * 1000,
				easing: 'ease-out',
				fill: 'forwards'
			});
		}

		/**
		 * Read data-* as literal strings. jQuery .data() camelCases hyphenated names and can
		 * coerce values, so closing flags were often undefined / wrong while data-close-positon worked.
		 */
		function ipbReadHyphenAttr($el, hyphenName) {
			var v = $el.attr('data-' + hyphenName);
			return (v === undefined || v === null) ? '' : String(v).trim();
		}
		function ipbAttrIsYes(val) {
			var s = String(val === undefined || val === null ? '' : val).toLowerCase().trim();
			return s === 'yes' || s === '1' || s === 'true';
		}

		var count = 0;
		jQuery(document).find(".instant_popup-front").each(function () {

			var $popupRoot = jQuery(this);
			var id = $popupRoot.data("form-id");
			var close_escape = ipbReadHyphenAttr($popupRoot, 'close-escape');
			// Backward compatibility: support both typo "close-positon" and correct "close-position"
			var close_positon = ipbReadHyphenAttr($popupRoot, 'close-positon') || ipbReadHyphenAttr($popupRoot, 'close-position') || '';
			var close_outside = ipbReadHyphenAttr($popupRoot, 'close-outside');
			var close_hide = ipbReadHyphenAttr($popupRoot, 'close-hide');
			var close_hover = ipbReadHyphenAttr($popupRoot, 'close-hover');
			var delayRaw = parseInt(jQuery(this).data("delay"), 10);
			var delay = delayRaw;
			var popup_class = jQuery(this).data("click");
			var popup_hover = jQuery(this).data("hover");
			var popup_trigger = jQuery(this).data("trigger");
			var popup_position = jQuery(this).data('position');
			var limit_expiry = jQuery(this).data('limit-expiry');
			var limit_count = jQuery(this).data('limit-count') ? parseInt(jQuery(this).data('limit-count')) : 0;
			console.log(limit_count);
			// var views = parseInt(jQuery(this).data('views-count'));
			let views = getCookie("popup_count"+id) || 0;
			console.log('views',views);
			// if (popupCount < 10) {
			// 	showPopup(); // Function to display the popup
			// 	popupCount++;
			// 	setCookie("popup_count", popupCount, 30); // Store for 30 days
			// }
			// views = views ? views : 0;

			// if (limit_count != '' && views< limit_count) {

			// 	var limit_count = limit_count != 0 ? limit_count - 1 : -1;

			// }
			var back_color_toggle = jQuery(this).data('back_color_toggle');
			var background_color = jQuery(this).data('background_color');
			var back_image_toggle = jQuery(this).data('back_image_toggle');
			var background_image = jQuery(this).data('background_image');
			var back_image_pos_toggle = jQuery(this).data('back_image_pos_toggle');
			var back_img_position = jQuery(this).data('back_img_position');
			var back_image_size = jQuery(this).data('back_image_size');
			var backcolor_opacity = jQuery(this).data('backcolor_opacity');
			var backimage_opacity = jQuery(this).data('backimage_opacity');
		var design_width = jQuery(this).data('design_width') || 0;
		var design_height = jQuery(this).data('design_height') || 0;
		var design_percentage = jQuery(this).data('design_percentage') || 50;
		var design_percentage_toggle = jQuery(this).data('design_percentage_toggle') || 'yes';
			var animate_type = jQuery(this).data('animate_type');
			var animate_speed = parseInt(jQuery(this).data('animate_speed')) / 100;
			var animate_origin = jQuery(this).data('animate_origin');
		var action = jQuery(this).data('action');
		var action_type = jQuery(this).data('action-type') || 'redirect';
		var action_popup_id = jQuery(this).data('action-popup-id');
		var action_url = jQuery(this).data('action-url');
		var action_tab = jQuery(this).data('action-tab');
		var redirect_delay_seconds_attr = jQuery(this).data('redirect-delay-seconds');
		var back_zindex = jQuery(this).data('back_zindex');
		var border_enabled = jQuery(this).data('border-enabled');
		var border_width = jQuery(this).data('border-width');
		var border_color = jQuery(this).data('border-color');

        // Text Styling Settings (always applied with defaults)
        var text_padding_top = jQuery(this).data('text_padding_top') || 20;
        var text_padding_right = jQuery(this).data('text_padding_right') || 25;
        var text_padding_bottom = jQuery(this).data('text_padding_bottom') || 20;
        var text_padding_left = jQuery(this).data('text_padding_left') || 25;
        var text_border_radius = jQuery(this).data('text_border_radius') || 12;
        var text_color = jQuery(this).data('text_color') || '#333333';
        var text_font_size = jQuery(this).data('text_font_size') || 16;
        var text_line_height = jQuery(this).data('text_line_height') || 1.5;

			// limit_count = limit_count  > 0 ?  limit_count : limit_count -1;
			var isIpbAnnouncementBar = jQuery(this).hasClass('ipb-announcement-bar-root');
			var ipbScheduleSeconds;
			if (isIpbAnnouncementBar) {
				ipbScheduleSeconds = isNaN(delayRaw) ? 0 : delayRaw;
			} else {
				delay = delay == 0 || delay == '' ? 2 : delay;
				count = count + delay;
				ipbScheduleSeconds = count;
			}
			var $this = jQuery(this);
			var $audioOpen = $this.find("#ipb_audioOpen")[0];
			var $audioClose = $this.find("#ipb_audioClose")[0];
			var nonce = instant_ajax_handler.view_count;
			var display_mode = jQuery(this).data("target");
			// Z-index popup (only when explicitly set)
			if (typeof back_zindex !== 'undefined' && back_zindex !== '' && back_zindex !== null) {
				jQuery($this).css("z-index", back_zindex);
			}

			// Border styling (applied to popup container)
			if (border_enabled === 'yes') {
				var bw = parseInt(border_width, 10);
				if (isNaN(bw) || bw < 0) bw = 0;
				if (bw > 40) bw = 40;
				var bc = border_color ? String(border_color) : '#111827';
				jQuery($this).find(".instant-popup-content").css("border", bw + "px solid " + bc);
			} else {
				// Ensure old borders don't stick when disabled
				jQuery($this).find(".instant-popup-content").css("border", "none");
			}

			// Popup Background Color

			if (back_color_toggle == 'yes') {

				jQuery($this).find(".instant-popup-content").css("background-color", background_color);
				jQuery($this).find(".instant-popup-content").css("opacity", backcolor_opacity);
			}

			// Popup Background Image: saved toggle yes, or legacy rows with URL but empty toggle (not explicitly "no")
			var ipb_bg_url = background_image ? String(background_image) : '';
			var ipb_bg_url_ok = ipb_bg_url && ipb_bg_url !== '1' && ipb_bg_url !== '#' && /^(\/\/|https?:|\/)/i.test(ipb_bg_url);
			var ipb_bg_toggle = String(back_image_toggle || '');
			if (ipb_bg_toggle !== 'no' && (back_image_toggle == 'yes' || ipb_bg_url_ok)) {

				back_img_position = (back_img_position && String(back_img_position).replace) ? String(back_img_position).replace(/-/g, ' ') : 'center center';
				jQuery($this).find(".instant-popup-content").css("background-image", "url('" + ipb_bg_url.replace(/'/g, "\\'") + "')");
				jQuery($this).find(".instant-popup-content").css("opacity", backimage_opacity);

				console.log(back_img_position);
				jQuery($this).find(".instant-popup-content").css("background-position", back_img_position);
				jQuery($this).find(".instant-popup-content").css("background-size", back_image_size);

			}

		// Popup width and height — skip for announcement bar (full-width strip; design tab sizes break layout)
		if (!isIpbAnnouncementBar) {
			// Popup width and height - Fixed Size Mode
			if (design_percentage_toggle == 'no' && (design_width > 0 || design_height > 0)) {

				if (design_width > 0) {
					jQuery($this).find(".instant-popup-content").css("width", design_width + 'px');
					jQuery($this).find(".instant-popup-content").css("max-width", "95vw"); // Responsive constraint
				}
				if (design_height > 0) {
					var $sizedPopup = jQuery($this).find(".instant-popup-content");
					var $sizedTextPopup = $sizedPopup.filter(".intant-popup-type-text");

					if ($sizedTextPopup.length) {
						// Text popups should hug their content. The configured height is
						// the point at which the content starts scrolling, not forced whitespace.
						var textPopupMaxHeight = Math.min(design_height, Math.floor(jQuery(window).height() * 0.88));
						$sizedTextPopup.css({
							"height": "auto",
							"max-height": textPopupMaxHeight + "px"
						});
						$sizedTextPopup.find(".inner_content").css({
							"max-height": Math.max(120, textPopupMaxHeight - text_padding_top - text_padding_bottom) + "px",
							"overflow-y": "auto"
						});
					} else {
						$sizedPopup.css("height", design_height + 'px');
					}
				}
			}

			// Popup width and height - Percentage Mode
			if (design_percentage_toggle == 'yes' && design_percentage > 0) {

				jQuery($this).find(".instant-popup-content").css("width", design_percentage + '%');
				jQuery($this).find(".instant-popup-content").css("max-width", design_percentage + '%');
				jQuery($this).find(".instant-popup-content").css("height", "auto"); // Auto height for responsive design
			}
		}

        // Text Popup Specific Styling (always applied with enhanced specificity)
        var $textPopup = jQuery($this).find(".intant-popup-type-text.instant-popup-content");

        // Only apply if text popup element exists
        if ($textPopup.length > 0) {
            // Apply custom padding with validation
            var paddingStyle = text_padding_top + 'px ' + text_padding_right + 'px ' + text_padding_bottom + 'px ' + text_padding_left + 'px';
            $textPopup.css("padding", paddingStyle);

            // Apply custom border radius with validation
            $textPopup.css("border-radius", text_border_radius + 'px');

            // Apply custom text color with validation
            $textPopup.css("color", text_color);

            // Apply custom font size ONLY to the container, not individual elements
            // This allows CSS clamp() functions to work for headings and other elements
            $textPopup.css("font-size", text_font_size + 'px');

            // Apply custom line height with validation
            $textPopup.css("line-height", text_line_height);

            // Add a class to indicate custom styling has been applied
            $textPopup.addClass('ipb-text-custom-styled');

			// Keep the close control clear of rich text without changing the
			// user's configured outer padding.
			var closePosition = String(close_positon || 'top-right');
			$textPopup.removeClass('ipb-close-at-left ipb-close-at-right');
			$textPopup.addClass(closePosition.indexOf('left') !== -1 ? 'ipb-close-at-left' : 'ipb-close-at-right');
        }

			// POpup animation

			// if (animate_type == 'fade-in') {

			// 	jQuery($this).find(".instant-popup-content").css("animation-name", 'fadeIn');
			// 	jQuery($this).find(".instant-popup-content").css("animation-duration", animate_speed+'s');

			// } else {

			// 	if (animate_origin == 'bottom') {

			// 		jQuery($this).find(".instant-popup-content").slideDown();
			// 	}
			// 	if (animate_origin == 'top') {

			// 		jQuery($this).find(".instant-popup-content").slideUp();
			// 	}
			// 	if (animate_origin == 'left') {

			// 		jQuery($this).find(".instant-popup-content").animate({
			// 			left: '50%'
			// 		});
			// 	}
			// 	if (animate_origin == 'right') {

			// 		jQuery($this).find(".instant-popup-content").animate({
			// 			right: '50%'
			// 		});
			// 	}
			// }

			// play audio

			function playAudio($this) {

				if ($this.find("#ipb_audioOpen")[0]) {
					// Check if audio is paused, to avoid multiple plays
					if ($this.find("#ipb_audioOpen")[0].paused) {
						$this.find("#ipb_audioOpen")[0].play()
							.then(function () {
								console.log('Audio started playing');
							})
							.catch(function (error) {
								console.error('Failed to play audio:', error);
							});
					}
				}

			}

			function playAudioClose($this) {
				var $audioClose = $this.find("#ipb_audioClose")[0]; // Get the DOM element

				if ($audioClose) {
					if ($audioClose.paused) {
					$audioClose.play()
						.then(function () {
						console.log('Close Audio started playing');
						})
						.catch(function (error) {
						console.error('Failed to play audio:', error);
						});
					}
				}
			}

			// if (limit_count == 0) {

			// 	// jQuery($this).fadeIn();
			// 	if (animate_type == 'fade-in') {

			// 		setTimeout(function(){

			// 			jQuery($this).fadeIn().css({
			// 				"animation-name": 'fadeIn',
			// 				"animation-duration": animate_speed + 's'
			// 			});

			// 		}, count*1000)
			// 	} else {

			// 		setTimeout(function(){

			// 			var $content = jQuery($this).find(".instant-popup-content");
			// 			jQuery($this).show();
			// 			if (animate_origin == 'bottom') {
			// 				$content.slideDown(animate_speed * 1000); // Ensure the duration is in milliseconds
			// 			}
			// 			if (animate_origin == 'top') {
			// 				$content.slideUp(animate_speed * 1000); // Ensure the duration is in milliseconds
			// 			}
			// 			if (animate_origin == 'left') {
			// 				$content.css({
			// 					'position': 'relative',
			// 					'left': '-100%' // Start position
			// 				}).animate({
			// 					left: '0%' // End position
			// 				}, animate_speed * 1000); // Ensure the duration is in milliseconds
			// 			}
			// 			if (animate_origin == 'right') {
			// 				$content.css({
			// 					'position': 'relative',
			// 					'right': '-100%' // Start position
			// 				}).animate({
			// 					right: '0%' // End position
			// 				}, animate_speed * 1000); // Ensure the duration is in milliseconds
			// 			}

			// 		}, count*1000)
			// 	}

			// 	playAudio(jQuery(this));
			// }
			// if (jQuery(this).data('limit-count') == '' && jQuery(this).data("delay") != '') {

			// 	setTimeout(function () {

			// 		jQuery($this).fadeIn();
			// 			playAudio(jQuery(this));

			// 	}, parseInt(jQuery(this).data("delay")) * 1000);
			// }
			setTimeout(function () {

				if (ipbIsStwSilentBlocked($this)) {
					return;
				}

				var ipbSkipShow = jQuery($this).data('ipb-skip-show');
				if (ipbSkipShow === 1 || ipbSkipShow === '1') {
					return;
				}

				if ((limit_count > views || limit_count == 0 || limit_count == '') && (popup_trigger == 'onload' && popup_trigger != 'scroll-trigger' && popup_trigger != 'woocommerce-trigger')) {

					// jQuery($this).fadeIn();
					// jQuery($this).fadeIn();
                    ///alert(popup_trigger);
					if(limit_count != 0 || limit_count != ''){

						views++;
						setCookie("popup_count"+id, views, 30);
						console.log(getCookie('popup_count'+id));

					}
					// console.log(limit_count+"hello");
					if (animate_type == 'none') {
						jQuery($this).show();
						playAudio($this);
					} else if (animate_type == 'fade-in') {
						jQuery($this).fadeIn().css({
							"animation-name": 'fadeIn',
							"animation-duration": animate_speed + 's'
						});
						playAudio($this);
					} else if (animate_type == 'scale') {
						var $content = jQuery($this).find(".instant-popup-content");
						$content.css({
							"animation-name": 'ipbZoomIn',
							"animation-duration": animate_speed + 's',
							"animation-fill-mode": 'forwards',
							"animation-timing-function": 'ease-out'
						});
						jQuery($this).fadeIn(0);
						playAudio($this);
					} else if (animate_type == 'reveal') {
						ipbCircularReveal(jQuery($this), animate_speed);
						playAudio($this);
					} else {
						var $content = jQuery($this).find(".instant-popup-content");
						jQuery($this).show();
						playAudio($this);
						if (animate_origin == 'bottom') {
							$content.slideDown(animate_speed * 1000);
						}
						if (animate_origin == 'top') {
							$content.slideUp(animate_speed * 1000);
						}
						if (animate_origin == 'left') {
							$content.css({
								'position': 'relative',
								'left': '-100%'
							}).animate({
								left: '0%'
							}, animate_speed * 1000);
						}
						if (animate_origin == 'right') {
							$content.css({
								'position': 'relative',
								'right': '-100%'
							}).animate({
								right: '0%'
							}, animate_speed * 1000);
						}
					}

					// limit_count = limit_count - 1;
					// Use popup-specific tracking instead of global flag
					var popupTrackingKey = 'ajaxCallTriggered_' + id;
					if (!window[popupTrackingKey]) {

						window[popupTrackingKey] = true; // Set popup-specific flag

						var formData = {
							action: 'instant_view_count',
							id: id,
							nonce: nonce
						};

						jQuery.ajax({
							type: "post",
							url: instant_ajax_handler.ajax_url,
							data: formData,
							success: function (response) {
								console.log('View tracked for popup ' + id + ':', response);
							},
							error: function(xhr, status, error) {
								console.error('Failed to track view for popup ' + id + ':', error);
								// Reset flag on error to allow retry
								window[popupTrackingKey] = false;
							},
							complete: function () {
								// Keep flag true to prevent duplicate tracking for same popup session
								// Only reset on page reload or if there's an error
							}
						});
					}
				}

				// limit_count = limit_count != 0 ?  limit_count -1 : 0;
				// localStorage.setItem('pop_count'+ id, limit_count);

				// if(localStorage.getItem('pop_count'+ id) > 0){

				// 	console.log(localStorage.getItem('pop_count'+ id));

				// }else{

				// 	jQuery($this).hide();

				// }

			}, ipbScheduleSeconds * 1000);
            // Global object to track shown state per popup ID
			let popupShownFlags = {};

			// Scroll Trigger Logic
			if (popup_trigger === 'scroll-trigger') {
				const popupId = jQuery($this).attr("id"); // Get unique popup ID

				if (!popupId) {
					console.warn("Popup element missing ID. Scroll trigger won't work.");
					return;
				}

				popupShownFlags[popupId] = false;

				// Get scroll trigger settings
				let scrollType = jQuery($this).data("scroll-type") || "distance"; // "distance" or "back_to_top"
				let scrollDistance = parseInt(jQuery($this).data("scroll-distance")) || 30;

				// Scroll listener per popup
				jQuery(window).on("scroll.instantPopup_" + popupId, function () {
					if (popupShownFlags[popupId]) return;

					let scrollTop = jQuery(window).scrollTop();
					let docHeight = jQuery(document).height();
					let winHeight = jQuery(window).height();

					if (scrollType === "distance") {
						let scrollPercent = (scrollTop / (docHeight - winHeight)) * 100;
						if (scrollPercent >= scrollDistance) {
							showPopup();
						}
					}

					if (scrollType === "back_to_top" && scrollTop === 0) {
						showPopup();
					}
				});

				function showPopup() {
					popupShownFlags[popupId] = true;

					if (ipbIsStwSilentBlocked($this)) {
						return;
					}

					var ipbSkipShowScroll = jQuery($this).data('ipb-skip-show');
					if (ipbSkipShowScroll === 1 || ipbSkipShowScroll === '1') {
						return;
					}

					if (limit_count != 0 || limit_count != '') {
						views++;
						setCookie("popup_count" + id, views, 30);
					}

					if (animate_type === 'none') {
						jQuery($this).show();
					} else if (animate_type === 'fade-in') {
						jQuery($this).fadeIn().css({
							"animation-name": 'fadeIn',
							"animation-duration": animate_speed + 's'
						});
					} else if (animate_type === 'scale') {
						let $content = jQuery($this).find(".instant-popup-content");
						$content.css({
							"animation-name": 'ipbZoomIn',
							"animation-duration": animate_speed + 's',
							"animation-fill-mode": 'forwards',
							"animation-timing-function": 'ease-out'
						});
						jQuery($this).fadeIn(0);
					} else if (animate_type === 'reveal') {
						ipbCircularReveal(jQuery($this), animate_speed);
					} else {
						let $content = jQuery($this).find(".instant-popup-content");
						jQuery($this).show();

						if (animate_origin === 'bottom') {
							$content.slideDown(animate_speed * 1000);
						} else if (animate_origin === 'top') {
							$content.slideUp(animate_speed * 1000);
						} else if (animate_origin === 'left') {
							$content.css({ 'position': 'relative', 'left': '-100%' })
								.animate({ left: '0%' }, animate_speed * 1000);
						} else if (animate_origin === 'right') {
							$content.css({ 'position': 'relative', 'right': '-100%' })
								.animate({ right: '0%' }, animate_speed * 1000);
						}
					}

					// AJAX View Count
					jQuery.ajax({
						type: "post",
						url: instant_ajax_handler.ajax_url,
						data: {
							action: 'instant_view_count',
							id: id,
							nonce: nonce
						},
						success: function (response) {
							console.log("Scroll Popup AJAX Response:", response);
						}
					});

					// Unbind scroll event for this popup
					jQuery(window).off("scroll.instantPopup_" + popupId);
				}
			}
			//WooCommerce Trigger

			if (popup_trigger === 'woocommerce-trigger') {

				const popupId = jQuery($this).attr("id"); // Get unique popup ID

				if (!popupId) {
					console.warn("Popup element missing ID. WooCommerce trigger won't work.");

					return;
				}

				// Get WooCommerce trigger settings and pass control to the extension
				const wooTrigger = jQuery($this).data('wooTrigger');
				const wooCondition = jQuery($this).data("wooCondition");

				function showPopup() {

					if (ipbIsStwSilentBlocked($this)) {
						return;
					}

					var ipbSkipShowWoo = jQuery($this).data('ipb-skip-show');
					if (ipbSkipShowWoo === 1 || ipbSkipShowWoo === '1') {
						return;
					}

					if (limit_count != 0 || limit_count != '') {
						views++;
						setCookie("popup_count" + id, views, 30);
					}

					if (animate_type === 'fade-in') {
						jQuery($this).fadeIn().css({
							"animation-name": 'fadeIn',
							"animation-duration": animate_speed + 's'
						});
					} else {
						let $content = jQuery($this).find(".instant-popup-content");
						jQuery($this).show();

						if (animate_origin === 'bottom') {
							$content.slideDown(animate_speed * 1000);
						} else if (animate_origin === 'top') {
							$content.slideUp(animate_speed * 1000);
						} else if (animate_origin === 'left') {
							$content.css({ 'position': 'relative', 'left': '-100%' })
								.animate({ left: '0%' }, animate_speed * 1000);
						} else if (animate_origin === 'right') {
							$content.css({ 'position': 'relative', 'right': '-100%' })
								.animate({ right: '0%' }, animate_speed * 1000);
						}
					}

					// AJAX View Count
					jQuery.ajax({
						type: "post",
						url: instant_ajax_handler.ajax_url,
						data: {
							action: 'instant_view_count',
							id: id,
							nonce: nonce
						},
						success: function (response) {
							console.log("WooCommerce Popup AJAX Response:", response);
						}
					});

					// Unbind event namespace if the extension used it
					jQuery(window).off("click.instantPopup_" + popupId);
				}

				const wooPayload = {
					popupId,
					wooTrigger,
					wooCondition,
					showPopup,
					popupEl: $this
				};

				// Queue the payload so late-loading listeners can still process it
				window.ipbWooQueue = window.ipbWooQueue || [];
				window.ipbWooQueue.push(wooPayload);

				// Dispatch event for listeners that are already registered
				window.dispatchEvent(new CustomEvent('ipbWooTriggerInit', { detail: wooPayload }));
			}
			if (ipbAttrIsYes(close_hide)) {

				jQuery($this).find(".instant-cross").hide();
			}

			// Close when clicking the dimmed backdrop (overlay), not deferred behind a stray document click.
			if (!isIpbAnnouncementBar && ipbAttrIsYes(close_outside)) {
				$popupRoot.find('.instant_overlay').on('click.ipbCloseOutside', function (e) {
					if (e.target !== this) {
						return;
					}
					e.preventDefault();
					$popupRoot.hide();
				});
			}
			if (!isIpbAnnouncementBar && ipbAttrIsYes(close_hover)) {

				jQuery($this).find(".instant-cross").hide();
				jQuery($this).find(".instant-popup-content").hover(
					function () {

					// jQuery($this).find(".instant-cross").toggleClass("pointer_class");
					jQuery($this).find(".instant-cross").fadeIn(200);
					// jQuery($this).find(".instant-cross").css("background-color","#eb8895")
				},
				function () {

					jQuery($this).find(".instant-cross").fadeOut(200);
					// jQuery($this).find(".instant-cross").css("background-color","#eb8895")
				}
			)
			}

			if (ipbAttrIsYes(close_escape)) {

				jQuery(document).keydown(function (event) {
					if (event.key === "Escape" || event.keyCode === 27) {
						console.log("Escape key pressed");
						jQuery($this).hide();
						// Perform your action here
					}
				});
			}
			// Close button position handling with data attribute for CSS
			if (close_positon != '' && close_positon != 'top-right') {
				var position = close_positon.split('-');
				var $closeBtn = jQuery($this).find(".instant-cross");
				
				// Set data attribute for CSS-based positioning (new approach)
				$closeBtn.attr('data-position', close_positon);
				
				// Also apply inline styles for backward compatibility with extensions
				// Reset all positions first
				$closeBtn.css({ top: 'auto', right: 'auto', bottom: 'auto', left: 'auto' });
				
				// Apply position based on value
				if (position[0] === 'top') {
					$closeBtn.css('top', '15px');
				} else if (position[0] === 'bottom') {
					$closeBtn.css('bottom', '15px');
				}
				
				if (position[1] === 'right') {
					$closeBtn.css('right', '15px');
				} else if (position[1] === 'left') {
					$closeBtn.css('left', '15px');
				}
			} else {
				// Sensible default for popups without an explicit close position
				jQuery($this).find(".instant-cross").css({ top: '15px', right: '15px' });
				jQuery($this).find(".instant-cross").attr('data-position', 'top-right');
			}

			// Popup position (modal overlay only — not announcement bar strip)
			if (!isIpbAnnouncementBar && popup_position != '') {

				var pos = popup_position.split('-');
				console.log(pos);
				jQuery($this).find(".instant_overlay").css('align-items', `${pos[0]}`);
				jQuery($this).find(".instant_overlay").css('justify-content', `${pos[1]}`);
			}

		// action
		if (action == 'yes') {

			jQuery($this).find(".instant-popup-content .inner_content").on("click", function (e) {
				e.preventDefault();

				// Track click event
				trackPopupClick(id, nonce);

				if (action_type === 'open_popup' && action_popup_id) {
					// Find the target popup
					var targetPopup = jQuery('.instant_popup-front[data-id="' + action_popup_id + '"]');

					if (targetPopup.length > 0) {
						// Target popup exists and is active
						// Close current popup
						jQuery($this).hide();
						// Show target popup
						targetPopup.show();
					} else {
						// Target popup not found (might be inactive, deleted, or not published)
						console.warn('IPB: Target popup (ID: ' + action_popup_id + ') is not available. It may be inactive, deleted, or not published.');
						// Keep current popup open as fallback
						// Optionally, you could close it: jQuery($this).hide();
					}
				} else if (action_type === 'redirect' || !action_type) {
					// Track conversion for redirect actions (user clicked and is being redirected)
					if (id) {
						trackConversion(id, 'redirect');
					}

					var target = action_tab == 'yes' ? '_blank' : '_self';
					var redirectDelaySeconds = (typeof redirect_delay_seconds_attr !== 'undefined' && redirect_delay_seconds_attr !== '' && redirect_delay_seconds_attr !== null) ? parseInt(redirect_delay_seconds_attr, 10) : ((typeof instant_ajax_handler !== 'undefined' && instant_ajax_handler.redirect_delay_seconds !== undefined) ? parseInt(instant_ajax_handler.redirect_delay_seconds, 10) : 0);
					if (isNaN(redirectDelaySeconds) || redirectDelaySeconds < 0) redirectDelaySeconds = 0;

					if (redirectDelaySeconds === 0) {
						window.open(action_url, target);
					} else {
						var redirectDelayMs = redirectDelaySeconds * 1000;
						var redirectMessage = (typeof instant_ajax_handler !== 'undefined' && instant_ajax_handler.redirect_message) ? instant_ajax_handler.redirect_message : 'You will be redirected to the link below.';
						var redirectDisplayUrl = action_url;
						try {
							var u = new URL(action_url);
							redirectDisplayUrl = u.hostname + (u.pathname !== '/' ? u.pathname : '');
						} catch (err) {}

						var $contentWrap = jQuery($this).find(".instant-popup-content .inner_content");
						var originalContent = $contentWrap.length ? $contentWrap.html() : '';
						$contentWrap.html(
							'<div class="ipb-redirect-message" style="text-align:center;padding:24px 20px;">' +
							'<p style="margin:0 0 12px;font-size:16px;line-height:1.5;">' + redirectMessage + '</p>' +
							'<p class="ipb-redirect-url" style="margin:0 0 16px;font-size:14px;color:#666;word-break:break-all;">' + redirectDisplayUrl + '</p>' +
							'<p class="ipb-redirect-countdown" style="margin:0;font-size:15px;font-weight:600;">' + redirectDelaySeconds + '</p>' +
							'</div>'
						);

						var count = redirectDelaySeconds;
						var countdownEl = jQuery($this).find(".ipb-redirect-countdown");
						var countdownInterval = setInterval(function () {
							count--;
							if (countdownEl.length) countdownEl.text(count > 0 ? count : '');
							if (count <= 0) {
								clearInterval(countdownInterval);
								window.open(action_url, target);
								if (target === '_self') {
									if ($contentWrap.length && originalContent) $contentWrap.html(originalContent);
								}
							}
						}, 1000);

						setTimeout(function () {
							clearInterval(countdownInterval);
							window.open(action_url, target);
							if ($contentWrap.length && originalContent) $contentWrap.html(originalContent);
						}, redirectDelayMs);
					}
				}
			})

		}

			// on click trigger
			if (popup_class != '' && popup_trigger == 'onclick') {

				jQuery(document).find(`.${popup_class}`).on("click", function (e) {

					e.preventDefault();
					if (jQuery($this).data('click') == popup_class) {

						if (ipbIsStwSilentBlocked($this)) {
							return;
						}

						if(limit_count !=0 || limit_count !=''){

							views++;
							setCookie("popup_count"+id, views, 30);
							console.log(getCookie('popup_count'+id));
							// var id = jQuery($this).attr("id");
						}
						// console.log(id);
						// console.log($this);
						// jQuery(document).find(`#${id}`).fadeIn();

						// jQuery($this).fadeIn();
						// jQuery($this).fadeIn();
						if (animate_type == 'fade-in') {
							jQuery($this).fadeIn().css({
								"animation-name": 'fadeIn',
								"animation-duration": animate_speed + 's'
							});
							playAudio($this);

						} else {

							var $content = jQuery($this).find(".instant-popup-content");
							jQuery($this).show();
							playAudio($this);
							if (animate_origin == 'bottom') {
								$content.slideDown(animate_speed * 1000); // Ensure the duration is in milliseconds
							}
							if (animate_origin == 'top') {
								$content.slideUp(animate_speed * 1000); // Ensure the duration is in milliseconds
							}
							if (animate_origin == 'left') {
								$content.css({
									'position': 'relative',
									'left': '-100%' // Start position
								}).animate({
									left: '0%' // End position
								}, animate_speed * 1000); // Ensure the duration is in milliseconds
							}
							if (animate_origin == 'right') {
								$content.css({
									'position': 'relative',
									'right': '-100%' // Start position
								}).animate({
									right: '0%' // End position
								}, animate_speed * 1000); // Ensure the duration is in milliseconds
							}
							playAudio($this);

						}
						// playAudio(jQuery(this));

						// limit_count = limit_count - 1;
						// Use popup-specific tracking instead of global flag
						var popupTrackingKey = 'ajaxCallTriggered_' + id;
						if (!window[popupTrackingKey]) {

							window[popupTrackingKey] = true; // Set popup-specific flag

							var formData = {
								action: 'instant_view_count',
								id: id,
								nonce: nonce
							};

							jQuery.ajax({
								type: "post",
								url: instant_ajax_handler.ajax_url,
								data: formData,
								success: function (response) {
									console.log('View tracked for popup ' + id + ':', response);
								},
								error: function(xhr, status, error) {
									console.error('Failed to track view for popup ' + id + ':', error);
									// Reset flag on error to allow retry
									window[popupTrackingKey] = false;
								},
								complete: function () {
									// Keep flag true to prevent duplicate tracking for same popup session
									// Only reset on page reload or if there's an error
								}
							});
						}

					}

				})
			}

			// on hover trigger

			if (popup_hover != '' && popup_trigger == 'onhover') {
				jQuery(document).find(`.${popup_hover}`).hover(function (e) {

					e.preventDefault();

					if (jQuery($this).data('hover') == popup_hover) {

						if (ipbIsStwSilentBlocked($this)) {
							return;
						}

						if(limit_count !== 0 || limit_count !== ''){

							views++;
							setCookie("popup_count"+id, views, 30);
							console.log(getCookie('popup_count'+id));
							// playAudio(jQuery(this));

						}
						console.log(popup_hover);
						if (animate_type == 'fade-in') {
							jQuery($this).fadeIn().css({
								"animation-name": 'fadeIn',
								"animation-duration": animate_speed + 's'
							});
							playAudio($this);

						} else {

							var $content = jQuery($this).find(".instant-popup-content");
							jQuery($this).show();
							playAudio($this);
							if (animate_origin == 'bottom') {
								$content.slideDown(animate_speed * 1000); // Ensure the duration is in milliseconds
							}
							if (animate_origin == 'top') {
								$content.slideUp(animate_speed * 1000); // Ensure the duration is in milliseconds
							}
							if (animate_origin == 'left') {
								$content.css({
									'position': 'relative',
									'left': '-100%' // Start position
								}).animate({
									left: '0%' // End position
								}, animate_speed * 1000); // Ensure the duration is in milliseconds
							}
							if (animate_origin == 'right') {
								$content.css({
									'position': 'relative',
									'right': '-100%' // Start position
								}).animate({
									right: '0%' // End position
								}, animate_speed * 1000); // Ensure the duration is in milliseconds
							}

						}

						playAudio($this);

						// Use popup-specific tracking instead of global flag
						var popupTrackingKey = 'ajaxCallTriggered_' + id;
						if (!window[popupTrackingKey]) {

							window[popupTrackingKey] = true; // Set popup-specific flag

							var formData = {
								action: 'instant_view_count',
								id: id,
								nonce: nonce
							};

							jQuery.ajax({
								type: "post",
								url: instant_ajax_handler.ajax_url,
								data: formData,
								success: function (response) {
									console.log('View tracked for popup ' + id + ':', response);
								},
								error: function(xhr, status, error) {
									console.error('Failed to track view for popup ' + id + ':', error);
									// Reset flag on error to allow retry
									window[popupTrackingKey] = false;
								},
								complete: function () {
									// Keep flag true to prevent duplicate tracking for same popup session
									// Only reset on page reload or if there's an error
								}
							});
						}
					}

				})
			}

			// Exit intent detection is now handled by the exit intent extension
			
			/**
			 * Close button click handler
			 * Centralized handler for all popup close buttons
			 * Maintains backward compatibility with extensions
			 */
			jQuery(document).on("click", ".instant-cross", function (e) {
				e.preventDefault();
				IPB_CloseManager.close(jQuery(this));
			});

			/**
			 * Close button keyboard handler for accessibility
			 * Allows closing popups with Enter or Space key when close button is focused
			 */
			jQuery(document).on("keydown", ".instant-cross", function (e) {
				// Handle Enter (13) or Space (32) key
				if (e.key === "Enter" || e.key === " " || e.keyCode === 13 || e.keyCode === 32) {
					e.preventDefault();
					IPB_CloseManager.close(jQuery(this));
				}
			})

			// Track clicks on popup content (general click tracking)
			jQuery(document).on("click", ".instant_popup-front .instant-popup-content", function (e) {
				var popupId = jQuery(this).closest(".instant_popup-front").data("form-id");
				var nonce = instant_ajax_handler.view_count;

				// Only track if it's not a close button or action button
				if (!jQuery(e.target).hasClass('instant-cross') &&
					!jQuery(e.target).closest('.instant-cross').length &&
					!jQuery(e.target).closest('.inner_content').length &&
					popupId && nonce) {
					trackPopupClick(popupId, nonce);
				}
			})
		});

		// var option = instant_ajax_handler.trigger_option;
		// console.log(option);
		// var trigger_class, trigger_delay, trigger_option;
		// var count= 0;
		// $.each(option, function (key, value) {

		// 	var trigger_id;
		// 	console.log(value);
		// 	$.each(value, function (key, value) {

		// 		if (key == 1) {

		// 			trigger_id = value;

		// 		}
		// 		else {

		// 			if (value?.trigger_class) {

		// 				trigger_class = value.trigger_class;
		// 			}
		// 			if (value?.trigger_option) {

		// 				trigger_option = value.trigger_option;
		// 			}
		// 			if (value?.trigger_delay) {

		// 				trigger_delay = value.trigger_delay;
		// 			}
		// 		}

		// 	})

		// 	for (var i = 0; i < trigger_option.length; i++) {

		// 		if (trigger_option[i] == "onload") {

		// 			count = count + parseInt(trigger_delay[i]) * 1000;
		// 			setTimeout(function () {

		// 				$(document).find(`#instant-${trigger_id}`).fadeIn();

		// 			}, count)
		// 			// clearTimeout(interval);

		// 		}

		// 		if (trigger_option[i] == "onclick") {

		// 			$(document).find(".instant-popup-trigger").on("click", function (e) {
		// 				e.preventDedault();
		// 				$(document).find(`#instant-${trigger_id}`).fadeIn();
		// 			})

		// 		}

		// 		if (trigger_option[i] == "hover") {

		// 			$(document).find(".instant-popup-trigger").hover(function (e) {
		// 				e.preventDedault();
		// 				$(document).find(`#instant-${trigger_id}`).fadeIn();
		// 			})
		// 		}
		// 	}

		// });

		// console.log(trigger_option);
		// console.log(trigger_id);
		// console.log(trigger_option);

		// for (let i = 0; i < trigger_option.length; i++) {

		// 	if (trigger_option[i] == "onload") {

		// 		setTimeout(function () {

		// 			$(document).find(`#instant-${trigger_id[i]}`).fadeIn();
		// 			console.log("hello");

		// 		}, parseInt(trigger_delay[i]) * 1000)
		// 	}

		// 	if (trigger_option[i] == "onclick") {

		// 		$(document).find(".instant-popup-trigger").on("click", function (e) {
		// 			e.preventDedault();
		// 			alert("hello world");
		// 		})

		// 	}
		// }

	})

	/**
	 * IPB Close Manager
	 * 
	 * Centralized close functionality for all popup types.
	 * Provides a unified API for closing popups with proper tracking and audio.
	 * Extensions can hook into this by listening to the 'ipb:popup:close' event.
	 * 
	 * @since 1.0.0
	 */
	var IPB_CloseManager = {
		/**
		 * Close a popup
		 * 
		 * @param {jQuery} $closeBtn - The close button element that was clicked
		 * @param {Object} options - Optional configuration
		 * @param {boolean} options.trackClick - Whether to track the click (default: true)
		 * @param {boolean} options.playAudio - Whether to play close audio (default: true)
		 * @param {string} options.animation - Animation type: 'fadeOut', 'hide', 'slideUp' (default: 'fadeOut')
		 */
		close: function($closeBtn, options) {
			options = jQuery.extend({
				trackClick: true,
				playAudio: true,
				animation: 'fadeOut'
			}, options || {});

			var $popup = $closeBtn.closest(".instant_popup-front");
			
			if ($popup.length === 0) {
				console.warn('IPB CloseManager: Could not find parent popup element');
				return;
			}

			var popupId = $popup.data("form-id");
			var nonce = typeof instant_ajax_handler !== 'undefined' ? instant_ajax_handler.view_count : null;

			// Track close click event (backward compatible)
			if (options.trackClick && popupId && nonce) {
				if (typeof trackPopupClick === 'function') {
					trackPopupClick(popupId, nonce);
				}
			}

			// Trigger custom event for extensions to hook into
			// Extensions can prevent default close by calling e.preventDefault()
			var closeEvent = jQuery.Event('ipb:popup:close');
			closeEvent.popupId = popupId;
			closeEvent.popup = $popup;
			closeEvent.closeButton = $closeBtn;
			$popup.trigger(closeEvent);

			if (closeEvent.isDefaultPrevented()) {
				return; // Extension prevented the close
			}

			// Perform the close animation
			switch (options.animation) {
				case 'hide':
					$popup.hide();
					break;
				case 'slideUp':
					$popup.slideUp(300);
					break;
				case 'fadeOut':
				default:
					$popup.fadeOut(300);
					break;
			}

			// Play close audio
			if (options.playAudio) {
				if (typeof playAudioClose === 'function') {
					playAudioClose($closeBtn);
				}
			}

			// Trigger after-close event for extensions
			$popup.trigger('ipb:popup:closed', [popupId]);
		},

		/**
		 * Close a popup by its ID
		 * 
		 * @param {string|number} popupId - The popup ID
		 * @param {Object} options - Optional configuration (same as close method)
		 */
		closeById: function(popupId, options) {
			var $popup = jQuery('.instant_popup-front[data-form-id="' + popupId + '"]');
			if ($popup.length > 0) {
				var $closeBtn = $popup.find('.instant-cross');
				this.close($closeBtn.length > 0 ? $closeBtn : $popup, options);
			}
		}
	};

	// Make IPB_CloseManager available globally for extensions
	window.IPB_CloseManager = IPB_CloseManager;

	// Function to set a cookie
	function setCookie(name, value, days) {
		let expires = "";
		if (days) {
			let date = new Date();
			date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
			expires = "; expires=" + date.toUTCString();
		}
		document.cookie = name + "=" + value + "; path=/" + expires;
	}

	// Function to get a cookie
	function getCookie(name) {
		let nameEQ = name + "=";
		let ca = document.cookie.split(';');
		for (let i = 0; i < ca.length; i++) {
			let c = ca[i];
			while (c.charAt(0) === ' ') c = c.substring(1, c.length);
			if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
		}
		return null;
	}

	// Make cookie functions available globally for extensions
	window.IPB_setCookie = setCookie;
	window.IPB_getCookie = getCookie;

	jQuery(document).ready(function () {
		// Check if user is already subscribed before showing popup
		checkSubscriptionStatus();
		jQuery('#subscription_form button').on('click', function() {
			var $form = jQuery(this).closest('#subscription_form');
			var popupid = jQuery(this).closest('.instant_popup-front').attr('data-form-id');
			$form.find('[name="campaign"]').val(popupid);
		});

	});

jQuery(document).on("submit", "#subscription_form", function (e) {
		e.preventDefault(); // Prevent default form submission

		// Form submission started

		// Show loading state
		var $submitBtn = $(this).find('button[type="submit"]');
		var originalText = $submitBtn.text();
		$submitBtn.prop('disabled', true).text('Subscribing...');

		var formData = $(this).serialize(); // Serialize form data

		//console.log('Form data being sent:', formData);
		//console.log('AJAX URL:', instnat_ajax_subscriber.ajaxurl);
		//console.log(formData);
		$.ajax({
			type: "POST",
			url: instnat_ajax_subscriber.ajax_url, // WordPress AJAX URL
			data: formData,
			dataType: "json",
			success: function (response) {
				//console.log('AJAX Success Response:', response);

				// Reset button state
				$submitBtn.prop('disabled', false).text(originalText);

				if (response.success) {
					// Handle wp_send_json_success format
					var message = response.data || response.message || 'Thank you for subscribing!';
					jQuery("#subscription_form .message").show();
					jQuery("#subscription_form .message").html("<p style='color: green;font-weight: bold;font-size: 18px;'>" + message + "</p>");

					// Store email in localStorage for future subscription checks
					var email = jQuery("#subscription_form input[name='email_address']").val();
					var submit_popup_id = jQuery("#subscription_form input[name='campaign']").val();
					if (email) {
						let existingEmails = localStorage.getItem('ipb_user_email');
						let items = existingEmails ? JSON.parse(existingEmails) : [];

						if (!items.includes(email)) {
							items.push(email);
						}

						localStorage.setItem('ipb_user_email', JSON.stringify(items));
					}
					if (submit_popup_id) {

						let existingPopupID = localStorage.getItem('ipb_subscribe_id');
						let items_ids = existingPopupID ? JSON.parse(existingPopupID) : [];

						if (!items_ids.includes(submit_popup_id)) {
							items_ids.push(submit_popup_id);
						}

						localStorage.setItem('ipb_subscribe_id', JSON.stringify(items_ids));
						//localStorage.setItem('ipb_subscribe_id', submit_popup_id);
					}

					// Track conversion event when subscription is successful
					// Works with both basic subscription and Subscription Pro extension
					if (submit_popup_id) {
						trackConversion(submit_popup_id, 'subscription');
					}

					// Trigger custom event for extensions (like Subscription Pro) to hook into
					// Extensions can listen to this event: jQuery(document).on('ipb:subscription:success', function(e, popupId) { ... });
					jQuery(document).trigger('ipb:subscription:success', [submit_popup_id]);

					// Clear form fields on success
					jQuery("#subscription_form")[0].reset();

					setTimeout(function(){
						jQuery(document).find(".instant_popup-front").hide();
					}, 4000);
				}
				else {
					// Handle wp_send_json_error format
					var errorMessage = response.data || response.message || 'An error occurred';
					jQuery("#subscription_form .message").show();
					jQuery("#subscription_form .message").html("<p style='color:red;font-weight: bold;font-size: 18px;'>" + errorMessage + "</p>");
				}
			},
			error: function (xhr, status, error) {
				console.error('AJAX Error:', {
					xhr: xhr,
					status: status,
					error: error,
					responseText: xhr.responseText
				});

				// Reset button state
				$submitBtn.prop('disabled', false).text(originalText);

				var errorMessage = "An error occurred while processing your subscription.";

				// Try to parse error response
				if (xhr.responseText) {
					try {
						var errorResponse = JSON.parse(xhr.responseText);
						if (errorResponse.data) {
							errorMessage = errorResponse.data;
						} else if (errorResponse.message) {
							errorMessage = errorResponse.message;
						}
					} catch (e) {
						// If JSON parsing fails, check if it's a plain text response
						// Error response received
						if (xhr.responseText.indexOf('Unauthorized') !== -1) {
							errorMessage = "Unauthorized: Please check your permissions.";
						} else {
							errorMessage = "Server Error (" + xhr.status + "): " + (error || "Unknown error");
						}
					}
				}
				jQuery("#subscription_form .message").show();
				jQuery("#subscription_form .message").html("<p style='color:red;font-weight: bold;font-size: 16px;'>" + errorMessage + "</p>");
			}
		});
	});
	/**
	 * Check if user is already subscribed
	 */
	function checkSubscriptionStatus() {
		// Get user's email from localStorage or prompt
		var userEmail = localStorage.getItem('ipb_user_email');
		var subscribeID = localStorage.getItem('ipb_subscribe_id');
		let existingEmails = localStorage.getItem('ipb_user_email');
		let items = existingEmails ? JSON.parse(existingEmails) : [];
        let subscribeID_item = subscribeID ? JSON.parse(subscribeID) : [];
		items.forEach(email => {
			if(email !== null){
              subscribeID_item.forEach( popupID =>{
               $('#instant-'+popupID).remove();
			  });
			}
		});

		if (!userEmail) {
			// Try to get email from any existing form on the page
			var $emailField = $('input[type="email"]').first();
			if ($emailField.length > 0) {
				userEmail = $emailField.val();
			}
		}

		if (userEmail && typeof instnat_ajax_subscriber !== 'undefined') {
			$.ajax({
				type: "POST",
				url: instnat_ajax_subscriber.ajaxurl,
				data: {
					action: 'instant_popup_check_subscription',
					email: userEmail,
					nonce: instnat_ajax_subscriber.subscription_check_nonce
				},
				dataType: "json",
				success: function (response) {
					if (response.success && response.data.subscribed) {
						// Check if prevent_reshow is enabled for this popup
						if (response.data.prevent_reshow) {
							// User is already subscribed and prevent_reshow is enabled, hide all subscription popups
							$('#instant-'+subscribeID).hide();
							// User already subscribed, hiding popups
						}
						// If prevent_reshow is disabled, popup will still show even if user is subscribed
					}
				},
				error: function (xhr, status, error) {
					console.error('Subscription check failed:', error);
				}
			});
		}
	}

	/**
	 * Track conversion events (subscription, redirect, etc.)
	 *
	 * @param {string|number} popupId - The popup ID
	 * @param {string} conversionType - Type of conversion (subscription, redirect, etc.)
	 */
	function trackConversion(popupId, conversionType) {
		if (!popupId || typeof instant_ajax_handler === 'undefined' || !instant_ajax_handler.view_count) {
			console.warn('Missing popup ID or nonce for conversion tracking');
			return;
		}

		var conversionFormData = {
			action: 'instant_conversion_count',
			id: popupId,
			nonce: instant_ajax_handler.view_count,
			conversion_type: conversionType || 'subscription'
		};

		jQuery.ajax({
			type: "post",
			url: instant_ajax_handler.ajax_url,
			data: conversionFormData,
			success: function (conversionResponse) {
				console.log('Conversion tracked for popup ' + popupId + ':', conversionResponse);
			},
			error: function(xhr, status, error) {
				console.error('Failed to track conversion for popup ' + popupId + ':', error);
			}
		});
	}

	// Make trackConversion available globally for extensions (like Subscription Pro)
	window.IPB_trackConversion = trackConversion;

	/**
	 * Track popup click events
	 *
	 * @param {string} popupId - The popup ID
	 * @param {string} nonce - The nonce for security
	 */
	function trackPopupClick(popupId, nonce) {
		if (!popupId || !nonce) {
			console.warn('Missing popup ID or nonce for click tracking');
			return;
		}

		// Use popup-specific tracking to prevent duplicate clicks
		var popupClickKey = 'clickTracked_' + popupId;
		if (window[popupClickKey]) {
			return; // Already tracked for this session
		}

		window[popupClickKey] = true;

		var formData = {
			action: 'instant_click_count',
			id: popupId,
			nonce: nonce
		};

		jQuery.ajax({
			type: "post",
			url: instant_ajax_handler.ajax_url,
			data: formData,
			success: function (response) {
				console.log('Click tracked for popup ' + popupId + ':', response);
			},
			error: function(xhr, status, error) {
				console.error('Failed to track click for popup ' + popupId + ':', error);
				// Reset flag on error to allow retry
				window[popupClickKey] = false;
			}
		});
	}
})(jQuery);

// document.addEventListener("DOMContentLoaded", function () {
//     let popupCount = getCookie("popup_count") || 0;

//     if (popupCount < 10) {
//         showPopup(); // Function to display the popup
//         popupCount++;
//         setCookie("popup_count", popupCount, 30); // Store for 30 days
//     }
// });

/**
 * Instant Popup Builder - Extension API
 *
 * This API allows extensions to trigger popups programmatically.
 * Extensions should use this API instead of directly manipulating popup elements.
 */
(function() {
	'use strict';

	// Wait for DOM to be ready
	jQuery(document).ready(function() {

		/**
		 * Display a popup by its ID
		 *
		 * @param {string|number} popupId - The popup ID (from data-form-id attribute)
		 * @param {object} options - Optional settings
		 * @returns {boolean} - Returns true if popup was shown, false otherwise
		 */
		window.IPB_ExtensionAPI = window.IPB_ExtensionAPI || {};

		window.IPB_ExtensionAPI.triggerPopup = function(popupId, options) {
			options = options || {};

			// Find the popup element
			var $popup = jQuery('.instant_popup-front[data-form-id="' + popupId + '"]');

			if ($popup.length === 0) {
				console.warn('IPB Extension API: Popup with ID "' + popupId + '" not found.');
				return false;
			}

			if (typeof window.ipbIsStwSilentBlocked === 'function' && window.ipbIsStwSilentBlocked($popup)) {
				return false;
			}

			// Get popup settings
			var id = $popup.data("form-id");
			var limit_count = $popup.data('limit-count') ? parseInt($popup.data('limit-count')) : 0;

			// Use global cookie functions
			var getCookieFunc = typeof window.IPB_getCookie === 'function' ? window.IPB_getCookie : getCookie;
			var setCookieFunc = typeof window.IPB_setCookie === 'function' ? window.IPB_setCookie : setCookie;

			var views = parseInt(getCookieFunc("popup_count" + id)) || 0;
			var animate_type = $popup.data('animate_type');
			var animate_speed = parseInt($popup.data('animate_speed')) / 100;
			var animate_origin = $popup.data('animate_origin');
			var nonce = typeof instant_ajax_handler !== 'undefined' ? instant_ajax_handler.view_count : '';

			// Check view limit (unless bypassed in options)
			if (!options.bypassLimit && limit_count > 0 && views >= limit_count) {
				console.log('IPB Extension API: Popup view limit reached for popup ' + popupId);
				return false;
			}

			// Increment view count if limit is set
			if (limit_count > 0 && !options.skipViewTracking) {
				views++;
				setCookieFunc("popup_count" + id, views, 30);
			}

			// Get audio element
			var $audioOpen = $popup.find("#ipb_audioOpen")[0];

			// Play audio
			function playAudio($this) {
				if ($this.find("#ipb_audioOpen")[0]) {
					if ($this.find("#ipb_audioOpen")[0].paused) {
						$this.find("#ipb_audioOpen")[0].play()
							.then(function () {
								console.log('Audio started playing');
							})
							.catch(function (error) {
								console.error('Failed to play audio:', error);
							});
					}
				}
			}

			// Display popup with animation
			if (animate_type == 'fade-in') {
				$popup.fadeIn().css({
					"animation-name": 'fadeIn',
					"animation-duration": animate_speed + 's'
				});
				playAudio($popup);
			} else {
				var $content = $popup.find(".instant-popup-content");
				$popup.show();
				playAudio($popup);

				if (animate_origin == 'bottom') {
					$content.slideDown(animate_speed * 1000);
				} else if (animate_origin == 'top') {
					$content.slideUp(animate_speed * 1000);
				} else if (animate_origin == 'left') {
					$content.css({
						'position': 'relative',
						'left': '-100%'
					}).animate({
						left: '0%'
					}, animate_speed * 1000);
				} else if (animate_origin == 'right') {
					$content.css({
						'position': 'relative',
						'right': '-100%'
					}).animate({
						right: '0%'
					}, animate_speed * 1000);
				}
			}

			// Track view (unless skipped)
			if (!options.skipViewTracking && nonce) {
				var popupTrackingKey = 'ajaxCallTriggered_' + id;
				if (!window[popupTrackingKey]) {
					window[popupTrackingKey] = true;

					var formData = {
						action: 'instant_view_count',
						id: id,
						nonce: nonce
					};

					jQuery.ajax({
						type: "post",
						url: instant_ajax_handler.ajax_url,
						data: formData,
						success: function (response) {
							console.log('View tracked for popup ' + id + ':', response);
						},
						error: function(xhr, status, error) {
							console.error('Failed to track view for popup ' + id + ':', error);
							window[popupTrackingKey] = false;
						}
					});
				}
			}

			return true;
		};

		/**
		 * Get popup element by ID
		 *
		 * @param {string|number} popupId - The popup ID
		 * @returns {jQuery} - jQuery object of the popup element
		 */
		window.IPB_ExtensionAPI.getPopup = function(popupId) {
			return jQuery('.instant_popup-front[data-form-id="' + popupId + '"]');
		};

		/**
		 * Get popup data attribute value
		 *
		 * @param {string|number} popupId - The popup ID
		 * @param {string} attribute - The data attribute name (without 'data-' prefix)
		 * @returns {*} - The attribute value
		 */
		window.IPB_ExtensionAPI.getPopupData = function(popupId, attribute) {
			var $popup = this.getPopup(popupId);
			if ($popup.length === 0) {
				return null;
			}
			return $popup.data(attribute);
		};

		// Dispatch event that extensions can listen to
		jQuery(document).trigger('ipb:api:ready');

		// Also make API available immediately (in case event listener hasn't been set up yet)
		console.log('IPB Extension API: Ready');
	});
})();
