/**
 * CartCue — Unified builder interactions (v1.5).
 *
 * Drives the single-page builder (play-edit-unified.php). Replaces the
 * stepper-driven guided-stepper.js when data-editor-layout="unified".
 *
 * Responsibilities:
 *  - Save-bar status routing: which button sets status="active|paused".
 *  - Inline validation on submit: scroll to first issue, no modal nags.
 *  - Timing-pill state sync (custom panel toggle, recommended-pill auto-select).
 *  - Trigger settings panel show/hide based on selected trigger.
 *  - Name sync between header inline input and the hidden form input.
 *  - "Send to past matches" guard: prompt with audience count before fire.
 */
(function ($) {
	'use strict';

	var $form = $('#ap-play-form[data-editor-layout="unified"]');
	if (!$form.length) { return; }

	var cfg = window.cartcueAdmin || {};

	// -------------------------------------------------------------------
	// Name sync — inline header input <-> hidden form input.
	// -------------------------------------------------------------------
	$('#ap-uni-name-inline').on('input', function () {
		$('#ap-play-name').val($(this).val());
	});

	// -------------------------------------------------------------------
	// Save-bar routing — set status before submitting.
	// -------------------------------------------------------------------
	$form.on('click', '[data-set-status]', function (e) {
		var status = $(this).attr('data-set-status');
		$('#ap-status-input').val(status);

		// Status pill in header shows what's about to happen.
		$('[data-status-display]').text(status === 'active' ? 'Active' : 'Draft');
	});

	// -------------------------------------------------------------------
	// Inline validation. WP-post-editor pattern: write anything, hit save,
	// get told what's missing.
	// -------------------------------------------------------------------
	$form.on('submit', function (e) {
		// Skip validation for "Save draft" — drafts can be incomplete.
		var goingActive = $('#ap-status-input').val() === 'active';
		if (!goingActive) { return; }

		var issues = [];

		// 1. Must have a name.
		if (!$.trim($('#ap-play-name').val() || '')) {
			issues.push({ scrollTo: '#ap-uni-name-inline', msg: 'Give this automation a name.' });
		}

		// 2. Must have a trigger.
		if (!$('input[name="trigger_slug"]:checked').length) {
			issues.push({ scrollTo: '#ap-uni-when', msg: 'Choose what starts this automation.' });
		}

		// 3. At least one action with a type.
		var hasAction = false;
		$('#ap-actions-list .ap-action-card').each(function () {
			if ($(this).find('.ap-action-type').val()) { hasAction = true; }
		});
		if (!hasAction) {
			issues.push({ scrollTo: '#ap-uni-then', msg: 'Pick what should happen.' });
		}

		// 4. If sending email, need a subject.
		$('#ap-actions-list .ap-action-card').each(function () {
			if ($(this).find('.ap-action-type').val() === 'send_email') {
				var $subj = $(this).find('input[name*="[subject]"]').first();
				if ($subj.length && !$.trim($subj.val() || '')) {
					issues.push({ scrollTo: $subj, msg: 'Email needs a subject line.' });
					return false;
				}
			}
		});

		if (issues.length) {
			e.preventDefault();
			showInlineErrors(issues);
			return false;
		}

		// 5. "Send to past matches" guard.
		if ($('#ap-past-matches-checkbox').is(':checked')) {
			var audCount = parseInt($('[data-audience-count]').text().replace(/[^0-9]/g, ''), 10) || 0;
			if (audCount > 50) {
				var ok = window.confirm(
					'This will email ' + audCount + ' customers RIGHT NOW. ' +
					'You cannot undo a send. Continue?'
				);
				if (!ok) { e.preventDefault(); return false; }
			}
		}
	});

	function showInlineErrors(issues) {
		$('.ap-uni-error').remove();
		var first = issues[0];

		var $target = typeof first.scrollTo === 'string' ? $(first.scrollTo) : first.scrollTo;
		if (!$target.length) { return; }

		var $err = $('<div class="ap-uni-error" role="alert"></div>').text(first.msg);
		$target.first().closest('.ap-uni-block, .ap-uni-header, .ap-field-row').before($err);

		// Scroll into view, with a little headroom.
		var top = $target.first().offset().top - 120;
		$('html,body').animate({ scrollTop: top }, 200);
	}

	// Clear errors on user activity.
	$form.on('input change click', function () {
		$('.ap-uni-error').fadeOut(180, function () { $(this).remove(); });
	});

	// -------------------------------------------------------------------
	// Trigger settings panel — show only the settings group for the
	// currently-selected trigger.
	// -------------------------------------------------------------------
	$form.on('change', 'input[name="trigger_slug"]', function () {
		var slug = $(this).val();
		$('.ap-tsettings-group').removeClass('is-visible');
		$('.ap-tsettings-group[data-trigger="' + slug + '"]').addClass('is-visible');

		// Move the recommended timing-pill ring if we have a per-trigger recommendation.
		var rec = (cfg.playUx && cfg.playUx.timingRecommendations) || {};
		if (rec[slug]) {
			$('.ap-timing-pill').removeClass('is-recommended');
			$('.ap-timing-pill').filter(function () {
				return $(this).data('type') === rec[slug].type
					&& String($(this).data('value')) === String(rec[slug].v || 0)
					&& ($(this).data('unit') || '') === (rec[slug].u || '');
			}).addClass('is-recommended');
		}

		// Pulse the trigger card so the click feels solid.
		var $card = $(this).closest('.ap-trigger-card');
		$('.ap-trigger-card').removeClass('is-selected');
		$card.addClass('is-selected ap-pulse-once');
		setTimeout(function () { $card.removeClass('ap-pulse-once'); }, 1500);
	});

	// -------------------------------------------------------------------
	// Timing pills.
	// -------------------------------------------------------------------
	$form.on('click', '.ap-timing-pill', function () {
		var $pill = $(this);
		if ($pill.hasClass('ap-timing-pill--custom-toggle')) {
			$('#ap-timing-custom-panel').toggleClass('is-open');
			$('.ap-timing-pill').removeClass('is-selected');
			$pill.addClass('is-selected');
			return;
		}

		$('.ap-timing-pill').removeClass('is-selected');
		$pill.addClass('is-selected');
		$('#ap-timing-custom-panel').removeClass('is-open');

		$('#ap-timing-type').val($pill.data('type'));
		$('#ap-delay-value').val($pill.data('value') || 0);
		$('#ap-delay-unit').val($pill.data('unit') || '');
	});

	$('#ap-custom-timing-btn').on('click', function () {
		var val = parseInt($('#ap-custom-val').val(), 10) || 1;
		var unit = $('#ap-custom-unit').val();
		$('#ap-timing-type').val('delay');
		$('#ap-delay-value').val(val);
		$('#ap-delay-unit').val(unit);

		$('.ap-timing-pill').removeClass('is-selected');
		$('.ap-timing-pill--custom-toggle').addClass('is-selected');
	});

	// -------------------------------------------------------------------
	// Frequency pills.
	// -------------------------------------------------------------------
	$form.on('click', '.ap-freq-pill', function () {
		var $pill = $(this);
		$('.ap-freq-pill').removeClass('is-selected');
		$pill.addClass('is-selected');

		if ($pill.data('custom') === 'cooldown') {
			var c = parseInt($('#ap-cooldown-val').val(), 10) || 30;
			$('#ap-max-runs').val(0);
			$('#ap-cooldown-days').val(c);
		} else {
			$('#ap-max-runs').val($pill.data('max-runs') || 0);
			$('#ap-cooldown-days').val(0);
		}
	});

	$('#ap-cooldown-val').on('input', function () {
		var c = parseInt($(this).val(), 10) || 30;
		$('#ap-cooldown-days').val(c);
	});

})(jQuery);
