/* global cartcueAdmin, jQuery */
(function ($) {
	'use strict';

	var cfg = window.cartcueAdmin || {};
	var tl = cfg.timelineStrings || {};

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

	function firstActionIndex() {
		var v = null;
		$('#ap-actions-list .ap-action-card').each(function () {
			var idx = $(this).data('index');
			if (idx === undefined || idx === null) {
				return;
			}
			if (v === null) {
				v = idx;
			}
		});
		return v !== null ? String(v) : '0';
	}

	function readSequenceSteps() {
		var steps = [];
		$('#ap-sequence-builder .ap-sequence-step').each(function () {
			var $row = $(this);
			steps.push({
				action_index: $row.find('.ap-seq-action').val() || firstActionIndex(),
				delay: parseInt($row.find('.ap-seq-delay').val(), 10) || 0,
				delay_unit: $row.find('.ap-seq-unit').val() || 'hours'
			});
		});
		if (steps.length) {
			return steps;
		}
		if ($.isArray(window.apSequenceInitial) && window.apSequenceInitial.length) {
			return window.apSequenceInitial.slice();
		}
		return [];
	}

	function getActionCard(actionIndex) {
		return $('#ap-actions-list .ap-action-card[data-index="' + actionIndex + '"]');
	}

	function isBuilderBodyEmpty(body, bodyMode) {
		if (!body) {
			return true;
		}
		var isBuilder = bodyMode === 'builder' || body.charAt(0) === '[' || body.charAt(0) === '{';
		if (!isBuilder) {
			return false;
		}
		try {
			var decoded = JSON.parse(body);
			if (Array.isArray(decoded)) {
				return decoded.length === 0;
			}
			if (decoded && Array.isArray(decoded.blocks)) {
				return decoded.blocks.length === 0;
			}
			return true;
		} catch (e) {
			return bodyMode === 'builder';
		}
	}

	function getActionCompleteness(actionIndex) {
		var $card = getActionCard(actionIndex);
		if (!$card.length) {
			return { ok: false, reasons: [t('missingActionCard', 'Action not found')] };
		}

		var slug = $card.find('.ap-action-type').val() || '';
		if (!slug) {
			return { ok: false, reasons: [t('missingActionType', 'Choose an action type')] };
		}

		var reasons = [];

		if (slug === 'send_email') {
			var subject = $.trim($card.find('[name$="[subject]"]').val() || '');
			var body = $.trim($card.find('textarea[name$="[body]"]').val() || '');
			var bodyMode = $card.find('[name$="[body_mode]"]').val() || '';
			if (!subject) {
				reasons.push(t('missingSubject', 'Subject line required'));
			}
			if (!body || isBuilderBodyEmpty(body, bodyMode)) {
				reasons.push(t('missingBody', 'Email content required'));
			}
		} else if (slug === 'send_sms' || slug === 'send_whatsapp') {
			var message = $.trim($card.find('textarea[name$="[message]"]').val() || '');
			if (!message) {
				reasons.push(t('missingMessage', 'Message required'));
			}
		}

		return { ok: reasons.length === 0, reasons: reasons };
	}

	function getReferencedActionIndices() {
		var seq = readSequenceSteps();
		if (seq.length) {
			var seen = {};
			seq.forEach(function (step) {
				seen[String(step.action_index != null ? step.action_index : firstActionIndex())] = true;
			});
			return Object.keys(seen);
		}
		return [firstActionIndex()];
	}

	function getIncompleteTimelineSteps() {
		var items = [];
		var seq = readSequenceSteps();

		if (!seq.length) {
			var ai = firstActionIndex();
			var c = getActionCompleteness(ai);
			if (!c.ok) {
				items.push({
					nodeId: 'action-' + ai,
					label: t('openingMessage', 'Opening message'),
					reasons: c.reasons
				});
			}
			return items;
		}

		seq.forEach(function (step, i) {
			var ai = String(step.action_index != null ? step.action_index : firstActionIndex());
			var c = getActionCompleteness(ai);
			if (!c.ok) {
				items.push({
					nodeId: 'seq-' + i + '-action',
					label: t('messageStep', 'Message %1$d').replace('%1$d', String(i + 1)),
					reasons: c.reasons
				});
			}
		});

		return items;
	}

	function isActionStepComplete() {
		var indices = getReferencedActionIndices();
		if (!indices.length) {
			return false;
		}
		for (var i = 0; i < indices.length; i++) {
			if (!getActionCompleteness(indices[i]).ok) {
				return false;
			}
		}
		return true;
	}

	function firstActionStepError() {
		var items = getIncompleteTimelineSteps();
		if (!items.length) {
			return null;
		}
		var first = items[0];
		return first.label + ': ' + first.reasons.join(', ');
	}

	function hasIncompleteContent() {
		return getIncompleteTimelineSteps().length > 0;
	}

	window.apPlayValidation = {
		getActionCompleteness: getActionCompleteness,
		getIncompleteTimelineSteps: getIncompleteTimelineSteps,
		isActionStepComplete: isActionStepComplete,
		firstActionStepError: firstActionStepError,
		hasIncompleteContent: hasIncompleteContent,
		getReferencedActionIndices: getReferencedActionIndices
	};
})(jQuery);
