(function( $ ) {
	'use strict';

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

	var generated = false;
	var percentage = 0;
	var loaded = 1;
	var opened_textarea = '';

	$( document ).ready( function() {

		$('body').on('click', function(e) {
			$('.edit-menu').hide();
		});

		$('.add_page_to_wizard').on('click', function(e) {
			let counter = $('.counter').length;
			let htmlBlock = '' +
				'<div class="flex relative pb-10 sm:items-center md:w-2/3 mx-auto">\n' +
				'  	<div class="h-full w-6 absolute inset-0 flex items-center justify-center">\n' +
				'  		<div class="h-full w-1 bg-gray-200 pointer-events-none"></div>\n' +
				'   </div>\n' +
				'   <div class="counter cursor-pointer flex-shrink-0 w-6 h-6 rounded-full mt-10 sm:mt-0 inline-flex items-center justify-center bg-indigo-500 text-white relative title-font font-medium text-sm" data-id="' + (counter + 1) + '">' + (counter + 1) +'</div>\n' +
				'   	<div class="flex-grow md:pl-8 pl-6 flex sm:items-center items-start flex-col sm:flex-row">\n' +
				'       	<div class="flex-shrink-0 w-24 h-24 bg-indigo-100 text-indigo-500 rounded-full inline-flex items-center justify-center">\n' +
				'           	<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-12">\n' +
				'  					<path stroke-linecap="round" stroke-linejoin="round" d="M12 6.042A8.967 8.967 0 0 0 6 3.75c-1.052 0-2.062.18-3 .512v14.25A8.987 8.987 0 0 1 6 18c2.305 0 4.408.867 6 2.292m0-14.25a8.966 8.966 0 0 1 6-2.292c1.052 0 2.062.18 3 .512v14.25A8.987 8.987 0 0 0 18 18a8.967 8.967 0 0 0-6 2.292m0-14.25v14.25" />\n' +
				'				</svg>\n' +
				'           </div>\n' +
				'      		<div class="flex-grow sm:pl-6 mt-6 sm:mt-0">\n' +
				'           	<input type="hidden" name="page_id[]" value="0" id="page_id_' + (counter + 1) + '">\n' +
				'           	<textarea rows="1" name="page_name[]" id="editable-text-area-with-value" class="page_name required text-xl text-gray-900 block w-full pr-10 p-1 -ml-1 rounded resize-none border-transparent bg-transparent cursor-pointer hover:bg-gray-100 focus:bg-transparent focus:outline-none focus:ring focus:ring-blue-500/50 focus:border-blue-500 group-focus-within:border-blue-500" placeholder="New page name"></textarea>\n' +
				'               <textarea rows="2" name="page_description[]" id="editable-text-area-with-value" class="block w-full pr-10 p-1 -ml-1 rounded resize-none border-transparent bg-transparent cursor-pointer hover:bg-gray-100 focus:bg-transparent focus:outline-none focus:ring focus:ring-blue-500/50 focus:border-blue-500 group-focus-within:border-blue-500" placeholder="We will generate the content for this page based on our best guess, but please write anything specific you’d like us to include in this page."></textarea>\n' +
				'           </div>\n' +
				'    </div>\n' +
				'</div>';

			$(htmlBlock).insertBefore('.wizard_action');
			scrollToBottom();
			e.preventDefault();
		});

		$('#wizard_form').on('click', '.counter', function () {
			const $btn = $(this);

			if ($btn.hasClass('bg-indigo-500')) {
				$btn.removeClass('bg-indigo-500').addClass('bg-gray-500');
				$('#page_id_' + $btn.data('id')).val(1);
			} else {
				$btn.removeClass('bg-gray-500').addClass('bg-indigo-500');
				$('#page_id_' + $btn.data('id')).val(0);
			}
		});

		$('.save_wizard_content').on('click', function(e) {
			if (!isValidPageNames()) {
				alert('All pages needs to have a page name!');
				return;
			}

			let formData = $('#wizard_form').serialize();
			$('#loader').removeClass('hidden');

			setInterval(() => getProcess(), 4000);

			wp.ajax.post( "generate_content", {data: formData})
				.done(function() {
					generated = true;
				})
				.fail(function(response) {
					$('#loader').addClass('hidden');
					
					// Debug: Log the actual response structure
					console.log('WordPress AJAX fail callback received:', response);
					console.log('Response type:', typeof response);
					console.log('Response keys:', Object.keys(response || {}));
					
					// Extract specific error information
					let errorMessage = 'There was an error processing your request.';
					
					// WordPress wp.ajax.post() passes different data structure
					if (response) {
						// Check for common WordPress AJAX error response patterns
						if (typeof response === 'string') {
							errorMessage = response;
						} else if (response.message) {
							errorMessage = response.message;
						} else if (response.data) {
							errorMessage = response.data;
						} else if (response.error) {
							errorMessage = response.error;
						} else if (response.responseText) {
							// Sometimes xhr object is passed
							try {
								const parsed = JSON.parse(response.responseText);
								if (parsed.data) {
									errorMessage = parsed.data;
								} else if (parsed.message) {
									errorMessage = parsed.message;
								}
							} catch (e) {
								errorMessage = response.responseText || 'Unknown error occurred';
							}
						}
					}
					
					console.log('Final error message:', errorMessage);
					
					// Update the modal with the specific error message
					$('#failure_error_message').text(errorMessage);
					$('.failure_modal').removeClass('hidden');
				});
			e.preventDefault();
		});

		$('#close_success_modal').on('click', function(e) {
			$('.success_modal').addClass('hidden');
			e.preventDefault();
		})

		$('#close_failure_modal').on('click', function(e) {
			$('.failure_modal').addClass('hidden');
			e.preventDefault();
		})

		$('.go_to_new_pages').on('click', function(e) {
			let url = $(this).data('url');
			window.location = url;
			e.preventDefault();
		})

		$('#ai_generate_description').on('click', function(e) {
			e.preventDefault();
			let description = $('#website_description');

			$('.ai-small-loader').show();
			description.addClass('disabled');

			jQuery.ajax({
				type: "post",
				url: spawnster.ajax_url,
				data: {
					action: "generate_description",
					website_name: $('#website_name').val(),
					_wpnonce: $('#_wpnonce').val(),
				},
				complete: function (response) {
					$('.ai-small-loader').hide();
					description.removeClass('disabled');
					$('#website_description').val(JSON.parse(response.responseText).data);
				},
			});
		});

		$('.regen').on('click', function(e) {
			let id = $(this).data('id');
			let regenContent = $('#regen_content_' + id);

			if (regenContent.val() === '') {
				alert('Description is required!');
				regenContent.focus();
				return false;
			}

			$(this).addClass('hidden');
			$('.small-loader').removeClass('hidden');
			e.preventDefault();
		});

		$('.edit_icon').on('click', function(e) {
			let id = $(this).data('id');

			jQuery.ajax({
				type: "post",
				url: spawnster.ajax_url,
				data: {
					action: "view_content",
					id: id,
					_wpnonce: $('#_wpnonce').val(),
				},
				complete: function (response) {
					$('#edit_modal_id').val(id);
					tinyMCE.activeEditor.setContent(response.responseText);
					$('#edit_modal_block').removeClass('hidden');
				},
			});
			e.preventDefault();
		});

		$('.close_edit_modal').on('click', function(e) {
			$('#edit_modal_block').addClass('hidden');
			e.preventDefault();
		});

		$('.update_edit_modal').on('click', function(e) {

			tinyMCE.triggerSave();
			let id = $('#edit_modal_id').val();
			let form = $('#edit_modal_form');

			jQuery.ajax({
				type: "post",
				url: spawnster.ajax_url,
				data: {
					action: "update_content",
					data: form.serialize(),
					_wpnonce: $('#_wpnonce').val(),
				},
				complete: function (response) {
					$('#response-' + id + ' > p').html(response.responseText);
					$('#edit_modal_block').addClass('hidden');
				},
			});
		});

		$('.publish_confirm').on('click', function(e) {
			$('.confirm_modal').removeClass('hidden');
			e.preventDefault();
		});

		$('.cancel_confirm, .close_confirm').on('click', function(e) {
			$('.confirm_modal').addClass('hidden');
			e.preventDefault();
		});

		$('.publish_pages').on('click', function(e) {

			jQuery.ajax({
				type: "post",
				url: spawnster.ajax_url,
				data: {
					action: "publish_pages",
				},
				complete: function (response) {
					$('.confirm_modal').addClass('hidden');
					$('.pages_created_modal').removeClass('hidden');
				},
			});
			e.preventDefault();
		})

		$('.got_it').on('click', function(e) {
			window.location = 'edit.php?post_type=page';
			e.preventDefault();
		});

		$('.para').on('mouseover', function(e) {
			let id = $(this).data('id');
			let responseBlock = $('#response-' + id);

			// hide all the reply block class
			$('.reply_block').addClass('hidden');

			// show specific reply block
			if (responseBlock.hasClass('hidden')) {
				$('#reply-block-' + id).removeClass('hidden');
			}

		});

		$('.reply-button').on('click', function(e) {
			$('.textarea_block').addClass('hidden');
			let id = $(this).data('id');
			opened_textarea = id;
			$('#textarea-block-' + id).removeClass('hidden');
			e.preventDefault();
		});

		$('.enhance_button').on('click', function(e) {
			let id = $(this).data('id');
			let context = $('#context-' + id);
			let content = $('#enhance-content-' + id);
			let small_loader = $(this).parent().next('div.small-loader-div');

			if (content.val() === '') {
				return false;
			}

			// hide button and show small loader
			$(this).hide();
			small_loader.show();

			jQuery.ajax({
				type: "post",
				url: spawnster.ajax_url,
				data: {
					action: "enhance_content",
					context: context.text().trim(),
					content: content.val(),
					_wpnonce: $('#_wpnonce').val(),
					id: id,
				},
				complete: function (response) {
					small_loader.hide();
					$('#enhance-button-' + id).show();
					$('#reply-block-' + id).addClass('hidden');
					$('#textarea-block-' + id).addClass('hidden');

					context.addClass('text-red-500');

					$('#response-' + id).removeClass('hidden');
					$('#response-' + id + ' > p').empty().append(response.responseText);
				},
			});

			e.preventDefault();
		});

		$('.accept_changes').on('click', function(e) {
			let id = $(this).data('id');
			let context = $('#context-' + id);

			jQuery.ajax({
				type: "post",
				url: spawnster.ajax_url,
				data: {
					action: "accept_content",
					id: id,
					_wpnonce: $('#_wpnonce').val(),
				},
				complete: function (response) {
					context.removeClass('text-red-500');
					$('#context-' + id + ' > p').html(response.responseText);
					$('#response-' + id).addClass('hidden');
					$('#textarea-block-' + id).addClass('hidden');
					$('#reply-block-' + id).addClass('hidden');
					$('#enhance-content-' + id).val('');
				},
			});

			e.preventDefault();
		});

		$('.reject_changes').on('click', function(e) {
			let id = $(this).data('id');
			let context = $('#context-' + id);

			jQuery.ajax({
				type: "post",
				url: spawnster.ajax_url,
				data: {
					action: "reject_content",
					id: id,
					_wpnonce: $('#_wpnonce').val(),
				},
				complete: function (response) {
					context.removeClass('text-red-500');
					$('#response-' + id).addClass('hidden');
					$('#textarea-block-' + id).addClass('hidden');
					$('#reply-block-' + id).addClass('hidden');
					$('#enhance-content-' + id).val('');
				},
			});

			e.preventDefault();
		});

		$('.menu-item').on('mouseover', function(e) {
			let id = $(this).data('id');

			// hide all edit menu icons
			$('.edit-menu').hide();

			// show edit icon on menu
			$('#edit-menu-' + id).show();

			e.preventDefault();
		});

		$('.edit-menu').on('click', function(e) {
			let id = $(this).data('id');
			let context = $('#menu-item-span-' + id ).html();
			$('#edit-menu-text').val(context);
			$('#edit-menu-id').val(id);
			$('.edit_modal_menu').removeClass('hidden');
		});

		$('.close_page_name_modal').on('click', function(e) {
			$('.edit_modal_menu').addClass('hidden');
			e.preventDefault();
		});

		$('.update_page_name_modal').on('click', function(e) {
			let menu = $('#edit-menu-text');
			let id = $('#edit-menu-id');

			if (menu.val() === '') {
				alert('Page name is required!');
				return false;
			}

			jQuery.ajax({
				type: "post",
				url: spawnster.ajax_url,
				data: {
					action: "edit_menu",
					id: id.val(),
					menu: menu.val(),
					_wpnonce: $('#_wpnonce').val(),
				},
				complete: function (response) {
					$('.edit_modal_menu').addClass('hidden');
					$('#menu-item-span-' + id.val()).html(menu.val());
				},
			});
		});

		$('.reset_all').on('click', function(e) {

			e.preventDefault();
		})
	});

	function scrollToBottom()
	{
		$("html, body").animate({
			scrollTop: $(document).height()
		}, 1000);
	}

	function isValidPageNames()
	{
		let valid = true;
		$('.page_name').each(function() {
			if ($(this).val() == '') {
				valid = false;
			}
		});
		return valid;
	}

	function getProcess() {

		var element = document.getElementById("robin");
		var number = document.getElementById("robin1");
		var length = $('.counter').length;
		var resp = 0;

		percentage = Math.ceil(loaded * (100 / length));

		jQuery.ajax({
			type: "post",
			url: spawnster.ajax_url,
			data: {
				action: "get_progress",
			},
			complete: function (response) {
				resp = parseInt(response.responseText);
			},
		});

		element.style.strokeDasharray = Math.round(Math.PI * (2 * 48));
		element.style.strokeDashoffset =
			Math.round(Math.PI * (2 * 48)) - (percentage / 100) * 302;
		number.innerHTML = percentage + "%";

		if (loaded < length) { loaded++; }

		if (generated) {
			$('#loader').addClass('hidden');
			$('.success_modal').removeClass('hidden');
		}

	}

})( jQuery );
