(function ($) {
	'use strict';

	$(function () {
		function field(key) {
			return $('[name="dreamfast_cf_settings[' + key + ']"]');
		}

		function fieldValue(key, fallback) {
			var element = field(key);
			if (!element.length) {
				return fallback;
			}
			if (element.is(':radio')) {
				return element.filter(':checked').val() || fallback;
			}
			if (element.is(':checkbox')) {
				return element.filter(':checked').val() || fallback;
			}
			return element.val() || fallback;
		}

		function updateCartPreview() {
			var preview = $('.df-sf-preview-cart');
			if (!preview.length) {
				return;
			}

			var presets = window.dreamfastCfAdmin.cartPresets || {};
			var preset = presets[fieldValue('cart_preset', 'contrast')] || {};
			var icon = fieldValue('cart_button_icon', 'cart');
			var iconPosition = fieldValue('cart_button_icon_pos', 'before');
			var button = preview.find('.df-sf-preview-cart__button');

			preview.attr('data-style', fieldValue('cart_style', 'classic'));
			preview.css({
				backgroundColor: preset.bg || '#111111',
				color: preset.text || '#ffffff',
			});
			button.css({
				backgroundColor: preset.btn || '#ffffff',
				color: preset.btnText || '#111111',
				flexDirection: iconPosition === 'after' ? 'row-reverse' : 'row',
			});
			preview.find('.df-sf-preview-cart__icon').html((window.dreamfastCfAdmin.icons || {})[icon] || '');
		}

		function updateContactPreview() {
			var preview = $('.df-sf-preview-contact');
			if (!preview.length) {
				return;
			}

			var presets = window.dreamfastCfAdmin.contactPresets || {};
			var preset = presets[fieldValue('contact_preset', 'whatsapp')] || {};
			preview.attr('data-style', fieldValue('contact_style', 'circle'));
			preview.find('.df-sf-preview-contact__fab').css({
				backgroundColor: preset.bg || '#25D366',
				color: preset.icon || '#ffffff',
			});
			preview.find('.df-sf-preview-contact__tooltip')
				.text(fieldValue('contact_tooltip_text', 'Need help?'))
				.toggle(!!fieldValue('contact_tooltip_enabled', ''));
		}

		function updatePreviews() {
			updateCartPreview();
			updateContactPreview();

			var direction = fieldValue('preview_direction', 'auto');
			if (direction === 'auto') {
				direction = document.documentElement.getAttribute('dir') === 'rtl' ? 'rtl' : 'ltr';
			}
			$('.df-sf-admin-preview-canvas').attr('dir', direction);
		}

		$(document).on('change input', '.df-sf-form select, .df-sf-form input, .df-sf-form textarea', updatePreviews);
		updatePreviews();
	});
})(jQuery);
