/* ==========================================================================
   SEOvault AI — Term Meta Box (character counters)
   ========================================================================== */

(function ($) {
	'use strict';

	var limits = typeof seovaultseo_term_metabox !== 'undefined' ? seovaultseo_term_metabox : null;
	if (!limits) {
		return;
	}

	var titleLimits = limits.title_limits || { ideal_min: 50, ideal_max: 60, max: 70, min: 30 };
	var descLimits = limits.desc_limits || { ideal_min: 120, ideal_max: 155, max: 200, min: 70 };
	var ogTitleLimits = limits.og_title_limits || { ideal_min: 25, ideal_max: 88, max: 100, min: 15 };
	var ogDescLimits = limits.og_desc_limits || { ideal_min: 80, ideal_max: 200, max: 300, min: 45 };

	var limitMap = {
		title: titleLimits,
		description: descLimits,
		og_title: ogTitleLimits,
		og_description: ogDescLimits
	};

	function updateCounter($input, $counter, lim) {
		var len = $input.val().length;
		var cls = 'seovaultseo-counter-good';
		var text = len + ' / ' + lim.ideal_min + '-' + lim.ideal_max;

		if (len === 0) {
			cls = 'seovaultseo-counter-bad';
			text = '0 / ' + lim.ideal_min + '-' + lim.ideal_max;
		} else if (len < lim.min) {
			cls = 'seovaultseo-counter-bad';
		} else if (len < lim.ideal_min) {
			cls = 'seovaultseo-counter-okay';
		} else if (len <= lim.ideal_max) {
			cls = 'seovaultseo-counter-good';
		} else if (len <= lim.max) {
			cls = 'seovaultseo-counter-okay';
			text = len + ' / max ' + lim.max;
		} else {
			cls = 'seovaultseo-counter-bad';
			text = len + ' / max ' + lim.max;
		}

		$counter
			.removeClass('seovaultseo-counter-good seovaultseo-counter-okay seovaultseo-counter-bad')
			.addClass(cls)
			.text(text);
	}

	$('.seovaultseo-counted').each(function () {
		var target = $(this).data('counter-target');
		var $counter = $('.seovaultseo-char-counter[data-target="' + $(this).attr('id') + '"]');
		var lim = limitMap[target] || descLimits;

		if ($counter.length) {
			updateCounter($(this), $counter, lim);
		}
	});

	$('.seovaultseo-counted').on('input', function () {
		var target = $(this).data('counter-target');
		var $counter = $('.seovaultseo-char-counter[data-target="' + $(this).attr('id') + '"]');
		var lim = limitMap[target] || descLimits;

		if ($counter.length) {
			updateCounter($(this), $counter, lim);
		}
	});
})(jQuery);
