/* ==========================================================================
   SEOvault AI — Quick Edit & Bulk Edit JavaScript
   Populates SEO fields when Quick Edit opens, saves via AJAX.
   ========================================================================== */

(function($) {
	'use strict';

	var qe = (typeof seovaultseo_quick_edit !== 'undefined') ? seovaultseo_quick_edit : null;

	if (!qe) {
		return;
	}

	// Populate Quick Edit fields when the inline editor opens.
	$(document).on('click', 'a.editinline', function() {
		var $row = $(this).closest('tr');
		var id = wp.inlineEdit.post.getId($row);

		// Wait for the inline editor row to be created.
		setTimeout(function() {
			var $editRow = $('#edit-' + id);
			if (!$editRow.length) {
				return;
			}

			// Find the hidden data span for this post.
			var $data = $('.seovaultseo-quick-edit-data[data-post-id="' + id + '"]');

			if ($data.length) {
				$editRow.find('input[name="seovault_seo_title"]').val($data.data('seo-title') || '');
				$editRow.find('textarea[name="seovault_seo_description"]').val($data.data('seo-description') || '');

				if ($data.data('noindex') === '1' || $data.data('noindex') === 1) {
					$editRow.find('input[name="seovault_robots_noindex"]').prop('checked', true);
				} else {
					$editRow.find('input[name="seovault_robots_noindex"]').prop('checked', false);
				}

				if ($data.data('nofollow') === '1' || $data.data('nofollow') === 1) {
					$editRow.find('input[name="seovault_robots_nofollow"]').prop('checked', true);
				} else {
					$editRow.find('input[name="seovault_robots_nofollow"]').prop('checked', false);
				}
			}
		}, 100);
	});

	// Override the Quick Edit save to include SEO fields via AJAX.
	// WordPress's inlineEdit.post.save doesn't know about our custom fields,
	// so we hook into the save button click and send our data separately.
	$(document).on('click', '.save .button-primary', function() {
		var $editRow = $(this).closest('tr');
		var id = $editRow.attr('id').replace('edit-', '');

		if (!id) {
			return;
		}

		var data = {
			action: 'seovaultseo_quick_edit_save',
			nonce: qe.nonce,
			post_id: id,
			seovault_seo_title: $editRow.find('input[name="seovault_seo_title"]').val() || '',
			seovault_seo_description: $editRow.find('textarea[name="seovault_seo_description"]').val() || '',
			seovault_robots_noindex: $editRow.find('input[name="seovault_robots_noindex"]').is(':checked') ? 1 : 0,
			seovault_robots_nofollow: $editRow.find('input[name="seovault_robots_nofollow"]').is(':checked') ? 1 : 0
		};

		$.ajax({
			url: qe.ajax_url,
			method: 'POST',
			data: data
		});
	});

})(jQuery);
