(function ($) {
	'use strict';

	var STEPS = ['trigger', 'timing', 'action', 'review'];
	var cur = 0;
	var done = new Set();
	var $form = $('#ap-play-form');
	var i18n = (window.cartcueAdmin && window.cartcueAdmin.guided) || {};

	function t(key, fallback) {
		return i18n[key] || fallback;
	}

	if (!$form.length) {
		return;
	}

	function stepIndex(step) {
		return STEPS.indexOf(step);
	}

	function playId() {
		return String($('input[name="play_id"]').val() || '0');
	}

	function isNewPlay() {
		return playId() === '0';
	}

	function storageKey() {
		return 'cartcue_guided_step_' + playId();
	}

	function maxDoneIndex() {
		if (!done.size) {
			return -1;
		}
		return Math.max.apply(null, Array.from(done));
	}
	function isTriggerStepComplete() {
		return !!$('input[name="trigger_slug"]:checked').val() && $.trim($('#ap-play-name').val() || '').length > 0;
	}
	function getVisibleNameField() {
		var $reviewName = $('#ap-play-name-review');
		if ($reviewName.length) {
			return $reviewName;
		}
		return $('#ap-play-name');
	}
	function isTimingStepComplete() {
		if (!isNewPlay()) {
			return true;
		}
		return !!$('#ap-timing-type').data('user-modified') || $('.ap-timing-pill.is-selected').length > 0;
	}
	function isActionStepComplete() {
		if (window.apPlayValidation && typeof window.apPlayValidation.isActionStepComplete === 'function') {
			return window.apPlayValidation.isActionStepComplete();
		}
		var actionType = $('#ap-actions-list .ap-action-type').first().val();
		if (!actionType) {
			return false;
		}
		var $subject = $('input[name*="[subject]"]').first();
		return actionType !== 'send_email' || !$subject.length || $.trim($subject.val() || '').length > 0;
	}
	function reconcileDoneState() {
		if (!isTriggerStepComplete()) {
			done.delete(0);
		}
		if (!isTimingStepComplete()) {
			done.delete(1);
		}
		if (!isActionStepComplete()) {
			done.delete(2);
		}
	}

	function syncChecklist() {
		if (typeof window.apSyncSetupChecklist === 'function') {
			window.apSyncSetupChecklist();
		}
	}

	function getPreviewFields() {
		if (typeof window.apGetPreviewFields === 'function') {
			return window.apGetPreviewFields();
		}
		var subject = $('input[name*="[subject]"]').first().val() || '';
		var body = $('textarea[name*="[body]"]').first().val() || '';
		var triggerSlug = $('input[name="trigger_slug"]:checked').val() || '';
		return { subject: subject, body: body, trigger_slug: triggerSlug };
	}

	function loadReviewPreview() {
		var fields = getPreviewFields();
		var $iframe = $('#ap-review-preview-iframe');
		if (!$iframe.length || !fields.body) {
			return;
		}

		$('[data-review-part="preview-subject"]').text(fields.subject || '(no subject)');
		$iframe.attr('srcdoc', '<p style="font-family:sans-serif;padding:20px;color:#666">' + t('loading', 'Loading…') + '</p>');

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

		$.post(cartcueAdmin.ajaxUrl, {
			action: 'cartcue_preview_email',
			nonce: cartcueAdmin.nonces.preview_email,
			subject: fields.subject,
			body: fields.body,
			trigger_slug: fields.trigger_slug,
			inline: 1
		}).done(function (r) {
			if (r.success && r.data) {
				$('[data-review-part="preview-subject"]').text(r.data.subject || fields.subject);
				$iframe.attr('srcdoc', r.data.html || '');
			}
		});
	}

	function syncReview() {
		var $rv = $('#ap-review-step');
		if (!$rv.length) {
			return;
		}

		var triggerCfg = (window.cartcueAdmin && window.cartcueAdmin.triggers) || {};
		var slug = $('input[name="trigger_slug"]:checked').val() || '';
		var when = slug && triggerCfg[slug] ? triggerCfg[slug].sentence : slug || t('when_fallback', 'something happens');
		var timingType = $('#ap-timing-type').val();
		var wait = timingType === 'delay'
			? (($('#ap-delay-value').val() || '1') + ' ' + ($('#ap-delay-unit').val() || 'hours'))
			: (timingType === 'schedule_time'
				? t('at_time', 'at ') + ($('#ap-schedule-time').val() || '09:00')
				: t('immediately', 'immediately'));
		var subject = $('input[name*="[subject]"]').first().val()
			|| (window.apCartCuePlayUx && window.apCartCuePlayUx.getStorySegmentText($('#ss-then')))
			|| '—';
		var name = $.trim($('#ap-play-name').val() || '') || '—';
		var ruleCount = $('#ap-rules-list .ap-rule-row').length;
		var filters = ruleCount
			? ruleCount + ' ' + t('filters', 'filter(s)')
			: t('no_filters', 'Everyone (no filters)');
		var seqCount = $('#ap-sequence-builder .ap-sequence-step').length;
		var sequence = seqCount
			? seqCount + ' ' + t('followups', 'follow-up step(s)')
			: t('no_followups', 'None');

		$rv.find('[data-review-part="when"]').text(when);
		$rv.find('[data-review-part="wait"]').text(wait);
		$rv.find('[data-review-part="then"]').text(subject);
		$rv.find('[data-review-part="name"]').text(name);
		$rv.find('[data-review-part="subject"]').text(subject);
		$rv.find('[data-review-part="filters"]').text(filters);
		$rv.find('[data-review-part="sequence"]').text(sequence);

		loadReviewPreview();

		if (window.apSequenceTimeline && typeof window.apSequenceTimeline.refresh === 'function') {
			window.apSequenceTimeline.refresh();
		}
	}

	function flashError($el, msg) {
		if (!$el || !$el.length) {
			return;
		}

		$('.ap-guided-error').remove();
		$('[aria-invalid="true"]').removeAttr('aria-invalid');
		var $err = $('<div class="ap-guided-error" role="alert"></div>').text(msg);
		$el.after($err);
		$el.attr('aria-invalid', 'true');

		if ($el[0] && typeof $el[0].scrollIntoView === 'function') {
			$el[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
		}
	}

	function validate(stepIndexToValidate) {
		if (stepIndexToValidate === 0) {
			if (!$('input[name="trigger_slug"]:checked').val()) {
				flashError($('#ap-trigger-grid'), t('err_trigger', 'Please choose a trigger first.'));
				return false;
			}
		}

		if (stepIndexToValidate === 2) {
			if (!$('#ap-actions-list .ap-action-type').first().val()) {
				flashError($('#ap-actions-list').first(), t('err_action', 'Choose what this automation should do.'));
				return false;
			}
			if (window.apPlayValidation && typeof window.apPlayValidation.firstActionStepError === 'function') {
				var stepErr = window.apPlayValidation.firstActionStepError();
				if (stepErr) {
					var $target = $('#ap-timeline-editor').length ? $('#ap-timeline-editor') : $('#ap-actions-list').first();
					flashError($target, stepErr);
					return false;
				}
			} else {
				var $subject = $('input[name*="[subject]"]').first();
				if ($subject.length && !$.trim($subject.val() || '')) {
					flashError($subject, t('err_subject', 'A subject line is required.'));
					return false;
				}
			}
		}
		if (stepIndexToValidate === 1 && !isTimingStepComplete()) {
			flashError($('.ap-timing-pills').first(), t('err_timing', 'Choose a timing option before continuing.'));
			return false;
		}

		return true;
	}

	function setButtonState() {
		$('.ap-guided-prev').prop('disabled', cur === 0);
		var prevLabels = [
			t('prev_generic', 'Back'),
			t('prev_trigger', '← When'),
			t('prev_timing', '← Wait'),
			t('prev_action', '← Then')
		];
		$('.ap-guided-prev').text(prevLabels[cur] || prevLabels[0]);
		var nextLabels = [
			t('next_timing', 'Next: set the wait →'),
			t('next_email', 'Next: write the message →'),
			t('next_review', 'Next: settings & activate →'),
			t('save_play', 'Save & Activate')
		];
		$('.ap-guided-next').text(cur === STEPS.length - 1 ? nextLabels[3] : nextLabels[cur]);
	}

	function show(stepIndexToShow) {
		cur = stepIndexToShow;
		reconcileDoneState();

		if (cur === 3) {
			$form.trigger('cartcue:before-review');
			syncReview();
		}

		$form.attr('data-guided-step', STEPS[cur]);
		$form.trigger('cartcue:guided-step-changed', [STEPS[cur]]);

		$('[data-guided-step-panel]').each(function () {
			var panelStep = stepIndex($(this).data('guidedStepPanel'));
			$(this)
				.toggleClass('ap-guided-panel--active', panelStep === cur)
				.toggleClass('ap-guided-panel--hidden', panelStep !== cur);
		});

		if (window.apSequenceTimeline && typeof window.apSequenceTimeline.onGuidedStepChange === 'function') {
			window.apSequenceTimeline.onGuidedStepChange();
		}

		$('.ap-guided-stepper__item').each(function () {
			var s = stepIndex($(this).data('guidedStep'));
			var isDone = done.has(s) && s !== cur;
			$(this)
				.toggleClass('is-active', s === cur)
				.toggleClass('is-done', isDone)
				.attr('aria-current', s === cur ? 'step' : null)
				.attr('aria-disabled', s > maxDoneIndex() + 1 ? 'true' : null)
				.prop('disabled', s > maxDoneIndex() + 1)
				.attr('tabindex', s > maxDoneIndex() + 1 ? '-1' : '0');

			var $num = $(this).find('.ap-guided-stepper__num');
			if (isDone) {
				$num.html('<i class="ti ti-check" style="font-size:10px" aria-hidden="true"></i>');
			} else {
				$num.text(String(s + 1));
			}
		});

		setButtonState();
		syncChecklist();

		try {
			sessionStorage.setItem(storageKey(), String(cur));
		} catch (e) {}

		var top = $form.offset().top - 80;
		$('html,body').animate({ scrollTop: top }, 160);
	}

	$(document).on('click', '.ap-guided-next', function () {
		if (cur < STEPS.length - 1) {
			if (!validate(cur)) {
				return;
			}
			done.add(cur);
			show(cur + 1);
			return;
		}

		for (var step = 0; step < STEPS.length - 1; step++) {
			if (!validate(step)) {
				if (cur !== step) {
					show(step);
				}
				return;
			}
		}
		var finalName = $.trim($('#ap-play-name').val() || '');
		if (!finalName) {
			if (cur !== 3) {
				show(3);
			}
			flashError($('#ap-play-name-review'), t('err_name', 'Give this automation a name.'));
			return;
		}
		$form.trigger('submit');
	});

	$(document).on('click', '.ap-guided-prev', function () {
		if (cur > 0) {
			show(cur - 1);
		}
	});

	$(document).on('click', '.ap-guided-stepper__item', function () {
		var s = stepIndex($(this).data('guidedStep'));
		if (s > cur && !validate(cur)) {
			return;
		}
		if (s <= maxDoneIndex() + 1) {
			if (s > cur) {
				done.add(cur);
			}
			show(s);
		}
	});

	$(document).on('click', '.ap-story-segment--clickable', function () {
		if (!$form.hasClass('ap-guided-mode')) {
			return;
		}
		var target = $(this).data('scrollTarget');
		var $panel = $(target).closest('[data-guided-step-panel]');
		if ($panel.length) {
			var s = stepIndex($panel.data('guidedStepPanel'));
			if (s >= 0) {
				show(s);
			}
		}
	});

	$(document).on('click', '.ap-review-preview-refresh', function () {
		loadReviewPreview();
	});

	$form.on('cartcue:before-review', syncReview);

	var initial = stepIndex($form.data('guidedStep') || 'trigger');
	done = new Set();

	if (isNewPlay()) {
		try {
			sessionStorage.removeItem(storageKey());
		} catch (e) {}
		if (initial < 0) {
			initial = 0;
		}
		for (var pre = 0; pre < initial; pre++) {
			done.add(pre);
		}
	} else {
		try {
			var stored = parseInt(sessionStorage.getItem(storageKey()), 10);
			if (!isNaN(stored) && stored >= 0 && stored < STEPS.length) {
				initial = stored;
				for (var d = 0; d < stored; d++) {
					done.add(d);
				}
			}
		} catch (e) {}
	}

	if ($form.hasClass('ap-guided-mode')) {
		cur = initial >= 0 ? initial : 0;
		show(cur);
	}
}(jQuery));
