/**
 * SEOvault AI — Settings Page Variable Panel
 * Persistent variable list with + buttons for inserting into template fields.
 */
(function ($) {
	'use strict';

	// ==========================================================================
	// Template Enable/Disable Toggle
	// ==========================================================================

	var $toggle = $('#seovaultseo_templates_enabled');
	if ($toggle.length) {
		var $rows = $('#seovaultseo-template-row-separator, #seovaultseo-template-row-title, #seovaultseo-template-row-description');

		function updateTemplateRows() {
			if ($toggle.is(':checked')) {
				$rows.show();
			} else {
				$rows.hide();
			}
		}

		$toggle.on('change', updateTemplateRows);
		updateTemplateRows();
	}

	// ==========================================================================
	// Variable Picker
	// ==========================================================================

	var data = (typeof seovaultseo_metabox !== 'undefined') ? seovaultseo_metabox : null;
	if (!data || !data.variables || !Object.keys(data.variables).length) {
		return;
	}

	var variables = data.variables;
	var $activeTarget = null;
	var $dropdown = $('<div class="seovaultseo-var-picker-dropdown" style="display:none;"></div>');
	var searchPlaceholder = (data && data.search_variables) ? data.search_variables : 'Search variables…';
	var $search = $('<input type="text" class="seovaultseo-var-picker-search" placeholder="' + searchPlaceholder.replace(/"/g, '&quot;') + '" />');
	var $list = $('<div class="seovaultseo-var-picker-list"></div>');

	$dropdown.append($search).append($list);
	$('body').append($dropdown);
	$dropdown.on('click', function (e) {
		e.stopPropagation();
	});

	function escapeHtml(str) {
		return String(str)
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;')
			.replace(/'/g, '&#039;');
	}

	function buildList(filter) {
		$list.empty();
		filter = (filter || '').toLowerCase();

		Object.keys(variables).forEach(function (id) {
			var v = variables[id];
			var label = v.name || id;
			if (filter && label.toLowerCase().indexOf(filter) === -1 && id.toLowerCase().indexOf(filter) === -1) {
				return;
			}

			var $item = $('<div class="seovaultseo-var-picker-item" data-variable="%' + v.variable + '%"></div>');
			$item.append('<span class="seovaultseo-var-picker-item-name">' + escapeHtml(label) + '</span>');
			$item.append('<span class="seovaultseo-var-picker-item-desc">' + escapeHtml(v.description || '') + '</span>');
			$list.append($item);
		});
	}

	buildList('');

	$search.on('input', function () {
		buildList($(this).val());
	});

	$('.seovaultseo-var-target').on('focus', function () {
		$activeTarget = $(this);
		$('.seovaultseo-var-target').removeClass('seovaultseo-var-target-active');
		$(this).addClass('seovaultseo-var-target-active');
	});

	$list.on('click', '.seovaultseo-var-picker-item', function (e) {
		e.preventDefault();
		e.stopPropagation();

		var token = $(this).data('variable');
		if (!$activeTarget || !token) {
			return;
		}

		var $field = $activeTarget;
		var val = $field.val();
		var start = $field[0].selectionStart !== undefined ? $field[0].selectionStart : val.length;
		var end = $field[0].selectionEnd !== undefined ? $field[0].selectionEnd : val.length;

		var newVal = val.substring(0, start) + token + val.substring(end);
		$field.val(newVal);

		var newPos = start + token.length;
		$field.focus();
		if ($field[0].setSelectionRange) {
			$field[0].setSelectionRange(newPos, newPos);
		}

		$field.trigger('input').trigger('change');

		closeDropdown();
	});

	$('.seovaultseo-var-picker-btn').on('click', function (e) {
		e.preventDefault();
		e.stopPropagation();
		var targetId = $(this).data('target');
		$activeTarget = $('#' + targetId);
		if (!$activeTarget.length) {
			return;
		}

		$('.seovaultseo-var-target').removeClass('seovaultseo-var-target-active');
		$activeTarget.addClass('seovaultseo-var-target-active').focus();

		if ($dropdown.is(':visible') && $dropdown.data('current-target') === targetId) {
			closeDropdown();
			return;
		}

		$dropdown.data('current-target', targetId);

		var $btn = $(this);
		var offset = $btn.offset();
		var dropdownWidth = 280;
		var left = offset.left - dropdownWidth + $btn.outerWidth();
		var top = offset.top + $btn.outerHeight() + 4;

		if (left < 0) {
			left = 0;
		}

		$dropdown.css({
			display: 'block',
			position: 'absolute',
			left: left + 'px',
			top: top + 'px',
			width: dropdownWidth + 'px',
			zIndex: 999999
		});

		$search.val('');
		buildList('');
		$search.focus();
	});

	$(document).on('click', function (e) {
		if (!$(e.target).closest('.seovaultseo-var-picker-dropdown, .seovaultseo-var-picker-btn').length) {
			closeDropdown();
		}
	});

	$(document).on('keydown', function (e) {
		if (e.keyCode === 27 && $dropdown.is(':visible')) {
			closeDropdown();
		}
	});

	function closeDropdown() {
		$dropdown.hide();
		$dropdown.data('current-target', '');
	}

	// ==========================================================================
	// @ Trigger — Type @ to open variable picker
	// ==========================================================================

	$('.seovaultseo-var-target').on('keyup', function (e) {
		if (e.key !== '@' && e.keyCode !== 50) {
			return;
		}

		var $field = $(this);
		$activeTarget = $field;
		$('.seovaultseo-var-target').removeClass('seovaultseo-var-target-active');
		$field.addClass('seovaultseo-var-target-active');

		var fieldId = $field.attr('id');
		$dropdown.data('current-target', fieldId);

		var caretPos = $field[0].selectionStart !== undefined ? $field[0].selectionStart : 0;
		var rect = $field[0].getBoundingClientRect();
		var dropdownWidth = 280;
		var left = rect.left + window.scrollX;
		var top = rect.bottom + window.scrollY + 4;

		if (left + dropdownWidth > $(window).width() + window.scrollX) {
			left = $(window).width() + window.scrollX - dropdownWidth - 10;
		}
		if (left < 0) {
			left = 0;
		}

		$dropdown.css({
			display: 'block',
			position: 'absolute',
			left: left + 'px',
			top: top + 'px',
			width: dropdownWidth + 'px',
			zIndex: 999999
		});

		$search.val('');
		buildList('');
		$search.focus();
	});

	// ==========================================================================
	// Character Counters
	// ==========================================================================

	function getFieldByTarget(targetId, $context) {
		var $scoped = $();
		if ($context && $context.length) {
			$scoped = $context.find('[id="' + targetId + '"]').filter('input, textarea, select');
		}

		if ($scoped.length) {
			return $scoped.first();
		}

		var $visible = $('[id="' + targetId + '"]:visible').filter('input, textarea, select');
		if ($visible.length) {
			return $visible.first();
		}

		return $('[id="' + targetId + '"]').filter('input, textarea, select').first();
	}

	function updateHomepageCounters() {
		$('.seovaultseo-char-counter').each(function () {
			var $counter = $(this);
			var targetId = $counter.data('target');
			var maxLen = parseInt($counter.data('max'), 10) || 0;
			var $countEl = $counter.find('.seovaultseo-char-count');
			var $field = getFieldByTarget(targetId, $counter.closest('.seovaultseo-homepage-field'));

			if (!$field.length) {
				return;
			}

			var val = $field.val() || '';
			var len = val.length;
			$countEl.text(len);

			if (maxLen > 0 && len > maxLen) {
				$counter.addClass('seovaultseo-char-over');
			} else {
				$counter.removeClass('seovaultseo-char-over');
			}
		});
	}

	// ==========================================================================
	// Google Search Result Preview
	// ==========================================================================

	var siteData = (data && data.site) ? data.site : { name: '', description: '', url: '', favicon: '' };

	function getPreviewTitleElement() {
		var $visible = $('.seovaultseo-google-preview-page-title:visible').first();
		return $visible.length ? $visible : $('.seovaultseo-google-preview-page-title').first();
	}

	function getPreviewDescElement() {
		var $visible = $('.seovaultseo-google-preview-page-desc:visible').first();
		return $visible.length ? $visible : $('.seovaultseo-google-preview-page-desc').first();
	}

	function getTitleField() {
		var $visible = $('.seovaultseo-homepage-title-input:visible').first();
		return $visible.length ? $visible : $('.seovaultseo-homepage-title-input').first();
	}

	function getDescField() {
		var $visible = $('.seovaultseo-homepage-desc-input:visible').first();
		return $visible.length ? $visible : $('.seovaultseo-homepage-desc-input').first();
	}

	function replaceVars(str) {
		if (!str) {
			return '';
		}
		var fallbacks = {
			'sitename': siteData.name || '',
			'sitedesc': siteData.description || '',
			'sep': '-',
			'currentdate': new Date().toLocaleDateString(),
			'currenttime': new Date().toLocaleTimeString(),
			'currentyear': String(new Date().getFullYear())
		};
		return str.replace(/%([a-z0-9_]+)%/gi, function (match, varName) {
			if (variables) {
				for (var id in variables) {
					if (variables[id].variable === varName) {
						var example = variables[id].example;
						if (example) {
							return example;
						}
					}
				}
			}
			if (fallbacks[varName] !== undefined) {
				return fallbacks[varName];
			}
			return '';
		});
	}

	function truncate(str, max) {
		if (!str) {
			return '';
		}
		return str.length > max ? str.substring(0, max) + '…' : str;
	}

	function updateGooglePreview() {
		var $previewTitle = getPreviewTitleElement();
		var $previewDesc = getPreviewDescElement();
		var $titleField = getTitleField();
		var $descField = getDescField();

		if (!$previewTitle.length) {
			return;
		}

		var titleVal = $titleField.val() || '';
		var descVal = $descField.val() || '';

		var title = titleVal ? replaceVars(titleVal) : (siteData.name || '');
		var desc = descVal ? replaceVars(descVal) : (siteData.description || '');

		$previewTitle.text(truncate(title, 60));
		$previewDesc.text(truncate(desc, 160));
	}

	$(document).on('input change keyup paste', '.seovaultseo-homepage-title-input, .seovaultseo-homepage-desc-input', function () {
		updateHomepageCounters();
		updateGooglePreview();
	});

	updateHomepageCounters();
	updateGooglePreview();

})(jQuery);
