(function( $ ) {
	'use strict';

	/**
	 * All of the code for your admin-facing JavaScript source
	 * should reside in this file.
	 *
	 * Note: It has been assumed you will write jQuery code here, so the
	 * $ function reference has been prepared for usage within the scope
	 * of this function.
	 *
	 * This enables you to define handlers, for when the DOM is ready:
	 * $( document ).ready(function() same as
	 * $(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.
	 */
	 
	 //document ready
	 $(function(){
		 
		 
		 
		$( ".popupchoice" ).on("click",function(event) {
			console.log(adminjs_script_vars);
			event.preventDefault();
			//find the type
			//id format: google_choosepopupdiv
			var rtype = $(this).attr('data-type').toLowerCase();
			
			console.log(rtype);
			
			var tbheight = "600";
			if(rtype=='google'){
				tbheight = "500";
			} else if(rtype=='airbnb' || rtype=='angieslist'){
				tbheight = "360";
			} else if(rtype=='facebook'){
				tbheight = "400";
			} else if(rtype=='tripadvisor'){
				tbheight = "395";
			} else if(rtype=='yelp'){
				tbheight = "360";
			} else if(rtype=='zillow'){
				tbheight = "400";
			}

			var url = "#TB_inline?width=930&height="+tbheight+"&inlineId="+rtype+"_choosepopupdiv";
			tb_show(adminjs_script_vars.choosemethod, url);
			$( "#TB_window" ).css({ "height":"auto !important" });
			$( "#TB_ajaxContent" ).css({ "height":"auto !important" });
			$( "#TB_ajaxContent" ).css({ "width":"auto" });
			$( "#TB_ajaxContent" ).focus();
			$('#TB_closeWindowButton').blur();
			
			$('head').append('<style type="text/css">#TB_window {top:100px !important;margin-top: 50px !important;margin-left: -480px !important;width: 960px !important; height: 655px !important; }#TB_ajaxContent {height:auto !important;}</style>');



		});
		
		//help button clicked
		$( "#wprevpro_helpicon_posts" ).on("click",function() {
			console.log(adminjs_script_vars);
			var url = "#TB_inline?width=400&height=200&inlineId=helppopup";
			tb_show("", url);
			$('#TB_closeWindowButton').blur();
			
			$('head').append('<style type="text/css">#TB_window {top:200px !important;margin-top: 50px !important;margin-left: -215px !important;width: 430px !important; height: 230px !important; }</style>');
			
		});
		//add new source
		$( "#wprevpro_addnewtemplate" ).on("click",function() {
			console.log(adminjs_script_vars);
			$( ".chsourcesitediv" ).toggle('slow');
			

		});
		
		// Add custom source button
		$( "#wprevpro_addnewcustomsource" ).on("click", function() {
			console.log('Opening custom source form');
			$( ".customsourceformdiv" ).slideToggle('slow');
		});

	// Cancel custom source form
	$( "#wprevpro_customsource_cancel" ).on("click", function() {
		$( ".customsourceformdiv" ).slideToggle('slow');
		$("#wprevpro_customsource_form")[0].reset();
		$("#custom_site_icon_url").val('');
		$("#icon_preview").hide();
	});

	// Preview icon from URL input
	$( "#custom_site_icon_url" ).on("input", function() {
		var url = $(this).val().trim();
		if (url) {
			$("#icon_preview_img").attr("src", url);
			$("#icon_preview").show();
		} else {
			$("#icon_preview").hide();
		}
	});

	// Media library picker
	var wprevproMediaUploader;
	$( "#wprevpro_media_select" ).on("click", function(e) {
		e.preventDefault();
		if (wprevproMediaUploader) {
			wprevproMediaUploader.open();
			return;
		}
		wprevproMediaUploader = wp.media({
			title: 'Select Icon',
			button: { text: 'Use this icon' },
			multiple: false,
			library: { type: ['image'] }
		});
		wprevproMediaUploader.on('select', function() {
			var attachment = wprevproMediaUploader.state().get('selection').first().toJSON();
			$("#custom_site_icon_url").val(attachment.url).trigger('input');
		});
		wprevproMediaUploader.open();
	});

		// Handle form submission
		$( "#wprevpro_customsource_form" ).on("submit", function(e) {
			e.preventDefault();
			
		// Validate site name doesn't contain URL
		var siteName = $('#custom_site_name').val().trim();
		if (/^(https?:\/\/|www\.)/i.test(siteName) || /\/\//.test(siteName)) {
			alert('Site name cannot be a URL. Please enter a simple name like "Doctify" or "ResellerRatings".');
			return false;
		}

		// Require an icon URL
		var iconUrl = $('#custom_site_icon_url').val().trim();
		if (!iconUrl) {
			alert('Please select an icon from the Media Library or paste an image URL.');
			return false;
		}

		var formData = new FormData(this);
			formData.append('action', 'wprevpro_save_custom_source');
			
			$("#wprevpro_savecustomsource").prop('disabled', true).text('Saving...');
			
			$.ajax({
				url: ajaxurl,
				type: 'POST',
				data: formData,
				processData: false,
				contentType: false,
				success: function(response) {
					if (response.success) {
						alert(response.data.message || 'Custom source saved successfully!');
						
						// Show the custom sources div if hidden
						$('.chsourcesitediv').removeClass('wprevpro_hide').show();
						
						// Add the new custom source button dynamically if we have the data
						if(response.data.custom_source) {
							var cs = response.data.custom_source;
							var customUrl = window.location.origin + '/wp-admin/admin.php?page=wp_pro-get_apps_custom&csid=' + cs.id;
							var newBtn = '<a href="' + customUrl + '" data-type="' + cs.site_name.toLowerCase() + '" data-customid="' + cs.id + '" class="w3-btn w3-white w3-border w3-round sourceiconbtn customsourcebtn">' +
								'<img src="' + cs.icon_url + '?id=' + Date.now() + '" alt="' + cs.site_name + ' icon" class="siconimg"> ' + cs.site_name + '</a>';
							
							// Find or create the custom sources container
							var $container = $('.chsourcesitediv .btnsourcecontainer').first();
							if($container.length === 0) {
								// Create the container if it doesn't exist
								var header = '<header class="w3-container w3-white"><h3 class="welcomecardheader">Custom Review Sources</h3></header>';
								var container = '<div class="w3-container btnsourcecontainer">' + newBtn + '</div>';
								$('.chsourcesitediv .w3-border').prepend(header + container);
							} else {
								// Prepend to existing container
								$container.prepend(newBtn);
							}
						}
						
					// Hide and reset the form
					$('.customsourceformdiv').addClass('wprevpro_hide').hide();
					$('#wprevpro_customsource_form')[0].reset();
					$('#custom_site_icon_url').val('');
					$('#icon_preview').hide();
						$("#wprevpro_savecustomsource").prop('disabled', false).text('Save Custom Source');
					} else {
						alert(response.data.message || 'Error saving custom source');
						$("#wprevpro_savecustomsource").prop('disabled', false).text('Save Custom Source');
					}
				},
				error: function() {
					alert('Error communicating with server');
					$("#wprevpro_savecustomsource").prop('disabled', false).text('Save Custom Source');
				}
			});
		});
		
		// Handle delete custom source button clicks
		$( document ).on("click", ".delete-custom-source", function(e) {
			e.preventDefault();
			var customId = $(this).data('customid');
			var $row = $(this).closest('tr');
			
			if(confirm('Are you sure you want to delete this custom source? This action cannot be undone.')) {
				$.ajax({
					url: ajaxurl,
					type: 'POST',
					data: {
						action: 'wprevpro_delete_custom_source',
						custom_id: customId
					},
					success: function(response) {
						if (response.success) {
							$row.fadeOut(400, function() {
								$(this).remove();
							});
							alert('Custom source deleted successfully!');
						} else {
							alert(response.data.message || 'Error deleting custom source');
						}
					},
					error: function() {
						alert('Error communicating with server');
					}
				});
			}
		});
		
		//create new datatable, https://datatables.net/
		$('#revsourcetbl').DataTable({
        order: [[0, 'desc']],
		"pageLength": 20,
    });



		
	 });

})( jQuery );
