/**
 * Schema template admin: display conditions, scope estimate, preview.
 */
(function ($) {
	'use strict';

	var cfg = window.seovaultSchemaTemplateAdmin || {};
	var $editor = $('#seovault-schema-template-editor');
	if (!$editor.length) {
		return;
	}

	function collectConditions() {
		var rows = [];
		$('#seovault-schema-conditions-rows tr.seovaultseo-schema-condition-row').each(function () {
			var $row = $(this);
			rows.push({
				condition: $row.find('select[name*="[condition]"]').val() || 'include',
				category: $row.find('select[name*="[category]"]').val() || 'singular',
				type: $row.find('select[name*="[type]"]').val() || '',
				value: parseInt($row.find('input[name*="[value]"]').val(), 10) || 0,
				postTaxonomy: $row.find('select[name*="[postTaxonomy]"]').val() || ''
			});
		});
		return rows;
	}

	function reindexRows() {
		$('#seovault-schema-conditions-rows tr.seovaultseo-schema-condition-row').each(function (index) {
			$(this).find('select, input').each(function () {
				var name = $(this).attr('name');
				if (!name) {
					return;
				}
				$(this).attr('name', name.replace(/seovault_display_conditions\[[^\]]+\]/, 'seovault_display_conditions[' + index + ']'));
				var id = $(this).attr('id');
				if (id) {
					$(this).attr('id', id.replace(/seovault-dc-(op|cat|type|tax|value)-.+/, 'seovault-dc-$1-' + index));
				}
			});
			$(this).find('label[for]').each(function () {
				var f = $(this).attr('for');
				if (f) {
					$(this).attr('for', f.replace(/seovault-dc-(op|cat|type|tax|value)-.+/, 'seovault-dc-$1-' + index));
				}
			});
		});
	}

	function updateScope() {
		var $status = $('#seovault-schema-scope-estimate');
		var $alert = $('#seovault-schema-targeting-alert');
		if (!$status.length || !cfg.ajaxUrl) {
			return;
		}
		$status.text((cfg.i18n && cfg.i18n.estimating) || 'Estimating…');
		$.post(cfg.ajaxUrl, {
			action: 'seovaultseo_schema_template_estimate_scope',
			nonce: cfg.nonce,
			conditions: JSON.stringify(collectConditions()),
			schema_type: $('#seovault-schema-type-select').val() || ''
		}).done(function (resp) {
			if (!resp || !resp.success || !resp.data) {
				return;
			}
			var scope = resp.data.scope || {};
			var targeting = resp.data.targeting || {};
			$status.text(scope.label || '');
			if (targeting.ok === false) {
				$alert.text((cfg.i18n && cfg.i18n.broadBlocked) || '').prop('hidden', false);
			} else {
				$alert.text('').prop('hidden', true);
			}
		});
	}

	function syncHiddenJson() {
		var $hidden = $('#seovault-schema-data');
		if (!$hidden.length) {
			return;
		}
		var payload = {};
		try {
			payload = JSON.parse($hidden.val() || '{}') || {};
		} catch (e) {
			payload = {};
		}
		if (!payload.metadata) {
			payload.metadata = {};
		}
		payload.type = $('#seovault-schema-type-select').val() || payload.type || '';
		payload.metadata.displayConditions = collectConditions();
		$hidden.val(JSON.stringify(payload));
	}

	$('#seovault-schema-condition-add').on('click', function () {
		var tpl = document.getElementById('seovault-schema-condition-row-template');
		if (!tpl) {
			return;
		}
		var html = tpl.innerHTML.replace(/__INDEX__/g, String(Date.now()));
		$('#seovault-schema-conditions-rows').append(html);
		reindexRows();
		updateScope();
	});

	$editor.on('click', '.seovaultseo-dc-remove', function () {
		var $rows = $('#seovault-schema-conditions-rows tr.seovaultseo-schema-condition-row');
		if ($rows.length <= 1) {
			$(this).closest('tr').find('select, input').val(function () {
				return $(this).is('input') ? '0' : ($(this).find('option:first').val() || '');
			});
			updateScope();
			return;
		}
		$(this).closest('tr').remove();
		reindexRows();
		updateScope();
	});

	$editor.on('change', '.seovaultseo-schema-conditions select, .seovaultseo-schema-conditions input, #seovault-schema-type-select', function () {
		syncHiddenJson();
		updateScope();
	});

	$('#seovault-schema-preview-btn').on('click', function () {
		var $out = $('#seovault-schema-preview-result');
		var previewId = parseInt($('#seovault-schema-preview-post-id').val(), 10) || 0;
		if (!previewId) {
			$out.text((cfg.i18n && cfg.i18n.previewNoMatch) || '');
			return;
		}
		$out.text((cfg.i18n && cfg.i18n.previewing) || 'Previewing…');
		syncHiddenJson();
		$.post(cfg.ajaxUrl, {
			action: 'seovaultseo_schema_template_preview',
			nonce: cfg.nonce,
			preview_post_id: previewId,
			template_id: $('#post_ID').val() || 0,
			schema_type: $('#seovault-schema-type-select').val() || '',
			conditions: JSON.stringify(collectConditions()),
			fields: (function () {
				try {
					var payload = JSON.parse($('#seovault-schema-data').val() || '{}');
					return JSON.stringify(payload.fields || {});
				} catch (e) {
					return '{}';
				}
			})()
		}).done(function (resp) {
			if (!resp || !resp.success || !resp.data) {
				$out.text('');
				return;
			}
			var d = resp.data;
			var parts = [];
			parts.push(d.matches ? (cfg.i18n.previewMatch || '') : (cfg.i18n.previewNoMatch || ''));
			parts.push(d.would_emit ? (cfg.i18n.ready || '') : (cfg.i18n.notReady || ''));
			if (d.preview_post && d.preview_post.title) {
				parts.push(d.preview_post.title);
			}
			$out.text(parts.filter(Boolean).join(' — '));
		}).fail(function () {
			$out.text('');
		});
	});

	$('form#post').on('submit', function () {
		reindexRows();
		syncHiddenJson();
	});

	updateScope();
})(jQuery);
