(function ($) {
	'use strict';

	var rsmButtonsAdmin = window.rsmsparkButtonsAdmin;
	var debounceTimer;

	function debounce(fn, wait) {
		return function () {
			var args = arguments;
			clearTimeout(debounceTimer);
			debounceTimer = setTimeout(function () {
				fn.apply(null, args);
			}, wait || 200);
		};
	}

	function collectConfig() {
		var $form = $('#rsm-buttons-builder-form');
		if (!$form.length) {
			return {};
		}
		var data = {};
		$form.find('[name^="rsm_button["]').each(function () {
			var name = (this.name.match(/rsm_button\[([^\]]+)\]/) || [])[1];
			if (!name) {
				return;
			}
			if (this.type === 'checkbox') {
				data[name] = this.checked ? '1' : '';
			} else if (this.type === 'radio') {
				if (this.checked) {
					data[name] = this.value;
				}
			} else {
				data[name] = $(this).val();
			}
		});
		return data;
	}

	function updatePreview() {
		var $preview = $('#rsm-buttons-live-preview');
		if (!$preview.length || typeof rsmButtonsAdmin === 'undefined') {
			return;
		}

		$.post(rsmButtonsAdmin.ajaxUrl, {
			action: 'rsmspark_buttons_preview',
			nonce: rsmButtonsAdmin.nonce,
			config: collectConfig()
		}).done(function (response) {
			if (response && response.success && response.data && response.data.html) {
				$preview.html(response.data.html);
			}
		});
	}

	function initColorPickers() {
		$('.rsm-color-picker').wpColorPicker({
			change: debounce(updatePreview, 150),
			clear: debounce(updatePreview, 150)
		});
	}

	function copyShortcode(text) {
		if (navigator.clipboard && navigator.clipboard.writeText) {
			navigator.clipboard.writeText(text);
			window.alert(rsmButtonsAdmin.i18n.copied);
			return;
		}
		window.prompt(rsmButtonsAdmin.i18n.copied, text);
	}

	function setIconValue(slug) {
		$('#rsmspark_button_icon').val(slug || '').trigger('change');
		$('#rsmspark_button_icon_custom').val(slug || '');
		$('#rsmspark_buttons_icon_picker .rsm-buttons-icon-choice').removeClass('is-selected');
		$('#rsmspark_buttons_icon_picker .rsm-buttons-icon-choice[data-icon="' + slug + '"]').addClass('is-selected');
		toggleIconColorRow();
	}

	function toggleIconColorRow() {
		var hasIcon = !!($('#rsmspark_button_icon').val() || '').trim() || !!($('#rsmspark_button_icon_image_id').val() || '').trim();
		$('.rsm-buttons-icon-color-row').toggle(hasIcon);
	}

	function toggleIconPanels() {
		var iconType = $('input[name="rsm_button[icon_type]"]:checked').val() || 'sprite';
		$('.rsm-buttons-icon-sprite-panel').toggle(iconType === 'sprite' || iconType === 'dashicon');
		$('.rsm-buttons-icon-image-panel').toggle(iconType === 'image');
		toggleIconColorRow();
	}

	function filterIconChoices() {
		var query = String($('#rsmspark_buttons_icon_search').val() || '').toLowerCase().trim();
		var category = String($('#rsmspark_buttons_icon_category').val() || '');

		$('#rsmspark_buttons_icon_picker .rsm-buttons-icon-choice').each(function () {
			var $btn = $(this);
			var slug = String($btn.data('icon') || '').toLowerCase();
			var label = String($btn.attr('title') || '').toLowerCase();
			var btnCategory = String($btn.data('category') || '');
			var matchesCategory = !category || btnCategory === category || slug === '';
			var matchesQuery = !query || slug.indexOf(query) !== -1 || label.indexOf(query) !== -1 || slug === '';
			$btn.toggle(matchesCategory && matchesQuery);
		});
	}

	function toggleGradientRows() {
		var isGradient = $('#rsmspark_button_bg_type').val() === 'gradient';
		$('.rsm-buttons-gradient-row').toggle(isGradient);
		$('.rsm-buttons-color-grid--solid').toggleClass('is-muted', isGradient);
	}

	function toggleLinkFields() {
		var linkType = $('input[name="rsm_button[link_type]"]:checked').val() || 'url';
		$('.rsm-buttons-link-url').toggle(linkType === 'url');
		$('.rsm-buttons-link-post').toggle(linkType === 'post');
	}

	function syncLinkTypeFromPostSelect() {
		var postId = String($('#rsmspark_button_link_post_id').val() || '');
		if (postId) {
			$('input[name="rsm_button[link_type]"][value="post"]').prop('checked', true);
		}
	}

	function initIconPicker() {
		var $picker = $('#rsmspark_buttons_icon_picker');
		if (!$picker.length) {
			return;
		}

		if (!$picker.children().length && typeof rsmButtonsAdmin !== 'undefined') {
			var icons = Array.isArray(rsmButtonsAdmin.icons) ? rsmButtonsAdmin.icons : [];
			icons.forEach(function (icon) {
				var slug = icon.slug || '';
				var $btn = $('<button type="button" class="rsm-buttons-icon-choice"></button>');
				$btn.attr('data-icon', slug);
				$btn.attr('data-category', icon.category || 'general');
				$btn.attr('title', icon.label || slug || rsmButtonsAdmin.i18n.iconNone);
				if (slug) {
					$btn.append('<svg class="rsm-buttons-icon-choice__svg" aria-hidden="true" focusable="false"><use href="#rsm-icon-' + slug + '"></use></svg>');
				} else {
					$btn.append('<span class="rsm-buttons-icon-choice__none-label" aria-hidden="true">—</span>');
				}
				$picker.append($btn);
			});
		}

		$('#rsmspark_buttons_icon_search, #rsmspark_buttons_icon_category').on('input change', filterIconChoices);

		setIconValue($('#rsmspark_button_icon').val() || '');

		$picker.on('click', '.rsm-buttons-icon-choice', function () {
			setIconValue($(this).data('icon') || '');
			updatePreview();
		});

		$('#rsmspark_button_icon_custom').on('input', debounce(function () {
			var slug = String($(this).val() || '')
				.replace(/^dashicons[\s-]*/i, '')
				.replace(/[^a-z0-9_-]/gi, '');
			setIconValue(slug);
			updatePreview();
		}, 200));

		filterIconChoices();
	}

	function setColorPickerValue($field, value) {
		if (!$field || !$field.length) {
			return;
		}
		$field.val(value);
		if ($field.hasClass('rsm-color-picker') && $field.data('wp-wpColorPicker')) {
			$field.wpColorPicker('color', value);
		}
		$field.trigger('change');
	}

	function applyPresetConfig(config) {
		if (!config || typeof config !== 'object') {
			return;
		}

		Object.keys(config).forEach(function (key) {
			var value = config[key];
			var $field = $('[name="rsm_button[' + key + ']"]');
			if (!$field.length) {
				return;
			}

			if ($field.is(':radio')) {
				$field.filter('[value="' + value + '"]').prop('checked', true).trigger('change');
			} else if ($field.is(':checkbox')) {
				$field.prop('checked', !!value && value !== '0').trigger('change');
			} else if ($field.hasClass('rsm-color-picker')) {
				setColorPickerValue($field.first(), value);
			} else {
				$field.val(value).trigger('change');
			}
		});

		if (config.icon) {
			setIconValue(config.icon);
		}

		toggleIconPanels();
		toggleGradientRows();
		toggleLinkFields();
		$('#rsmspark_button_shape').trigger('change');

		var $colorsCard = $('.rsm-buttons-color-grid--solid').closest('.rsm-buttons-card');
		if ($colorsCard.length) {
			$colorsCard.get(0).scrollIntoView({ behavior: 'smooth', block: 'nearest' });
		}

		updatePreview();
	}

	function initIconImagePicker() {
		var frame;

		function applyIconImage(attachment) {
			$('#rsmspark_button_icon_image_id').val(attachment.id || '').trigger('change');
			$('#rsmspark_buttons_icon_image_preview').html(
				attachment.url ? '<img src="' + attachment.url + '" alt="" />' : ''
			);
			updatePreview();
			toggleIconColorRow();
		}

		function openImagePicker() {
			var mediaOpts = {
				title: rsmButtonsAdmin.i18n.selectImage,
				button: { text: rsmButtonsAdmin.i18n.selectImage },
				library: { type: 'image' },
				multiple: false
			};

			if (typeof window.rsmMediaOpenFrame === 'function') {
				window.rsmMediaOpenFrame(mediaOpts, function (attachments) {
					if (attachments && attachments[0]) {
						applyIconImage(attachments[0]);
					}
				});
				return;
			}

			if (typeof wp === 'undefined' || !wp.media) {
				return;
			}

			if (frame) {
				frame.open();
				return;
			}

			frame = wp.media(mediaOpts);
			frame.on('select', function () {
				applyIconImage(frame.state().get('selection').first().toJSON());
			});
			frame.open();
		}

		$('#rsmspark_buttons_pick_icon_image').on('click', function (event) {
			event.preventDefault();
			openImagePicker();
		});

		$('#rsmspark_buttons_remove_icon_image').on('click', function (event) {
			event.preventDefault();
			$('#rsmspark_button_icon_image_id').val('').trigger('change');
			$('#rsmspark_buttons_icon_image_preview').empty();
			updatePreview();
			toggleIconColorRow();
		});
	}

	function initPresets() {
		$('#rsmspark_buttons_apply_preset').on('click', function () {
			var slug = $('#rsmspark_buttons_style_preset').val();
			if (!slug) {
				return;
			}

			var presets = Array.isArray(rsmButtonsAdmin.presets) ? rsmButtonsAdmin.presets : [];
			var preset = presets.find(function (item) {
				return item.slug === slug;
			});

			if (!preset) {
				return;
			}

			if (!window.confirm(rsmButtonsAdmin.i18n.applyPreset)) {
				return;
			}

			applyPresetConfig(preset.config || {});
		});
	}

	$(function () {
		if ($('.rsm-color-picker').length) {
			initColorPickers();
		}

		initIconPicker();
		initIconImagePicker();
		initPresets();

		$(document).on('change', '.rsm-buttons-icon-type', function () {
			toggleIconPanels();
			updatePreview();
		});

		$('#rsmspark_button_bg_type').on('change', function () {
			toggleGradientRows();
		});

		$(document).on('input change', '.rsm-buttons-live', debounce(updatePreview, 200));

		$(document).on('click', '.rsm-buttons-copy-shortcode', function () {
			copyShortcode($(this).data('shortcode') || '');
		});

		$('#rsmspark_button_link_post_id').on('change', function () {
			syncLinkTypeFromPostSelect();
			toggleLinkFields();
			updatePreview();
		});

		$('#rsmspark_button_shape').on('change', function () {
			var isPill = $(this).val() === 'pill';
			$('.rsm-buttons-radius-row').toggle(!isPill);
		}).trigger('change');

		$('input[name="rsm_button[border_radius]"]').on('input', function () {
			$(this).siblings('.rsm-buttons-range-value').text($(this).val());
		});

		$(document).on('change', '.rsm-buttons-link-type', function () {
			if ($('input[name="rsm_button[link_type]"]:checked').val() === 'url') {
				$('#rsmspark_button_link_post_id').val('');
			}
			toggleLinkFields();
		});
		syncLinkTypeFromPostSelect();
		toggleLinkFields();
		toggleIconPanels();
		toggleGradientRows();
		toggleIconColorRow();
	});
})(jQuery);
