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

	var cfg = window.cartcueAdmin || {};
	var actions = cfg.actions || {};
	var triggers = cfg.triggers || {};
	var playUx = cfg.playUx || {};
	var tagsPanelReturnFocus = null;

	function storyRefresh() {
		if (typeof window.apUpdateStory === 'function') {
			window.apUpdateStory();
		}
		if (window.apCartCuePlayUx) {
			window.apCartCuePlayUx.refresh();
		}
		renderTimelines();
	}

	function formatWaitPhrase() {
		if (window.apCartCuePlayUx && window.apCartCuePlayUx.formatDelayWait) {
			return window.apCartCuePlayUx.formatDelayWait();
		}
		var timingType = $('#ap-timing-type').val() || 'immediate';
		if ('delay' !== timingType) {
			return timingType === 'schedule_time'
				? ((playUx.atTime || 'at ') + ($('#ap-schedule-time').val() || '09:00'))
				: (playUx.immediately || 'immediately');
		}
		return ($('#ap-delay-value').val() || '1') + ' ' + ($('#ap-delay-unit').val() || 'hours');
	}

	function getTriggerLabel() {
		var slug = $('input[name="trigger_slug"]:checked').val() || '';
		return slug && triggers[slug] ? triggers[slug].sentence : (playUx.somethingHappens || 'Trigger');
	}

	function getActionLabelForIndex(actionIndex) {
		var slug = '';
		$('#ap-actions-list .ap-action-card').each(function () {
			if (String($(this).data('index')) === String(actionIndex)) {
				slug = $(this).find('.ap-action-type').val();
				return false;
			}
		});
		if (slug && actions[slug]) {
			return actions[slug].label;
		}
		return playUx.actionFallback || 'Action';
	}

	function renderTimelines() {
		if (typeof window.renderTimingTimeline === 'function') {
			window.renderTimingTimeline();
			return;
		}
	}

	function applyTimingRecommendation(slug) {
		var rec = (playUx.timingRecommendations || {})[slug];
		if (!rec) {
			return;
		}
		if ($('#ap-timing-type').data('user-modified')) {
			return;
		}
		$('.ap-timing-pill').find('.ap-timing-recommended').remove();
		$('.ap-timing-pill').removeClass('is-selected is-recommended');
		var $match = $('.ap-timing-pill').filter(function () {
			return $(this).data('type') === rec.type
				&& String($(this).data('value')) === String(rec.v || 0)
				&& ($(this).data('unit') || '') === (rec.u || '');
		}).first();
		if (!$match.length && 'schedule_time' === rec.type) {
			$match = $('.ap-timing-pill[data-type="schedule_time"]').first();
		}
		if ($match.length) {
			$('#ap-timing-type').data('auto-selecting', true);
			$match.addClass('is-recommended').trigger('click');
			$('#ap-timing-type').data('auto-selecting', false);

			$('.ap-timing-pill.is-selected').first().append(
				'<span class="ap-timing-recommended" style="font-size:10px;margin-left:6px;opacity:0.75;font-weight:500">recommended</span>'
			);
		}
	}

	function suggestPlayName(slug) {
		var $name = $('#ap-play-name');
		if (!$name.length) {
			return;
		}
		var suggested = (playUx.triggerNames || {})[slug];
		if (!suggested) {
			return;
		}

		var current = $.trim($name.val() || '');
		var wasAuto = $name.data('autofilled') === true;

		if (!current || wasAuto) {
			$name.val(suggested).data('autofilled', true);
			$('#ap-uni-name-inline').val(suggested);
			$('#ap-play-name-review').val(suggested);
			if (typeof window.apSyncSetupChecklist === 'function') {
				window.apSyncSetupChecklist();
			}
		}
	}

	function featuredActionSlugs() {
		if (cfg.featuredActions && cfg.featuredActions.length) {
			return cfg.featuredActions;
		}
		return Object.keys(actions);
	}

	function availableMessageSlugs() {
		var base = Array.isArray(cfg.messageActionSlugs) && cfg.messageActionSlugs.length
			? cfg.messageActionSlugs
			: ['send_email', 'send_sms', 'send_whatsapp'];
		return base.filter(function (slug) {
			return !!actions[slug];
		});
	}

	function buildActionInserterSlot(idx) {
		var label = (playUx.inserter && playUx.inserter.chooseAction) || 'Take action';
		var $slot = $('<div class="ap-action-inserter-slot"></div>').attr('data-card-index', idx);
		if (window.apActionInserter && typeof window.apActionInserter.buildTriggerButton === 'function') {
			$slot.append(window.apActionInserter.buildTriggerButton(label));
		} else {
			$slot.append(
				$('<button type="button" class="ap-btn ap-btn-ghost ap-action-inserter-trigger"></button>')
					.append('<span class="ap-action-inserter-trigger__icon" aria-hidden="true">+</span> ')
					.append(document.createTextNode(label))
			);
		}
		return $slot;
	}

	function hasActionInserter() {
		return window.apActionInserter && typeof window.apActionInserter.open === 'function';
	}

	function openActionInserterForCard($card, anchor) {
		if (!$card || !$card.length) {
			return;
		}
		var el = anchor || $card.find('.ap-action-inserter-trigger')[0];
		if (hasActionInserter() && el) {
			$card.find('.ap-action-type-grid').attr('hidden', 'hidden');
			window.apActionInserter.open(el, function (slug) {
				selectActionType($card, slug);
			});
			return;
		}
		$card.find('.ap-action-inserter-slot').attr('hidden', 'hidden');
		$card.find('.ap-action-type-grid').removeAttr('hidden');
		if ($card[0] && typeof $card[0].scrollIntoView === 'function') {
			$card[0].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
		}
	}

	function buildActionTypeGrid(idx) {
		var $grid = $('<div class="ap-action-type-grid"></div>');
		var icons = playUx.actionIcons || {};
		var messageSlugs = availableMessageSlugs();
		var slugs = Array.isArray(cfg.otherActionSlugs) && cfg.otherActionSlugs.length
			? cfg.otherActionSlugs
			: featuredActionSlugs().filter(function (slug) {
				return messageSlugs.indexOf(slug) === -1;
			});

		if (messageSlugs.length) {
			$grid.append(
				$('<button type="button" class="ap-action-type-card ap-action-type-card--message"></button>')
					.attr('data-action-group', 'message')
					.attr('data-message-slugs', messageSlugs.join(','))
					.attr('data-card-index', idx)
					.append($('<i class="ti ti-message" aria-hidden="true"></i>'))
					.append($('<span></span>').text(playUx.sendMessageLabel || 'Send a message'))
			);
		}

		slugs.forEach(function (slug) {
			if (!actions[slug]) {
				return;
			}
			var icon = icons[slug] || 'ti-bolt';
			var $btn = $('<button type="button" class="ap-action-type-card"></button>')
				.attr('data-action-slug', slug)
				.attr('data-card-index', idx)
				.append($('<i class="ti ' + icon + '" aria-hidden="true"></i>'))
				.append($('<span></span>').text(actions[slug].label));
			$grid.append($btn);
		});
		return $grid;
	}

	function setMessageChannelSelection($picker, slug) {
		if (!$picker || !$picker.length) {
			return;
		}
		var $buttons = $picker.find('.ap-message-channel-btn');
		if (!$buttons.length) {
			return;
		}

		$buttons.removeClass('is-selected').attr('aria-pressed', 'false');
		var $selected = slug ? $buttons.filter('[data-action-slug="' + slug + '"]').first() : $();
		if (!$selected.length) {
			$selected = $buttons.first();
		}
		$selected.addClass('is-selected').attr('aria-pressed', 'true');
	}

	function renderMessageChannelPicker($card, messageSlugs) {
		var $grid = $card.find('.ap-action-type-grid');
		if (!$grid.length || !messageSlugs.length) {
			return;
		}
		var $existing = $grid.find('.ap-message-channel-picker');
		if ($existing.length) {
			$existing.toggleClass('is-open');
			if ($existing.hasClass('is-open')) {
				setMessageChannelSelection($existing, $card.find('.ap-action-type').val() || '');
			}
			return;
		}
		var $picker = $('<div class="ap-message-channel-picker is-open"></div>');
		messageSlugs.forEach(function (slug) {
			var action = actions[slug];
			if (!action) {
				return;
			}
			$picker.append(
				$('<button type="button" class="ap-btn ap-btn-ghost ap-btn-sm ap-message-channel-btn"></button>')
					.attr('data-action-slug', slug)
					.attr('aria-pressed', 'false')
					.text(action.label)
			);
		});
		$grid.append($picker);
		setMessageChannelSelection($picker, $card.find('.ap-action-type').val() || '');
	}

	function selectActionType($card, slug) {
		var idx = $card.data('index');
		$card.addClass('ap-action-card--has-type');
		$card.toggleClass('ap-action-card--email', slug === 'send_email');
		$card.find('.ap-action-type').val(slug);
		$card.find('.ap-action-type-grid').attr('hidden', 'hidden');
		$card.find('.ap-action-inserter-slot').attr('hidden', 'hidden');
		$card.find('.ap-action-card__header').show();
		$card.find('.ap-action-type-label').text(actions[slug] ? actions[slug].label : slug);

		$card.find('.ap-action-type').val(slug).trigger('change');
		storyRefresh();
	}

	function syncSaveButtonLabel() {
		var status = $('#ap-status-input').val() || 'active';
		var $btn = $('#ap-save-submit');
		if (!$btn.length) {
			return;
		}
		var labels = playUx.saveLabels || {};
		var isNew = $('#ap-play-form').data('is-new') === 1 || $('#ap-play-form').data('is-new') === '1';
		var key = status === 'active'
			? (isNew ? 'active_new' : 'active_edit')
			: (isNew ? 'paused_new' : 'paused_edit');
		var txt = labels[key];
		if (!txt) {
			txt = status === 'active' ? (labels.active || labels.active_new || labels.active_edit) : (labels.paused || labels.paused_new || labels.paused_edit);
		}
		$btn.text(txt || 'Save ✓');
	}

	$(document).on('change', 'input[name="trigger_slug"]', function () {
		storyRefresh();
	});
	$(document).on('click', '.ap-trigger-card', function () {
		window.setTimeout(storyRefresh, 0);
	});

	$(document).on('click', '.ap-action-inserter-trigger', function (e) {
		e.preventDefault();
		var idx = $(this).closest('.ap-action-inserter-slot').data('cardIndex');
		var $card = idx !== undefined
			? $('#ap-actions-list .ap-action-card[data-index="' + idx + '"]')
			: $(this).closest('.ap-action-card');
		openActionInserterForCard($card, this);
	});

	$(document).on('click', '.ap-action-type-card', function () {
		var slug = $(this).data('actionSlug');
		var idx = $(this).data('cardIndex');
		var $card = $('#ap-actions-list .ap-action-card[data-index="' + idx + '"]');
		var group = $(this).data('actionGroup');
		if ($card.length && group === 'message') {
			var messageSlugs = String($(this).data('messageSlugs') || '')
				.split(',')
				.map(function (item) { return item.trim(); })
				.filter(Boolean);
			renderMessageChannelPicker($card, messageSlugs);
			return;
		}
		if ($card.length && slug) {
			selectActionType($card, slug);
		}
	});

	$(document).on('click', '.ap-message-channel-btn', function (e) {
		e.preventDefault();
		e.stopPropagation();
		var $btn = $(this);
		var slug = $btn.data('actionSlug');
		var $picker = $btn.closest('.ap-message-channel-picker');
		var $card = $btn.closest('.ap-action-card');
		setMessageChannelSelection($picker, slug);
		if ($card.length && slug) {
			selectActionType($card, slug);
		}
	});

	$(document).on('click', '.ap-change-action-type', function () {
		var $card = $(this).closest('.ap-action-card');
		var hasData = $card.find('.ap-action-fields :input').filter(function () {
			var $field = $(this);
			if ($field.is(':checkbox,:radio')) {
				return $field.is(':checked');
			}
			return String($field.val() || '').trim() !== '';
		}).length > 0;
		if (hasData && !window.confirm('Switch action type? Your current action content will be removed.')) {
			return;
		}
		$card.removeClass('ap-action-card--has-type ap-action-card--email');
		$card.find('.ap-action-type').val('');
		$card.find('.ap-action-fields').empty();
		$card.find('.ap-action-card__header').hide();
		$card.find('.ap-action-type-grid').attr('hidden', 'hidden');
		$card.find('.ap-message-channel-picker').remove();
		if (!$card.find('.ap-action-inserter-slot').length) {
			$card.prepend(buildActionInserterSlot($card.data('index')));
		}
		if (!$card.find('.ap-action-type-grid').length && !hasActionInserter()) {
			$card.find('.ap-action-inserter-slot').after(buildActionTypeGrid($card.data('index')));
		}
		$card.find('.ap-action-inserter-slot').removeAttr('hidden');
		storyRefresh();
		openActionInserterForCard($card, $card.find('.ap-action-inserter-trigger')[0]);
	});

	$(document).on('click', '#ap-add-action', function () {
		window.setTimeout(function () {
			var $card = $('#ap-actions-list .ap-action-card').last();
			if ($card.length && !$card.hasClass('ap-action-card--has-type')) {
				openActionInserterForCard($card, $card.find('.ap-action-inserter-trigger')[0]);
			}
			if (window.apSequenceTimeline) {
				if (typeof window.apSequenceTimeline.refresh === 'function') {
					window.apSequenceTimeline.refresh();
				}
				if ($card.length && typeof window.apSequenceTimeline.selectStep === 'function') {
					var idx = $card.data('index');
					if (idx !== undefined) {
						window.apSequenceTimeline.selectStep('action-' + idx);
					}
				}
			}
		}, 0);
	});

	$(document).on('click', '.ap-status-toggle__btn:not([disabled])', function () {
		var status = $(this).data('status');
		$('.ap-status-toggle__btn').removeClass('is-selected').attr('aria-pressed', 'false');
		$(this).addClass('is-selected').attr('aria-pressed', 'true');
		$('#ap-status-input').val(status);
		syncSaveButtonLabel();
	});

	$(document).on('click', '#ap-timing-add-followup', function () {
		var $wrap = $('#ap-timing-sequence-wrap');
		$wrap.addClass('is-expanded');
		$('#ap-sequence-body').addClass('is-open');
		$(this).attr('aria-expanded', 'true');
		if (!$('#ap-sequence-builder .ap-sequence-step').length) {
			$('#ap-add-sequence-step').trigger('click');
		}
	});

	function closeTagsPanel() {
		if (typeof window.apCloseTagsSlidePanel === 'function') {
			window.apCloseTagsSlidePanel();
			return;
		}
	}

	$(document).on('click', '[data-close-tags-panel]', function () {
		closeTagsPanel();
	});

	$(document).on('keydown', function (e) {
		var panel = document.getElementById('ap-tags-slide-panel');
		if (!panel || panel.hidden) {
			return;
		}
		if (e.key === 'Escape') {
			e.preventDefault();
			closeTagsPanel();
			return;
		}
		if (e.key !== 'Tab') {
			return;
		}
		var focusable = panel.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
		if (!focusable.length) {
			return;
		}
		var first = focusable[0];
		var last = focusable[focusable.length - 1];
		if (e.shiftKey && document.activeElement === first) {
			e.preventDefault();
			last.focus();
		} else if (!e.shiftKey && document.activeElement === last) {
			e.preventDefault();
			first.focus();
		}
	});

	$(document).on('click', '.ap-timing-pill, #ap-custom-timing-btn', function () {
		setTimeout(renderTimelines, 0);
	});

	$(document).on('change input', '#ap-sequence-builder :input, #ap-delay-value, #ap-delay-unit, #ap-schedule-time', function () {
		renderTimelines();
	});

	$(document).on('apActionInserterClose', function () {
		$('#ap-actions-list .ap-action-card').not('.ap-action-card--has-type').each(function () {
			var $card = $(this);
			$card.find('.ap-action-type-grid').attr('hidden', 'hidden');
			$card.find('.ap-action-inserter-slot').removeAttr('hidden');
		});
	});

	// Extend global action card builder when present.
	if (typeof window.apBuildActionCardOverride !== 'function') {
		window.apBuildActionCardOverride = function (idx) {
			var playId = parseInt($('input[name="play_id"]').val(), 10) || 0;
			var $card = $('<div class="ap-action-card"></div>')
				.attr('data-index', idx)
				.attr('data-play-id', playId);
			var $hidden = $('<input type="hidden" class="ap-action-type">').attr('name', 'actions[' + idx + '][type]').val('');
			var $hdrMain = $('<div class="ap-action-card__header-main"></div>')
				.append('<span class="ap-action-type-label"></span>')
				.append('<button type="button" class="ap-btn ap-btn-ghost ap-btn-sm ap-change-action-type">Change</button>');
			var $hdr = $('<div class="ap-action-card__header" style="display:none"></div>')
				.append($hdrMain)
				.append('<button type="button" class="ap-icon-btn ap-remove-action" aria-label="Remove action" title="Remove this action">✕</button>');
			$card.append($hidden, buildActionInserterSlot(idx));
			if (!hasActionInserter()) {
				$card.append(buildActionTypeGrid(idx));
				$card.find('.ap-action-type-grid').attr('hidden', 'hidden');
			}
			$card.append($hdr, $('<div class="ap-action-fields"></div>'));
			return $card;
		};
	}

	$(function () {
		syncSaveButtonLabel();
		renderTimelines();
		var slug = $('input[name="trigger_slug"]:checked').val();
		if (slug) { suggestPlayName(slug); }
		$('#ap-play-form').on('cartcue:before-review', renderTimelines);
	});
}(jQuery));
