/**
 * CartCue — Live audience estimate.
 *
 * Listens for changes on trigger_slug or the rule rows, debounces, and posts
 * to the existing cartcue_preview_audience endpoint. Renders a small chip with
 * a count + a sample of matching email addresses (already returned by
 * AudiencePreview::count()).
 *
 * Mounts inside the existing #cartcue-audience-count container — that node
 * already lives in play-edit.php on line ~854.
 */
(function ($) {
	'use strict';

	if (!window.cartcueAdmin || !cartcueAdmin.nonces || !cartcueAdmin.nonces.preview_audience) {
		return;
	}

	var DEBOUNCE_MS = 600;
	var strings = (cartcueAdmin.buildFeatures && cartcueAdmin.buildFeatures.strings) || {};

	function debounce(fn, wait) {
		var t;
		return function () {
			var ctx = this, args = arguments;
			clearTimeout(t);
			t = setTimeout(function () { fn.apply(ctx, args); }, wait);
		};
	}

	function collectRules() {
		var rules = [];
		$('#ap-rules-list .ap-rule-row').each(function () {
			var slug  = $(this).find('.ap-rule-slug').val();
			if (!slug) { return; }
			rules.push({
				slug:     slug,
				operator: $(this).find('.ap-rule-op').val() || '',
				value:    $(this).find('.ap-rule-val').val() || ''
			});
		});
		return rules;
	}

	function ensureContainer() {
		var $c = $('#cartcue-audience-count');
		if (!$c.length) { return null; }
		if (!$c.data('cartcueMounted')) {
			$c.data('cartcueMounted', true).html(
				'<div class="ap-audience-chip" data-audience-chip>' +
					'<span class="ap-audience-chip__icon" aria-hidden="true">👥</span>' +
					'<span class="ap-audience-chip__count" data-audience-count>—</span>' +
					'<span class="ap-audience-chip__hint" data-audience-hint></span>' +
				'</div>'
			);
		}
		return $c;
	}

	function format(n) {
		try { return Number(n).toLocaleString(); } catch (e) { return String(n); }
	}

	function fetchEstimate() {
		var $c = ensureContainer();
		if (!$c) { return; }

		var triggerSlug = $('input[name="trigger_slug"]:checked').val();
		if (!triggerSlug) {
			$c.find('[data-audience-count]').text('—');
			$c.find('[data-audience-hint]').text('Pick a trigger first');
			return;
		}

		$c.find('[data-audience-count]').text('…');
		$c.find('[data-audience-hint]').text(strings.audienceLoading || 'Counting…');

		$.post(cartcueAdmin.ajaxUrl, {
			action: 'cartcue_preview_audience',
			nonce: cartcueAdmin.nonces.preview_audience,
			trigger_slug: triggerSlug,
			rules: JSON.stringify(collectRules())
		}).done(function (res) {
			if (!res || !res.success) {
				$c.find('[data-audience-hint]').text('Could not estimate');
				return;
			}
			var data = res.data || {};
			var count = parseInt(data.count, 10) || 0;
			$c.find('[data-audience-count]').text(format(count));

			if (count === 0) {
				$c.find('[data-audience-hint]').text(strings.audienceZero || 'No customers match.');
				$c.attr('data-tone', 'zero');
				return;
			}
			$c.attr('data-tone', count >= 10 ? 'healthy' : 'small');

			var hint = (strings.audienceMany || '%s match today').replace('%s', format(count) + ' customer' + (count === 1 ? '' : 's'));
			var sample = (data.sample || []).slice(0, 3);
			if (sample.length) {
				hint += ' · ' + (strings.audienceSample || 'Including %s').replace('%s', sample.join(', '));
			}
			$c.find('[data-audience-hint]').text(hint);
		}).fail(function () {
			$c.find('[data-audience-hint]').text('Could not estimate');
		});
	}

	var debounced = debounce(fetchEstimate, DEBOUNCE_MS);

	$(function () {
		ensureContainer();

		// Recompute on rule changes.
		$(document).on('change input', '#ap-rules-list .ap-rule-row :input', debounced);
		$(document).on('click', '#ap-add-rule, .ap-remove-rule', function () {
			setTimeout(debounced, 100);
		});

		// Recompute on trigger change.
		$(document).on('change', 'input[name="trigger_slug"]', debounced);

		// Initial estimate after the page has stabilized.
		setTimeout(fetchEstimate, 600);
	});

})(jQuery);
