(function ($) {
	'use strict';

	var cfg = window.skynsmfaAdmin || {};
	var iconPaths = (cfg && cfg.iconPaths && typeof cfg.iconPaths === 'object') ? cfg.iconPaths : {};
	var i18n = (cfg && cfg.i18n && typeof cfg.i18n === 'object') ? cfg.i18n : {};

	function appearanceForm() {
		return document.querySelector('.skynsmfa-appearance-form');
	}

	function field(id) {
		var form = appearanceForm();
		if (form) {
			return form.querySelector('#' + id);
		}
		return document.getElementById(id);
	}

	function val(id) {
		var el = field(id);
		return el ? el.value.trim() : '';
	}

	function labelVal(id, fallback) {
		var el = field(id);
		if (!el) {
			return fallback || '';
		}
		var text = el.value.trim();
		if (text) {
			return text;
		}
		var placeholder = (el.getAttribute('placeholder') || '').trim();
		return placeholder || fallback || '';
	}

	function updatePreviewLabels(labelAdd, labelAdded) {
		document.querySelectorAll('.skynsmfa-preview-text .skynsmfa-btn-text').forEach(function (textSpan) {
			var btn = textSpan.closest('.skynsmfa-preview-text');
			if (!btn) {
				return;
			}
			textSpan.textContent = btn.classList.contains('is-added') ? labelAdded : labelAdd;
		});
	}

	function setBtnStyle(btn, prop, value) {
		if (value) {
			btn.style.setProperty(prop, value, 'important');
		} else {
			btn.style.removeProperty(prop);
		}
	}

	function clearBtnStyles(btn) {
		['background', 'color', 'border-color', 'border-style', 'border-width', 'border-radius'].forEach(function (prop) {
			btn.style.removeProperty(prop);
		});
	}

	function toggleAppearanceSections() {
		var mode = val('skynsmfa_display_mode') || 'button';
		var showText = (mode === 'button' || mode === 'icon_text');
		var showIcon = (mode === 'icon' || mode === 'icon_text');
		var showIconPreview = (mode === 'icon');
		var iconPanel = document.querySelector('.skynsmfa-appearance-section--icon');
		var textPanel = document.querySelector('.skynsmfa-appearance-section--text-button');
		var iconTextField = document.querySelector('.skynsmfa-field-block--icon-text-only');
		var iconPreviewStage = document.querySelector('.skynsmfa-appearance-preview__stage--icon');
		var textPreviewStage = document.querySelector('.skynsmfa-appearance-preview__stage--text');

		if (iconPanel) {
			iconPanel.classList.toggle('is-hidden', !showIcon);
		}
		if (textPanel) {
			textPanel.classList.toggle('is-hidden', !showText);
		}
		if (iconTextField) {
			iconTextField.classList.toggle('is-hidden', mode !== 'icon_text');
		}
		if (iconPreviewStage) {
			iconPreviewStage.classList.toggle('is-hidden', !showIconPreview);
		}
		if (textPreviewStage) {
			textPreviewStage.classList.toggle('is-hidden', !showText);
		}
	}

	function iconPath(style) {
		if (iconPaths[style]) {
			return iconPaths[style];
		}
		return iconPaths.heart || '';
	}

	function getCustomIconUrl() {
		var id = val('skynsmfa_icon_custom_id');
		var img = document.querySelector('.skynsmfa-custom-icon__preview');
		if (id && id !== '0' && img && img.getAttribute('src')) {
			return img.getAttribute('src');
		}
		return '';
	}

	function svgMarkup(d, size) {
		return '<svg class="skynsmfa-preview-svg" viewBox="0 0 24 24" aria-hidden="true" focusable="false" style="width:' + size + 'px;height:' + size + 'px;">' + (d ? '<path d="' + d + '" />' : '') + '</svg>';
	}

	function imgMarkup(url, size) {
		var safeUrl = encodeURI(url).replace(/"/g, '%22');
		return '<img class="skynsmfa-wishlist-icon--custom" src="' + safeUrl + '" alt="" style="width:' + size + 'px;height:' + size + 'px;object-fit:contain;" />';
	}

	function showFigure(el, visible) {
		var fig = el.closest('.skynsmfa-preview-item');
		if (fig) {
			fig.style.display = visible ? '' : 'none';
		}
	}

	function updatePreview() {
		var mode = val('skynsmfa_display_mode') || 'button';
		var style = val('skynsmfa_icon_style') || 'heart';
		var customUrl = getCustomIconUrl();
		var iconPos = val('skynsmfa_icon_text_position') || 'before';
		var size = parseInt(val('skynsmfa_icon_size'), 10);
		if (!isFinite(size) || size <= 0) {
			size = 24;
		}
		var shape = val('skynsmfa_icon_shape') || 'none';
		var fill = val('skynsmfa_icon_fill') || 'outline';
		var btnRadius = val('skynsmfa_btn_radius');
		var useCustomBtn = true;

		var iconColor = val('skynsmfa_icon_color') || 'currentColor';
		var activeColor = val('skynsmfa_icon_active_color') || '#e74c3c';
		var hoverColor = val('skynsmfa_icon_hover_color') || '#e74c3c';

		var btnBg = val('skynsmfa_btn_bg_color');
		var btnText = val('skynsmfa_btn_text_color');
		var btnBorder = val('skynsmfa_btn_border_color');
		var btnActiveBg = val('skynsmfa_btn_active_bg_color');
		var btnActiveText = val('skynsmfa_btn_active_text_color');

		var labelAdd = labelVal('skynsmfa_label_add', i18n.labelAdd || 'Add to wishlist');
		var labelAdded = labelVal('skynsmfa_label_added', i18n.labelAdded || 'Already in wishlist');

		updatePreviewLabels(labelAdd, labelAdded);
		toggleAppearanceSections();

		var d = iconPath(style);
		var showIcons = (mode === 'icon');
		var showText = (mode === 'button' || mode === 'icon_text');

		document.querySelectorAll('.skynsmfa-preview-icon').forEach(function (btn) {
			showFigure(btn, showIcons);
			if (!showIcons) {
				return;
			}
			var isAdded = btn.classList.contains('is-added');
			var isHover = btn.classList.contains('is-hover');
			var stateColor = isAdded ? activeColor : (isHover ? hoverColor : iconColor);

			var radius = '0';
			if (shape === 'rounded') {
				radius = '6px';
			} else if (shape === 'circle') {
				radius = '50%';
			}
			btn.style.borderRadius = radius;
			btn.style.color = stateColor;

			btn.innerHTML = customUrl ? imgMarkup(customUrl, size) : svgMarkup(d, size);
			if (!customUrl) {
				var svg = btn.querySelector('.skynsmfa-preview-svg');
				if (svg) {
					var filled = isAdded || (fill === 'filled');
					svg.style.fill = filled ? stateColor : 'none';
					svg.style.stroke = stateColor;
				}
			}
		});

		document.querySelectorAll('.skynsmfa-preview-text').forEach(function (btn) {
			var isHover = btn.classList.contains('is-hover');
			// Text buttons have no separate hover color, so only show the hover swatch for icon-only mode.
			showFigure(btn, showText && !isHover);
			if (!showText || isHover) {
				return;
			}
			var isAdded = btn.classList.contains('is-added');
			btn.classList.toggle('skynsmfa-btn-style-custom', useCustomBtn);
			if (useCustomBtn) {
				var bg = isAdded ? (btnActiveBg || btnBg) : btnBg;
				var textColor = isAdded ? (btnActiveText || btnText) : btnText;
				setBtnStyle(btn, 'background', bg);
				setBtnStyle(btn, 'color', textColor);
				setBtnStyle(btn, 'border-color', btnBorder);
				if (btnBorder) {
					setBtnStyle(btn, 'border-style', 'solid');
					setBtnStyle(btn, 'border-width', '1px');
				} else {
					btn.style.removeProperty('border-style');
					btn.style.removeProperty('border-width');
				}
				btn.style.borderRadius = (btnRadius !== '' && isFinite(parseInt(btnRadius, 10))) ? (parseInt(btnRadius, 10) + 'px') : '';
			} else {
				clearBtnStyles(btn);
			}

			var textSpan = btn.querySelector('.skynsmfa-btn-text');
			var existingIcon = btn.querySelector('.skynsmfa-btn-icon');
			if (existingIcon) {
				existingIcon.parentNode.removeChild(existingIcon);
			}
			btn.classList.remove('skynsmfa-has-icon', 'skynsmfa-icon-fill-filled');
			if (mode === 'icon_text') {
				btn.classList.add('skynsmfa-has-icon');
				btn.classList.toggle('skynsmfa-icon-fill-filled', fill === 'filled');
				var iconSpan = document.createElement('span');
				iconSpan.className = 'skynsmfa-btn-icon';
				iconSpan.setAttribute('aria-hidden', 'true');
				iconSpan.innerHTML = customUrl ? imgMarkup(customUrl, 16) : svgMarkup(d, 16);
				if (!customUrl) {
					var inlineSvg = iconSpan.querySelector('.skynsmfa-preview-svg');
					if (inlineSvg) {
						var iconFilled = isAdded || (fill === 'filled');
						inlineSvg.style.fill = iconFilled ? 'currentColor' : 'none';
						inlineSvg.style.stroke = 'currentColor';
					}
				}
				textSpan = btn.querySelector('.skynsmfa-btn-text');
				if (iconPos === 'after') {
					btn.appendChild(iconSpan);
				} else if (textSpan) {
					btn.insertBefore(iconSpan, textSpan);
				} else {
					btn.insertBefore(iconSpan, btn.firstChild);
				}
			}
		});
	}

	function initMediaUploader() {
		var selectBtn = document.querySelector('.skynsmfa-custom-icon__select');
		var removeBtn = document.querySelector('.skynsmfa-custom-icon__remove');
		var preview = document.querySelector('.skynsmfa-custom-icon__preview');
		var hidden = field('skynsmfa_icon_custom_id');
		if (!selectBtn || !hidden) {
			return;
		}

		var frame;
		selectBtn.addEventListener('click', function (e) {
			e.preventDefault();
			if (!window.wp || !window.wp.media) {
				return;
			}
			if (frame) {
				frame.open();
				return;
			}
			frame = window.wp.media({
				title: i18n.selectIcon || 'Select custom icon',
				button: { text: i18n.useIcon || 'Use this icon' },
				library: { type: 'image' },
				multiple: false
			});
			frame.on('select', function () {
				var attachment = frame.state().get('selection').first().toJSON();
				hidden.value = attachment.id;
				if (preview) {
					var url = attachment.url;
					if (attachment.sizes && attachment.sizes.thumbnail) {
						url = attachment.sizes.thumbnail.url;
					}
					preview.setAttribute('src', url);
					preview.removeAttribute('hidden');
				}
				if (removeBtn) {
					removeBtn.removeAttribute('hidden');
				}
				updatePreview();
			});
			frame.open();
		});

		if (removeBtn) {
			removeBtn.addEventListener('click', function (e) {
				e.preventDefault();
				hidden.value = '0';
				if (preview) {
					preview.setAttribute('src', '');
					preview.setAttribute('hidden', 'hidden');
				}
				removeBtn.setAttribute('hidden', 'hidden');
				updatePreview();
			});
		}
	}

	$(function () {
		var $appearanceForm = $('.skynsmfa-appearance-form');
		if (!$appearanceForm.length) {
			return;
		}

		var $colorFields = $appearanceForm.find('.skynsmfa-color-field');
		if ($.fn.wpColorPicker) {
			$colorFields.wpColorPicker({
				change: function () {
					setTimeout(updatePreview, 0);
				},
				clear: function () {
					setTimeout(updatePreview, 0);
				}
			});
		}

		$appearanceForm.on('input change', 'input, select', updatePreview);

		initMediaUploader();
		updatePreview();
	});
})(window.jQuery);
