(function ($) {
	'use strict';

	$(function () {
		$('.szp-import-card__img').on('error', function () {
			var ph = window.WcommeroProImport && WcommeroProImport.placeholderUrl;
			if (ph && this.src !== ph) {
				this.src = ph;
			}
		});
	});

	function filterCards(filter) {
		$('.szp-import-card').each(function () {
			var $card = $(this);
			var cat = $card.data('category') || 'other';
			if (filter === 'all' || cat === filter) {
				$card.show();
			} else {
				$card.hide();
			}
		});
	}

	$(document).on('click', '.szp-filter-pill', function () {
		var $btn = $(this);
		var f = $btn.data('filter') || 'all';
		$('.szp-filter-pill').removeClass('is-active');
		$btn.addClass('is-active');
		filterCards(f);
	});

	$(document).on('click', '.szp-import-btn', function () {
		var $btn = $(this);
		var id = $btn.data('template-id');
		if (!id || !window.WcommeroProImport) {
			return;
		}

		var $card = $btn.closest('.szp-import-card');
		var $msg = $card.find('.szp-import-card__msg');
		$btn.prop('disabled', true);
		$msg.removeClass('is-success is-error').text(WcommeroProImport.i18n.importing);

		$.post(
			WcommeroProImport.ajaxUrl,
			{
				action: WcommeroProImport.action,
				nonce: WcommeroProImport.nonce,
				template_id: id
			}
		)
			.done(function (res) {
				if (res.success && res.data) {
					$msg.addClass('is-success').text(WcommeroProImport.i18n.done);
					if (res.data.edit_url) {
						$msg.append(
							' <a href="' +
								res.data.edit_url +
								'">' +
								WcommeroProImport.i18n.edit +
								'</a>'
						);
					}

					// If the server flipped any widget toggles to make this
					// template render correctly, surface them so the merchant
					// understands what changed under the hood.
					if (res.data.enabled_toggles && res.data.enabled_toggles.length) {
						var note = $('<div class="szp-import-card__enabled"></div>');
						var heading = WcommeroProImport.i18n.enabledHeading || 'Auto-enabled widgets:';
						note.append($('<strong></strong>').text(heading));
						var ul = $('<ul></ul>');
						res.data.enabled_toggles.forEach(function (t) {
							ul.append($('<li></li>').text(t.label || t.key));
						});
						note.append(ul);
						$msg.after(note);
					}
				} else {
					var err =
						res.data && res.data.message
							? res.data.message
							: WcommeroProImport.i18n.error;
					$msg.addClass('is-error').text(err);
				}
			})
			.fail(function (xhr) {
				var err = WcommeroProImport.i18n.error;
				try {
					var json = xhr.responseJSON;
					if (json && json.data && json.data.message) {
						err = json.data.message;
					}
				} catch (e) {}
				$msg.addClass('is-error').text(err);
			})
			.always(function () {
				$btn.prop('disabled', false);
			});
	});
})(jQuery);
