(function(){
	var l10n = window.kramarSwatchL10n || {};

	document.addEventListener('click', function(e) {
		var btn = e.target.closest('.kramar-upload-swatch-image');
		if (!btn) return;
		var wrap = btn.closest('.kramar-swatch-image-wrap');
		var frame = wp.media({
			title: l10n.selectTitle || '',
			button: { text: l10n.useImage || '' },
			multiple: false
		});
		frame.on('select', function() {
			var att = frame.state().get('selection').first().toJSON();
			wrap.querySelector('.kramar-swatch-image-id').value = att.id;
			var preview = wrap.querySelector('.kramar-swatch-image-preview');
			preview.src = att.sizes && att.sizes.thumbnail ? att.sizes.thumbnail.url : att.url;
			preview.style.display = '';
			wrap.querySelector('.kramar-remove-swatch-image').style.display = '';
		});
		frame.open();
	});

	document.addEventListener('click', function(e) {
		var btn = e.target.closest('.kramar-remove-swatch-image');
		if (!btn) return;
		var wrap = btn.closest('.kramar-swatch-image-wrap');
		wrap.querySelector('.kramar-swatch-image-id').value = '';
		var preview = wrap.querySelector('.kramar-swatch-image-preview');
		preview.src = '';
		preview.style.display = 'none';
		btn.style.display = 'none';
	});

	document.addEventListener('DOMContentLoaded', function() {
		var addForm = document.getElementById('addtag');
		if (!addForm) return;
		addForm.addEventListener('reset', function() {
			var wrap = addForm.querySelector('.kramar-swatch-image-wrap');
			if (!wrap) return;
			wrap.querySelector('.kramar-swatch-image-id').value = '';
			var preview = wrap.querySelector('.kramar-swatch-image-preview');
			if (preview) { preview.src = ''; preview.style.display = 'none'; }
			var removeBtn = wrap.querySelector('.kramar-remove-swatch-image');
			if (removeBtn) removeBtn.style.display = 'none';
		});
	});
})();
