/**
 * CartCue — Inline trigger recommendation.
 *
 * Shown only when the user lands on the blank custom builder (no recipe).
 * Renders a banner above the trigger grid that one-click selects
 * cart_abandoned (or any other recommended slug).
 *
 * Server controls visibility via buildFeatures.showRecommendation.
 */
(function ($) {
	'use strict';

	var cfg = (window.cartcueAdmin && cartcueAdmin.buildFeatures) || {};
	if (!cfg.showRecommendation) { return; }

	var strings = cfg.strings || {};
	var RECOMMENDED_SLUG = 'cart_abandoned';

	$(function () {
		var $grid = $('#ap-trigger-grid');
		if (!$grid.length) { return; }

		// Don't show if a trigger is already chosen (loaded play / recipe).
		if ($('input[name="trigger_slug"]:checked').length) { return; }

		var $banner = $(
			'<div class="ap-trigger-recommend" role="region" aria-label="Recommendation">' +
				'<div class="ap-trigger-recommend__icon" aria-hidden="true">💡</div>' +
				'<div class="ap-trigger-recommend__body">' +
					'<strong class="ap-trigger-recommend__title"></strong>' +
					'<p class="ap-trigger-recommend__desc"></p>' +
				'</div>' +
				'<button type="button" class="ap-btn ap-btn-primary ap-trigger-recommend__cta"></button>' +
				'<button type="button" class="ap-trigger-recommend__dismiss" aria-label="Dismiss recommendation" title="Dismiss">×</button>' +
			'</div>'
		);
		$banner.find('.ap-trigger-recommend__title').text(strings.recommendTitle || 'Not sure where to start?');
		$banner.find('.ap-trigger-recommend__desc').text(strings.recommendBody  || 'Most stores start with Cart Abandoned — it recovers the most revenue.');
		$banner.find('.ap-trigger-recommend__cta').text(strings.recommendCta   || 'Use Cart Abandoned →');

		$grid.before($banner);

		$banner.on('click', '.ap-trigger-recommend__cta', function () {
			var $radio = $('input[name="trigger_slug"][value="' + RECOMMENDED_SLUG + '"]');
			if ($radio.length) {
				$radio.prop('checked', true).trigger('change');
				var $card = $radio.closest('.ap-trigger-card');
				if ($card.length && $card[0].scrollIntoView) {
					$card[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
					$card.addClass('ap-pulse-once');
					setTimeout(function () { $card.removeClass('ap-pulse-once'); }, 1500);
				}
				$banner.slideUp(180, function () { $banner.remove(); });
			}
		});

		$banner.on('click', '.ap-trigger-recommend__dismiss', function () {
			try { sessionStorage.setItem('cartcue_recommend_dismissed', '1'); } catch (e) {}
			$banner.slideUp(180, function () { $banner.remove(); });
		});

		// Auto-hide on first trigger selection (whatever they pick).
		$(document).one('change', 'input[name="trigger_slug"]', function () {
			$banner.fadeOut(180, function () { $banner.remove(); });
		});

		// Honour same-session dismiss.
		try {
			if (sessionStorage.getItem('cartcue_recommend_dismissed') === '1') { $banner.hide(); }
		} catch (e) {}
	});

})(jQuery);
