(function( $ ) {
	'use strict';

	/**
	 * Debug logging function that only logs when debug is enabled
	 * @param {...any} args - Arguments to log
	 */
	function pinnerpressDebugLog() {
		if (typeof pinnerpressVars !== 'undefined' && pinnerpressVars.debug_enabled) {
			console.log.apply(console, arguments);
		}
	}

	/**
	 * Track if initialization has already been completed
	 */
	var pinnerpressInitialized = false;
	var pinnerpressUpdateTimeout = null;
	var pinnerpressIsUpdating = false;

	/**
	 * All of the code for your admin-facing JavaScript source
	 * should reside in this file.
	 */

	$(function() {
		// Prevent multiple initializations
		if (pinnerpressInitialized) {
			return;
		}
		pinnerpressInitialized = true;

		// Initialize color pickers
		if ($.fn.wpColorPicker) {
			// Initialize each color picker individually
			initializeColorPicker('.pinnerpress-hover-button-color-picker', '#E60023');
			initializeColorPicker('.pinnerpress-hover-button-text-color-picker', '#FFFFFF');
			initializeColorPicker('.pinnerpress-follow-button-bg-color-picker', '#E60023');
			initializeColorPicker('.pinnerpress-follow-button-text-color-picker', '#FFFFFF');
			initializeColorPicker('.pinnerpress-banner-text-color-picker', '#BD081C');
			initializeColorPicker('.pinnerpress-button-color-picker', '#E60023');
			initializeColorPicker('.pinnerpress-button-text-color-picker', '#FFFFFF');
			
			// Follow Button Default color pickers (General tab)
			initializeColorPicker('.pinnerpress-follow-button-default-color-picker', '#E60023');
			initializeColorPicker('.pinnerpress-follow-button-default-text-color-picker', '#FFFFFF');
			
			// Call Out Banner color pickers
			initializeColorPicker('.pinnerpress-call-out-bg-color-picker', '#E60023');
			initializeColorPicker('.pinnerpress-call-out-border-color-picker', '#E60023');
			initializeColorPicker('.pinnerpress-call-out-text-color-picker', '#FFFFFF');
			initializeColorPicker('.pinnerpress-call-out-button-bg-color-picker', '#FFFFFF');
			initializeColorPicker('.pinnerpress-call-out-button-text-color-picker', '#E60023');
			
			// Special case for banner background which has alpha channel
			initializeColorPicker('.pinnerpress-banner-bg-color-picker', 'rgba(255, 255, 255, 0.5)', true);
		}
		
		// Initialize media uploader
		initMediaUploader();
		
		// Initialize form fields and add event listeners
		initializeFormFields();
		
		// Add all event listeners (consolidated)
		addEventListeners();
		
		// Initialize hidden images functionality only if enabled and user is premium
		if (pinnerpressVars.hiddenPinsEnabled && pinnerpressVars.isPremium) {
			initHiddenImages();
		}
		
		// Initial preview update (only once, with delay to ensure everything is initialized)
		setTimeout(function() {
			updatePreview();
		}, 500);

		/**
		 * Initialize a color picker with specific settings
		 * 
		 * @param {string} selector  CSS selector for the color picker
		 * @param {string} defaultColor  Default color value
		 * @param {boolean} hasAlpha  Whether this picker supports alpha channel
		 */
		function initializeColorPicker(selector, defaultColor, hasAlpha) {
			var $colorPicker = $(selector);
			
			if (!$colorPicker.length) {
				return;
			}
			
			// Skip initialization if the color picker is disabled (for free users)
			if ($colorPicker.prop('disabled') || $colorPicker.closest('.pinnerpress-disabled-feature').length) {
				return;
			}
			
			// Make sure we never use an empty value - use the default if value is empty or not set
			var currentValue = $colorPicker.val();
			if (!currentValue || currentValue === '' || currentValue === 'undefined') {
				currentValue = defaultColor;
				// Set the value to default to ensure it's visible in the input field
				$colorPicker.val(defaultColor);
			}
			
			var options = {
				defaultColor: defaultColor,
				color: currentValue,
				change: function(event, ui) {
					// Use debounced update to prevent multiple rapid calls
					debouncedUpdatePreview();
				},
				clear: function() {
					// Use debounced update to prevent multiple rapid calls
					debouncedUpdatePreview();
				}
			};
			
			// Add alpha support if needed
			if (hasAlpha === true) {
				options.palettes = true;
				options.alpha = true;
			}
			
			$colorPicker.wpColorPicker(options);
		}
		
		// Debounced update function to prevent multiple rapid calls
		function debouncedUpdatePreview() {
			// Clear any existing timeout
			if (pinnerpressUpdateTimeout) {
				clearTimeout(pinnerpressUpdateTimeout);
			}
			
			// Set a new timeout
			pinnerpressUpdateTimeout = setTimeout(function() {
				updatePreview();
			}, 150);
		}
		
		// Toggle dependent fields visibility
		$('input[name="pinnerpress_enable_rich_pins"]').on('change', function() {
			var $richPinOptions = $('.pinnerpress-rich-pin-types');
			
			if ($(this).is(':checked')) {
				$richPinOptions.slideDown();
			} else {
				$richPinOptions.slideUp();
			}
		}).trigger('change');
		
		// Pin Button Preview Updates
		function updatePinButtonPreview() {
			// Prevent multiple simultaneous updates
			if (pinnerpressIsUpdating) {
				return;
			}
			pinnerpressIsUpdating = true;
			
			// Get current values from form
			var position = $('select[name="pinnerpress_hover_button_position"]').val() || 'top-left';
			var shape = $('select[name="pinnerpress_hover_button_shape"]').val() || 'rectangular';
			var size = $('select[name="pinnerpress_hover_button_size"]').val() || 'medium';
			var color = $('input[name="pinnerpress_hover_button_color"]').val() || '#E60023';
			var textColor = $('input[name="pinnerpress_hover_button_text_color"]').val() || '#FFFFFF';
			var buttonStyle = $('input[name="pinnerpress_hover_button_style"]:checked').val() || 'default';
			var customButtonText = $('input[name="pinnerpress_custom_button_text"]').val() || '';
			var imageShadow = $('input[name="pinnerpress_image_shadow"]:checked').val() === '1';
			
			pinnerpressDebugLog('PinnerPress: Updating button preview with shadow:', imageShadow ? 'enabled' : 'disabled');
			
			// Thoroughly remove ALL existing buttons - more aggressive cleanup
			$('#pinnerpress-preview-image-container .pinnerpress-pin-it-button-wrapper').remove();
			$('#pinnerpress-preview-image-container span[data-pinnerpress-button="true"]').remove();
			$('#pinnerpress-preview-image-container .pinnerpress-pin-it-button').remove();
			
			// Delay slightly to ensure DOM is updated
			setTimeout(function() {
				// Create new button with AJAX
				$.ajax({
					url: pinnerpressVars.ajaxurl,
					type: 'POST',
					data: {
						action: 'pinnerpress_get_preview_button',
						nonce: pinnerpressVars.previewNonce,
						position: position,
						shape: shape,
						size: size,
						color: color,
						text_color: textColor,
						button_style: buttonStyle,
						custom_button_text: customButtonText,
						image_shadow: imageShadow ? '1' : '0'
					},
					success: function(response) {
						// Double-check to remove any buttons that might still be there
						$('#pinnerpress-preview-image-container .pinnerpress-pin-it-button-wrapper').remove();
						
						// Add new button HTML to preview container
						$('#pinnerpress-preview-image-container').append(response);
						
						// After adding button to DOM, explicitly apply shadow style if needed
						var $button = $('#pinnerpress-preview-image-container .pinnerpress-pin-it-button');
						if (imageShadow) {
							$button.css('box-shadow', '0 2px 4px rgba(0,0,0,0.15)');
						} else {
							$button.css('box-shadow', 'none');
						}
						
						pinnerpressDebugLog('PinnerPress: Button count after update:', $('#pinnerpress-preview-image-container .pinnerpress-pin-it-button-wrapper').length);
						
						// Reset the updating flag
						pinnerpressIsUpdating = false;
					},
					error: function() {
						// Reset the updating flag even on error
						pinnerpressIsUpdating = false;
					}
				});
			}, 50);
		}
		
		// Live preview updates
		function updatePreview() {
			// Update based on active tab
			var activeTab = getUrlParameter('tab') || 'settings';
			
			if (activeTab === 'settings') {
				updatePinButtonPreview();
			} else if (activeTab === 'banner') {
				updateBannerPreview();
			} else if (activeTab === 'follow_box') {
				updateFollowBoxPreview();
			} else if (activeTab === 'call_out') {
				updateCallOutPreview();
			}
		}
		
		function updateBannerPreview() {
			// Update banner preview based on settings
			// Get current values from form
			var bannerStatus = $('select[name="pinnerpress_banner_status"]').val() || 'off';
			var bgColor = $('input[name="pinnerpress_banner_bg_color"]').val() || 'rgba(255, 255, 255, 0.5)';
			var opacity = $('input[name="pinnerpress_banner_opacity"]').val() || '50';
			var textColor = $('input[name="pinnerpress_banner_text_color"]').val() || '#BD081C';
			var bannerText = $('input[name="pinnerpress_banner_text"]').val() || 'Pin this';
			
			// Convert opacity to decimal for CSS
			var opacityDecimal = parseInt(opacity) / 100;
			
			// Parse color to apply opacity if it's not already an rgba value
			if (bgColor.indexOf('rgba') === -1) {
				// Convert hex or rgb to rgba
				var rgbColor = bgColor;
				if (bgColor.indexOf('rgb') === -1) {
					// Convert hex to rgb
					rgbColor = hexToRgb(bgColor);
				}
				// Extract the rgb values
				var rgbMatch = rgbColor.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
				if (rgbMatch) {
					var r = rgbMatch[1];
					var g = rgbMatch[2];
					var b = rgbMatch[3];
					// Create rgba with new opacity
					bgColor = 'rgba(' + r + ', ' + g + ', ' + b + ', ' + opacityDecimal + ')';
				}
			} else {
				// It's already rgba, just update the opacity
				bgColor = bgColor.replace(/rgba\((\d+),\s*(\d+),\s*(\d+),\s*[\d\.]+\)/, 'rgba($1, $2, $3, ' + opacityDecimal + ')');
			}
			
			// Remove existing banner
			$('#pinnerpress-banner-preview .pinnerpress-image-banner').remove();

			// For free users, always show the banner preview for demonstration purposes
			// For premium users, only show if banner is enabled
			var shouldShowBanner = false;
			if (typeof pinnerpressVars !== 'undefined' && !pinnerpressVars.isPremium) {
				// Free user - always show preview
				shouldShowBanner = true;
			} else {
				// Premium user - show based on status
				shouldShowBanner = (bannerStatus === 'on');
			}

			if (shouldShowBanner) {
				// Create banner HTML
				var bannerHTML = '<a href="#" class="pinnerpress-image-banner" style="position: absolute; bottom: 0; left: 0; right: 0; background-color: ' + bgColor + '; color: ' + textColor + '; padding: 8px 15px; font-size: 22px; font-weight: 500; display: flex; align-items: center; justify-content: center; text-align: center; text-decoration: none; cursor: pointer; z-index: 9;">';
				bannerHTML += '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="pinnerpress-banner-icon" style="width: 1em; height: 1em; vertical-align: -0.125em; margin-right: 0.4em; fill: currentColor;">';
				bannerHTML += '<path d="M12 0C5.373 0 0 5.373 0 12c0 4.99 3.657 9.132 8.48 10.099-.118-.859-.224-2.178.045-3.116.244-.834 1.577-5.313 1.577-5.313s-.402-.803-.402-1.986c0-1.863 1.08-3.254 2.42-3.254 1.142 0 1.693.859 1.693 1.89 0 1.151-.733 2.87-1.11 4.467-.318 1.322.672 2.401 1.99 2.401 2.388 0 4.224-2.516 4.224-6.14 0-3.204-2.303-5.442-5.581-5.442-3.803 0-6.037 2.849-6.037 5.794 0 1.148.438 2.382 1.054 3.049.117.13.134.244.099.377-.109.427-.354 1.35-.398 1.539-.062.248-.2.302-.461.182-1.723-.796-2.797-3.294-2.797-5.301 0-4.33 3.141-8.306 9.067-8.306 4.754 0 8.442 3.384 8.442 7.917 0 4.715-2.969 8.502-7.085 8.502-1.381 0-2.681-.712-3.123-1.557l-.847 3.216c-.306 1.156-1.14 2.6-1.699 3.487C9.19 23.414 10.573 24 12 24c6.627 0 12-5.373 12-12S18.627 0 12 0z"/>';
				bannerHTML += '</svg>';
				bannerHTML += '<span>' + bannerText + '</span>';
				bannerHTML += '</a>';

				// Add banner to preview container
				$('#pinnerpress-banner-preview').append(bannerHTML);
			}
		}
		
		// Helper function to convert hex color to rgb
		function hexToRgb(hex) {
			// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
			var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
			hex = hex.replace(shorthandRegex, function(m, r, g, b) {
				return r + r + g + g + b + b;
			});
			
			var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
			return result ? 
				'rgb(' + parseInt(result[1], 16) + ', ' + parseInt(result[2], 16) + ', ' + parseInt(result[3], 16) + ')' :
				'rgb(0, 0, 0)';
		}
		
		function updateFollowBoxPreview() {
			// Get current values from follow box form
			var pinterestUrl = $('input[name="pinnerpress_pinterest_url"]').val() || 'https://www.pinterest.com/pinnerpress';
			var displayName = $('input[name="pinnerpress_pinterest_display_name"]').val() || 'PinnerPress';
			var description = $('textarea[name="pinnerpress_account_description"]').val() || 'Follow us on Pinterest for more inspiration!';
			var buttonBgColor = $('input[name="pinnerpress_follow_button_bg_color"]').val() || '#E60023';
			var buttonTextColor = $('input[name="pinnerpress_follow_button_text_color"]').val() || '#FFFFFF';
			var profileImage = $('#pinnerpress_profile_image').val();
			var headerImage = $('#pinnerpress_header_image').val();
			var allowDismiss = $('input[name="pinnerpress_follow_box_allow_dismiss"]').is(':checked');
			
			// Ensure Pinterest URL has protocol if provided
			if (pinterestUrl && !pinterestUrl.match(/^https?:\/\//i)) {
				pinterestUrl = 'https://' + pinterestUrl;
			}
			
			// Log variables for debugging
			pinnerpressDebugLog('updating follow box preview:', {
				pinterestUrl: pinterestUrl,
				displayName: displayName,
				description: description,
				buttonBgColor: buttonBgColor,
				buttonTextColor: buttonTextColor,
				profileImage: profileImage,
				headerImage: headerImage,
				allowDismiss: allowDismiss
			});
			
			// Update text elements in the preview
			$('#pinnerpress-follow-box-preview .pinnerpress-follow-box-inner h3').text(displayName);
			$('#pinnerpress-follow-box-preview .pinnerpress-follow-box-inner p').text(description);
			
			// Update the follow button
			$('#pinnerpress-follow-box-preview .pinnerpress-follow-box-button').css({
				'background-color': buttonBgColor,
				'color': buttonTextColor
			}).attr('href', pinterestUrl);
			
			// Update SVG color to match the text color
			$('#pinnerpress-follow-box-preview .pinnerpress-pinterest-button-logo path').css('fill', buttonTextColor);
			
			// Update profile and header images
			// Don't replace images if they're not set - use the defaults in the HTML
			if (profileImage && profileImage.trim() !== '') {
				$('#pinnerpress-follow-box-preview .pinnerpress-follow-box-logo').css('background-image', 'url(' + profileImage + ')');
			}
			
			if (headerImage && headerImage.trim() !== '') {
				$('#pinnerpress-follow-box-preview .pinnerpress-follow-box-header').css('background-image', 'url(' + headerImage + ')');
			}
			
			// Update dismiss link visibility
			if (allowDismiss) {
				if ($('#pinnerpress-follow-box-preview .pinnerpress-follow-box-dismiss').length === 0) {
					$('#pinnerpress-follow-box-preview .pinnerpress-follow-box-inner').append(
						'<div class="pinnerpress-follow-box-dismiss">' +
						'<a href="#" class="pinnerpress-follow-box-dismiss-link">Don\'t remind me</a>' +
						'</div>'
					);
				}
			} else {
				$('#pinnerpress-follow-box-preview .pinnerpress-follow-box-dismiss').remove();
			}
		}
		
		function updateCallOutPreview() {
			// Get current values from call out banner form
			var bgColor = $('input[name="pinnerpress_call_out_bg_color"]').val() || '#E60023';
			var borderColor = $('input[name="pinnerpress_call_out_border_color"]').val() || '#E60023';
			var textColor = $('input[name="pinnerpress_call_out_text_color"]').val() || '#FFFFFF';
			var title = $('input[name="pinnerpress_call_out_title"]').val() || 'Follow us on Pinterest';
			var buttonText = $('input[name="pinnerpress_call_out_button_text"]').val() || 'Follow';
			var buttonBgColor = $('input[name="pinnerpress_call_out_button_bg_color"]').val() || '#FFFFFF';
			var buttonTextColor = $('input[name="pinnerpress_call_out_button_text_color"]').val() || '#E60023';
			var logo = $('select[name="pinnerpress_call_out_logo"]').val() || 'pinterest';
			var profileImage = $('#pinnerpress_profile_image').val() || '';
			
			// Update the preview elements
			var $preview = $('#pinnerpress-call-out-preview');
			var $banner = $preview.find('.pinnerpress-call-out-banner');
			
			// Update banner background and border colors (NO global text color here)
			$banner.css({
				'background-color': bgColor,
				'border-color': borderColor
			});
			
			// Update title span color
			var $titleSpan = $banner.find('span.pinnerpress-banner-title-span');
			if ($titleSpan.length === 0) { // If it doesn't exist (e.g. first run or structure changed)
			    // We might need to recreate it or ensure its structure, but for now, just find or assume it exists based on PHP output
			    // For robustness, this part could be improved to rebuild the title span if not found.
			    // For now, let's assume it's always the first span that's not inside the button.
			    $titleSpan = $banner.find('span').not('.pinnerpress-button-text-span').first();
			}
			$titleSpan.text(title).attr('style', 'color: ' + textColor + ' !important; font-weight: 600; margin: 0; font-size: 24px !important; text-align: center; flex: 1; display: flex; justify-content: center; align-items: center;');
			
			// Update button with jQuery direct html method
			var $button = $banner.find('.pinnerpress-call-out-button');
			
			// If button doesn't exist, create a new one
			if ($button.length === 0) {
				$button = $('<a target="_blank" class="pinnerpress-call-out-button pinnerpress-button-force-color"></a>');
				$banner.append($button);
			}
			
			$button.addClass('pinnerpress-button-force-color');
			
			// Attempt to find or create the span for the text
			var $spanForText = $button.find('span.pinnerpress-button-text-span');
			if ($spanForText.length === 0) {
				pinnerpressDebugLog('PinnerPress CTA Preview: Text span not found, creating new one.');
				$spanForText = $('<span></span>').addClass('pinnerpress-button-text-span');
				$button.empty().append($spanForText); // Empty button before appending new span
			} else {
				$button.empty().append($spanForText); // Ensure only this span is the content if it was found
			}
			$spanForText.text(buttonText); // Set/update text
			
			pinnerpressDebugLog('PinnerPress CTA Preview: Button Text Variable:', buttonText);
			pinnerpressDebugLog('PinnerPress CTA Preview: Span HTML after text set:', $spanForText.prop('outerHTML'));
			pinnerpressDebugLog('PinnerPress CTA Preview: Button HTML after span append:', $button.html());
			
			// Log the button text color being used
			pinnerpressDebugLog('PinnerPress CTA Preview: Button Text Color Before Style Update:', buttonTextColor);
			
			// Update button styles (main <a> tag)
			var buttonAStyle = 'display: inline-block; ' +
				'background-color: ' + buttonBgColor + ' !important; ' +
				'padding: 8px 15px; ' +
				'text-decoration: none !important; ' +
				'border-radius: 50px; ' +
				'font-weight: 700; ' +
				'white-space: nowrap; ' +
				'margin-left: 15px; ' +
				'min-width: 90px; ' +
				'text-align: center; ' +
				'flex-shrink: 0; ' +
				'box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); ' +
				'font-size: 16px; ' +
				'line-height: 1.4;';
			$button.attr('style', buttonAStyle);
			
			// Update span styles
			var spanStyle = 'color: ' + buttonTextColor + ' !important; ' +
			                'display: inline-block !important; ' +
			                'visibility: visible !important; ' +
			                'opacity: 1 !important;'; 
			                // No font-size or line-height here, as it's on the parent <a> now
			$spanForText.attr('style', spanStyle);
			
			pinnerpressDebugLog('PinnerPress CTA Preview: Button A Style Attribute After Update:', $button.attr('style'));
			pinnerpressDebugLog('PinnerPress CTA Preview: Span Style Attribute After Update:', $spanForText.attr('style'));
			pinnerpressDebugLog('PinnerPress CTA Preview: Final Button HTML:', $button.prop('outerHTML'));
			
			// Set the href attribute
			// First try to get from data attribute (when on Call Out tab), then from input field (when on General tab)
			var pinterestUrl = $('#pinnerpress-call-out-preview').data('pinterest-url') || 
			                   $('input[name="pinnerpress_pinterest_url"]').val() || 
			                   'https://www.pinterest.com/pinnerpress'; // Default if empty
			// Ensure the URL has a protocol
			if (pinterestUrl && !pinterestUrl.match(/^https?:\/\//i)) {
				pinterestUrl = 'https://' + pinterestUrl;
			}
			$button.attr('href', pinterestUrl);
			
			// Handle logo display based on selected option
			if (logo === 'pinterest') {
				// Show Pinterest logo
				var $logoContainer = $banner.find('.pinnerpress-logo');
				if ($logoContainer.length === 0) {
					// Create logo container if it doesn't exist
					$logoContainer = $('<div class="pinnerpress-logo" style="display: flex; align-items: center; justify-content: flex-start; margin-right: 15px; width: auto; min-width: 38px; flex-shrink: 0;"></div>');
					$banner.prepend($logoContainer);
				}
				
				// Clear logo container and add Pinterest SVG
				$logoContainer.empty().show();
				$logoContainer.html('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" style="width: 38px; height: 38px; fill: ' + textColor + ' !important;">' +
					'<path d="M12 0C5.373 0 0 5.373 0 12c0 4.99 3.657 9.132 8.48 10.099-.118-.859-.224-2.178.045-3.116.244-.834 1.577-5.313 1.577-5.313s-.402-.803-.402-1.986c0-1.863 1.08-3.254 2.42-3.254 1.142 0 1.693.859 1.693 1.89 0 1.151-.733 2.87-1.11 4.467-.318 1.322.672 2.401 1.99 2.401 2.388 0 4.224-2.516 4.224-6.14 0-3.204-2.303-5.442-5.581-5.442-3.803 0-6.037 2.849-6.037 5.794 0 1.148.438 2.382 1.054 3.049.117.13.134.244.099.377-.109.427-.354 1.35-.398 1.539-.062.248-.2.302-.461.182-1.723-.796-2.797-3.294-2.797-5.301 0-4.33 3.141-8.306 9.067-8.306 4.754 0 8.442 3.384 8.442 7.917 0 4.715-2.969 8.502-7.085 8.502-1.381 0-2.681-.712-3.123-1.557l-.847 3.216c-.306 1.156-1.14 2.6-1.699 3.487C9.19 23.414 10.573 24 12 24c6.627 0 12-5.373 12-12S18.627 0 12 0z"></path>' +
				'</svg>');
			} else if (logo === 'profile') {
				// Show profile image
				var $logoContainer = $banner.find('.pinnerpress-logo');
				if ($logoContainer.length === 0) {
					// Create logo container if it doesn't exist
					$logoContainer = $('<div class="pinnerpress-logo" style="display: flex; align-items: center; justify-content: flex-start; margin-right: 15px; width: auto; min-width: 38px; flex-shrink: 0;"></div>');
					$banner.prepend($logoContainer);
				}
				
				// Clear logo container and add profile image
				$logoContainer.empty().show();
				
				// Use profile image from settings or default
				var imgSrc = profileImage;
				if (!imgSrc || imgSrc.trim() === '') {
					// Use default profile image
					imgSrc = pinnerpressVars.pluginUrl + 'images/follow-box/default-pinterest-profile-images.png';
				}
				
				$logoContainer.html('<img src="' + imgSrc + '" alt="Profile" style="width: 38px; height: 38px; border-radius: 50%;" />');
			} else {
				// No logo
				$banner.find('.pinnerpress-logo').hide();
			}
		}
		
		
		// Helper function to get URL parameters
		function getUrlParameter(name) {
			name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
			var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
			var results = regex.exec(location.search);
			return results === null ? null : decodeURIComponent(results[1].replace(/\+/g, ' '));
		}
		
		// Ensure radio buttons and checkboxes are properly initialized
		function initializeFormFields() {
			// Ensure default selection for hover button style
			if (!$('input[name="pinnerpress_hover_button_style"]:checked').length) {
				$('input[name="pinnerpress_hover_button_style"][value="default"]').prop('checked', true);
			}
			
			// Ensure default selection for image shadow
			if (!$('input[name="pinnerpress_image_shadow"]:checked').length) {
				$('input[name="pinnerpress_image_shadow"][value="1"]').prop('checked', true);
			}
			
			// Set default values for selects if they don't have a value
			if (!$('select[name="pinnerpress_hover_button_position"]').val()) {
				$('select[name="pinnerpress_hover_button_position"]').val('top-left');
			}
			
			if (!$('select[name="pinnerpress_hover_button_shape"]').val()) {
				$('select[name="pinnerpress_hover_button_shape"]').val('rectangular');
			}
			
			if (!$('select[name="pinnerpress_hover_button_size"]').val()) {
				$('select[name="pinnerpress_hover_button_size"]').val('medium');
			}
		}
		
		// Add event listeners for real-time preview updates
		function addEventListeners() {
			// Pin Button Tab - use debounced updates for rapid changes
			$('select[name="pinnerpress_hover_button_position"]').on('change', debouncedUpdatePreview);
			$('select[name="pinnerpress_hover_button_shape"]').on('change', debouncedUpdatePreview);
			$('select[name="pinnerpress_hover_button_size"]').on('change', debouncedUpdatePreview);
			$('input[name="pinnerpress_hover_button_style"]').on('change', debouncedUpdatePreview);
			$('input[name="pinnerpress_image_shadow"]').on('change', debouncedUpdatePreview);
			$('input[name="pinnerpress_custom_button_text"]').on('input', debouncedUpdatePreview);

			// Custom selector toggle for global filters
			$('#pinnerpress_custom_selectors_enabled').on('change', function() {
				if ($(this).is(':checked')) {
					$('.pinnerpress-global-custom-selectors-row').show();
				} else {
					$('.pinnerpress-global-custom-selectors-row').hide();
				}
			});

			// Follow Box Tab - use debounced updates
			$('select[name="pinnerpress_follow_box_status"]').on('change', debouncedUpdatePreview);
			$('input[name="pinnerpress_pinterest_url"]').on('input', function() {
				validatePinterestUrl();
				debouncedUpdatePreview();
			});
			$('input[name="pinnerpress_pinterest_display_name"]').on('input', debouncedUpdatePreview);
			$('textarea[name="pinnerpress_account_description"]').on('input', debouncedUpdatePreview);
			$('input[name="pinnerpress_profile_image"]').on('change', debouncedUpdatePreview);
			$('input[name="pinnerpress_header_image"]').on('change', debouncedUpdatePreview);

			// Banner Tab - use debounced updates
			$('select[name="pinnerpress_banner_status"]').on('change', debouncedUpdatePreview);
			$('input[name="pinnerpress_banner_text"]').on('input', debouncedUpdatePreview);
			$('input[name="pinnerpress_banner_opacity"]').on('input', updateBannerOpacity);

			// Custom selector toggle for Image Banner
			$('#pinnerpress_banner_custom_selectors_enabled').on('change', function() {
				if ($(this).is(':checked')) {
					$('.pinnerpress-banner-custom-selectors-row').show();
				} else {
					$('.pinnerpress-banner-custom-selectors-row').hide();
				}
			});
			
			// Image size slider - update display value only
			$('.pinnerpress-image-size-slider').on('input change', updateImageSizeValue);
			
			// Call Out Tab - use specific function for call out updates
			$('select[name="pinnerpress_call_out_status"]').on('change', function() {
				setTimeout(updateCallOutPreview, 100);
			});
			$('select[name="pinnerpress_call_out_position"]').on('change', function() {
				setTimeout(updateCallOutPreview, 100);
			});
			$('input[name="pinnerpress_call_out_display_posts"]').on('change', function() {
				setTimeout(updateCallOutPreview, 100);
			});
			$('input[name="pinnerpress_call_out_display_pages"]').on('change', function() {
				setTimeout(updateCallOutPreview, 100);
			});
			$('input[name="pinnerpress_call_out_bg_color"]').on('change', function() {
				setTimeout(updateCallOutPreview, 100);
			});
			$('input[name="pinnerpress_call_out_border_color"]').on('change', function() {
				setTimeout(updateCallOutPreview, 100);
			});
			$('input[name="pinnerpress_call_out_text_color"]').on('change', function() {
				setTimeout(updateCallOutPreview, 100);
			});
			$('input[name="pinnerpress_call_out_title"]').on('input', function() {
				setTimeout(updateCallOutPreview, 100);
			});
			$('input[name="pinnerpress_call_out_button_text"]').on('input', function() {
				setTimeout(updateCallOutPreview, 100);
			});
			$('input[name="pinnerpress_call_out_button_bg_color"]').on('change', function() {
				setTimeout(updateCallOutPreview, 100);
			});
			$('input[name="pinnerpress_call_out_button_text_color"]').on('change', function() {
				setTimeout(updateCallOutPreview, 100);
			});
			$('select[name="pinnerpress_call_out_logo"]').on('change', function() {
				setTimeout(updateCallOutPreview, 100);
			});
			
			// Handle tab switching - use immediate update for tab changes
			$('.nav-tab').on('click', function() {
				// Small delay to ensure the DOM is updated
				setTimeout(function() {
					updatePreview();
				}, 100);
			});
			
			// Show follow modal after saving settings
			$(document).on('submit', '.pinnerpress-settings-form', function(e) {
				// Let the form submit as normal, but show the modal after a short delay
				setTimeout(function() {
					// Try to show the follow modal if it exists
					var $modal = $('#pinnerpress-follow-box-modal');
					if ($modal.length) {
						$modal.fadeIn(300);
					}
				}, 500); // Delay to allow settings to save and page to reload if needed
			});
			
			// Add form validation before submission
			$('.pinnerpress-settings-form').on('submit', function(e) {
				// Only validate if we're on the general tab
				if (getUrlParameter('tab') === 'general') {
					if (!validatePinterestUrl()) {
						e.preventDefault();
						$('html, body').animate({
							scrollTop: $('#pinnerpress_pinterest_url').offset().top - 100
						}, 200);
					}
				}
			});
		}
		
		// Validate Pinterest URL format
		function validatePinterestUrl() {
			var urlField = $('#pinnerpress_pinterest_url');
			var url = urlField.val().trim();
			var errorMessage = $('.pinnerpress-url-error');
			
			// Check if URL is empty - no validation needed
			if (url === '') {
				errorMessage.hide();
				return true;
			}
			
			// Pattern to check for https://pinterest.[tld]/username or https://www.pinterest.[tld]/username format
			var pinterestUrlPattern = /^(https?:\/\/)?(www\.)?pinterest\.[a-z\.]{2,}\/[\w\-\.]+\/?$/i;
			
			if (pinterestUrlPattern.test(url)) {
				// Valid URL format
				errorMessage.hide();
				
				// Make sure URL starts with https:// protocol
				if (!/^https?:\/\//i.test(url)) {
					urlField.val('https://' + url);
				}
				
				return true;
			} else {
				// Invalid URL format
				errorMessage.show();
				return false;
			}
		}
		
		// Handle opacity slider changes
		function updateBannerOpacity() {
			var opacity = $(this).val();
			// Update the displayed value
			$('.pinnerpress-opacity-value').text(opacity + '%');
			// Trigger the banner preview update with debouncing
			debouncedUpdatePreview();
		}
		
		// Handle image size slider changes
		function updateImageSizeValue() {
			var size = $(this).val();
			// Update the displayed value
			$('.pinnerpress-image-size-value').text(size + 'px');
		}
		
		// Initialize Hidden Pinterest Images functionality
		function initHiddenImages() {
			var hiddenImageIndex = $('#pinnerpress-hidden-images-container .pinnerpress-hidden-image-item').length;
			
			// Add hidden image button click
			$(document).on('click', '#pinnerpress-add-hidden-image', function(e) {
				e.preventDefault();
				
				// Always create a fresh media frame to avoid conflicts
				var file_frame = wp.media({
					title: 'Select Hidden Pinterest Images',
					button: {
						text: 'Use these images'
					},
					multiple: true, // Enable multiple selection
					library: {
						type: 'image'
					},
					frame: 'select' // Explicitly set frame type
				});
				
				// Clear any existing event handlers to prevent conflicts
				file_frame.off('select');
				
				// When images are selected, run a callback
				file_frame.on('select', function() {
					// Get all selected images
					var selection = file_frame.state().get('selection');
					var attachments = selection.toJSON();
					
					pinnerpressDebugLog('Selected ' + attachments.length + ' images');
					
					// Loop through each selected image
					attachments.forEach(function(attachment) {
						// Use thumbnail URL if available, otherwise fall back to full URL
						var thumbnailUrl = attachment.sizes && attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url;
						
						// Create new hidden image item for each selected image
						var imageItemHtml = '<div class="pinnerpress-hidden-image-item" data-index="' + hiddenImageIndex + '">' +
							'<div class="pinnerpress-hidden-image-preview">' +
							'<img src="' + thumbnailUrl + '" alt="Hidden Pinterest Image">' +
							'<button type="button" class="pinnerpress-remove-hidden-image" title="Remove image">&times;</button>' +
							'<input type="hidden" name="pinnerpress_hidden_images[' + hiddenImageIndex + '][url]" value="' + attachment.url + '">' +
							'</div>' +
							'</div>';
						
						// Add to container
						$('#pinnerpress-hidden-images-container').append(imageItemHtml);
						
						// Increment index for next image
						hiddenImageIndex++;
					});
				});
				
				// Open the media uploader
				file_frame.open();
			});
			
			// Remove hidden image button click
			$(document).on('click', '.pinnerpress-remove-hidden-image', function(e) {
				e.preventDefault();
				
				// Confirm removal - use localized string if available
				var confirmMessage = pinnerpressVars.confirmRemoveImage || 'Are you sure you want to remove this hidden Pinterest image?';
				if (confirm(confirmMessage)) {
					$(this).closest('.pinnerpress-hidden-image-item').remove();
					
					// Re-index remaining items
					reindexHiddenImages();
				}
			});
			
			// Re-index hidden image items after removal
			function reindexHiddenImages() {
				$('#pinnerpress-hidden-images-container .pinnerpress-hidden-image-item').each(function(index) {
					$(this).attr('data-index', index);
					
					// Update input names
					$(this).find('input[name*="pinnerpress_hidden_images"]').each(function() {
						var name = $(this).attr('name');
						var newName = name.replace(/\[\d+\]/, '[' + index + ']');
						$(this).attr('name', newName);
					});
				});
				
				// Update the index counter
				hiddenImageIndex = $('#pinnerpress-hidden-images-container .pinnerpress-hidden-image-item').length;
			}
		}
		
		// Initialize WordPress Media Uploader
		function initMediaUploader() {
			var file_frame;
			var targetField;
			
			// Handle the media upload button click
			$(document).on('click', '.pinnerpress-media-upload', function(e) {
				e.preventDefault();
				
				// Skip if button is disabled (for free users)
				if ($(this).prop('disabled')) {
					return false;
				}
				
				// Get the target field
				targetField = $(this).data('target');
				
				// If the media frame already exists, reopen it
				if (file_frame) {
					file_frame.open();
					return;
				}
				
				// Create a new media frame
				file_frame = wp.media({
					title: 'Select or Upload Image',
					button: {
						text: 'Use this image'
					},
					multiple: false
				});
				
				// When an image is selected, run a callback
				file_frame.on('select', function() {
					// Get selected image data
					var attachment = file_frame.state().get('selection').first().toJSON();
					
					// Set the image URL in the hidden field
					$('#' + targetField).val(attachment.url).trigger('change');
					
					// Show the preview container
					$('.pinnerpress-media-preview').filter(function() {
						return $(this).closest('.pinnerpress-media-field').find('input').attr('id') === targetField;
					}).show();
					
					// Update preview image with selected image
					var $preview = $('.pinnerpress-media-preview').filter(function() {
						return $(this).closest('.pinnerpress-media-field').find('input').attr('id') === targetField;
					});
					
					// If there's no img element, create one
					if ($preview.find('img').length === 0) {
						$preview.append('<img alt="Selected Image" style="max-width: 200px; max-height: 100px;" />');
					}
					
					// Update the image source
					$preview.find('img').attr('src', attachment.url);
					
					// Show the remove button
					$('.pinnerpress-media-remove[data-target="' + targetField + '"]').show();
					
					// Update the preview with debouncing
					debouncedUpdatePreview();
				});
				
				// Open the media uploader
				file_frame.open();
			});
			
			// Handle the media remove button click
			$(document).on('click', '.pinnerpress-media-remove', function(e) {
				e.preventDefault();
				
				// Skip if button is disabled (for free users)
				if ($(this).prop('disabled')) {
					return false;
				}
				
				// Get the target field
				targetField = $(this).data('target');
				
				// Clear the hidden field value
				$('#' + targetField).val('').trigger('change');
				
				// Hide the preview container
				$('.pinnerpress-media-preview').filter(function() {
					return $(this).closest('.pinnerpress-media-field').find('input').attr('id') === targetField;
				}).hide();
				
				// Hide the remove button
				$(this).hide();
				
				// Update the preview with debouncing
				debouncedUpdatePreview();
			});
		}

		/**
		 * Fix Freemius modal display and functionality issues
		 */
		jQuery(document).ready(function($) {
			// Fix Freemius modal CSS if it's not loading correctly
			if ($('.fs-modal').length > 0 && !$('.fs-modal').hasClass('active')) {
				// The modal exists but isn't properly styled - fix this
				$('.fs-modal').each(function() {
					var $modal = $(this);
					
					// Ensure proper modal styling
					if (!$modal.is(':hidden')) {
						$modal.css({
							'position': 'fixed',
							'top': '0',
							'left': '0',
							'width': '100%',
							'height': '100%',
							'background': 'rgba(0,0,0,0.6)',
							'z-index': '100000',
							'display': 'none'
						});
						
						// Show modal when deactivate is clicked
						$(document).on('click', 'a[href*="action=deactivate"][href*="pinnerpress"]', function(e) {
							e.preventDefault();
							$modal.show().addClass('active');
						});
						
						// Hide modal on cancel
						$modal.find('a:contains("Cancel")').on('click', function(e) {
							e.preventDefault();
							$modal.hide().removeClass('active');
						});
						
						// Handle skip & deactivate
						$modal.find('a:contains("Skip"), a[class*="deactivate"]').on('click', function(e) {
							var originalUrl = $('a[href*="action=deactivate"][href*="pinnerpress"]').attr('href');
							if (originalUrl) {
								window.location.href = originalUrl;
							}
						});
					}
				});
			}
			
					// Let Freemius handle deactivation flow
		});
	});
	
	// Premium feature handling
	$(document).ready(function($) {
		// Handle premium tab clicks
		$('.pinnerpress-disabled-tab').on('click', function(e) {
			e.preventDefault();
			const featureName = $(this).data('premium-feature');
			showUpgradeModal(featureName);
		});
		
		// Handle premium button clicks
		$('.pinnerpress-premium-disabled').on('click', function(e) {
			e.preventDefault();
			const featureName = $(this).attr('title');
			showUpgradeModal(featureName);
		});
		
		// Date range validation for free users
		function validateDateRange(startDate, endDate) {
			if (typeof pinnerpressVars !== 'undefined' && !pinnerpressVars.isPremium) {
				const start = new Date(startDate);
				const end = new Date(endDate);
				const diffDays = Math.ceil((end - start) / (1000 * 60 * 60 * 24));

				if (diffDays > 7) {
					showUpgradeModal('Extended Date Ranges');
					return false;
				}
			}
			return true;
		}

		// Filter chart data for free users
		window.pinnerpressFilterChartData = function(data) {
			if (typeof pinnerpressVars !== 'undefined' && !pinnerpressVars.isPremium) {
				// Hide Follow Box, Call Out, and Post Block Follow stats in charts for free users
				if (data.daily_data) {
					data.daily_data = data.daily_data.filter(item =>
						!['follow_button_click', 'call_out_banner_click', 'block_editor_button_click'].includes(item.event_type)
					);
				}
				if (data.totals) {
					data.totals = data.totals.filter(item =>
						!['follow_button_click', 'call_out_banner_click', 'block_editor_button_click'].includes(item.event_type)
					);
				}
			}
			return data;
		};
		
		// Show upgrade modal
		function showUpgradeModal(featureName) {
			const pricingUrl = '/wp-admin/admin.php?page=pinnerpress-pricing';
			const modal = $('<div class="pinnerpress-upgrade-modal">')
				.html(`
					<div class="pinnerpress-modal-content">
						<span class="pinnerpress-modal-close">&times;</span>
						<h3>🚀 Unlock PinnerPress Premium</h3>
						<p>Upgrade to premium to unlock advanced features including: Call-out Banners, Image Control, Custom CTA Banners, Follow Buttons, Rich Pins, Hidden Pins, Custom Descriptions, Repin Attribution, Post Analytics, and Image Analytics</p>
						<a href="${pricingUrl}" class="button button-primary">
							Upgrade to Premium
						</a>
					</div>
				`);
			
			$('body').append(modal);
			modal.fadeIn();
			
			// Close modal handlers
			modal.find('.pinnerpress-modal-close, .pinnerpress-modal-content').on('click', function(e) {
				if (e.target === this) {
					modal.fadeOut(() => modal.remove());
				}
			});
		}
		
		// Add modal CSS if not already present
		if (!$('#pinnerpress-upgrade-modal-css').length) {
			$('<style id="pinnerpress-upgrade-modal-css">').html(`
				.pinnerpress-upgrade-modal {
					display: none;
					position: fixed;
					z-index: 100000;
					left: 0;
					top: 0;
					width: 100%;
					height: 100%;
					background-color: rgba(0,0,0,0.5);
				}
				.pinnerpress-modal-content {
					background-color: #fefefe;
					margin: 10% auto;
					padding: 20px;
					border: none;
					border-radius: 8px;
					width: 80%;
					max-width: 500px;
					position: relative;
				}
				.pinnerpress-modal-close {
					color: #aaa;
					float: right;
					font-size: 28px;
					font-weight: bold;
					position: absolute;
					right: 15px;
					top: 10px;
					cursor: pointer;
				}
				.pinnerpress-modal-close:hover {
					color: #000;
				}
			`).appendTo('head');
		}

		// Handle date preset clicks on the dashboard
		$('.pinnerpress-dashboard .pinnerpress-date-preset').on('click', function() {
			var days = $(this).data('days');
			
			// Use the server's date as the source of truth
			const serverDateStr = $('.pinnerpress-dashboard').data('server-date');
			const endDate = new Date(serverDateStr + 'T00:00:00'); // Use server date to avoid timezone issues

			const startDate = new Date(endDate.getTime());
			startDate.setDate(startDate.getDate() - (days - 1));

			var startDateStr = formatDate(startDate);
			var endDateStr = formatDate(endDate);

			$('#pinnerpress-start-date').val(startDateStr);
			$('#pinnerpress-end-date').val(endDateStr);

			// Update active class
			$('.pinnerpress-dashboard .pinnerpress-date-preset').removeClass('active');
			$(this).addClass('active');

			// Reload chart with new dates
			loadAnalyticsChart(startDateStr, endDateStr);

			// Reload top posts with new dates
			loadTopPosts(startDateStr, endDateStr);
		});

		// Function to format date as YYYY-MM-DD
		function formatDate(date) {
			var year = date.getFullYear();
			var month = String(date.getMonth() + 1).padStart(2, '0');
			var day = String(date.getDate()).padStart(2, '0');
			return year + '-' + month + '-' + day;
		}
	});

})( jQuery ); 