/**
 * Character Counter
 *
 * Displays character count with visual warnings for textareas as users
 * approach the maximum length limit.
 *
 * @file
 * @since 1.0.0
 * @package AgenticWP
 * @namespace AgenticWPAdmin.characterCounter
 */

(function($) {
	'use strict';

	const AgenticWPAdmin = window.AgenticWPAdmin = window.AgenticWPAdmin || {};

	/**
	 * Initializes character counter.
	 */
	function init() {
		const $textarea = $('#agentic_wp_create_post_directions');
		const $counter = $('#agenticwp-char-count');

		if (!$textarea.length || !$counter.length) {
			return;
		}

		updateCount($textarea, $counter);
		$textarea.on('input keyup paste', function() {
			updateCount($textarea, $counter);
		});
	}

	/**
	 * Updates character count display.
	 *
	 * @param {jQuery} $textarea - Textarea element.
	 * @param {jQuery} $counter - Counter display element.
	 */
	function updateCount($textarea, $counter) {
		if (!$textarea || !$textarea.length || !$counter || !$counter.length) {
			return;
		}

		try {
			const currentLength = ($textarea.val() || '').length;
			$counter.text(currentLength);
			$counter.removeClass('agenticwp-char-warning agenticwp-char-danger');

			const maxLength = parseInt($textarea.attr('maxlength'), 10);
			if (!maxLength || isNaN(maxLength)) {
				return;
			}

			const percentage = (currentLength / maxLength) * 100;

			if (percentage >= 90) {
				$counter.addClass('agenticwp-char-danger');
			} else if (percentage >= 75) {
				$counter.addClass('agenticwp-char-warning');
			}
		} catch (e) {
		}
	}

	AgenticWPAdmin.characterCounter = {
		init: init
	};
})(jQuery);
