/**
 * Storzen — Variation Swatches (admin term editor)
 *
 * Wires up the color picker and image uploader on WooCommerce attribute term
 * edit screens. Idempotent: handlers attach only if the fields are present.
 */
(function ($) {
	'use strict';

	$(function () {
		var I18N = window.StorzenSwatchAdminI18n || {
			chooseImage: 'Choose swatch image',
			useImage:    'Use this image'
		};

		// ── Color picker ──────────────────────────────────────────────
		var $color = $('.storzen-swatch-color-field');
		if ($color.length && $.fn.wpColorPicker) {
			$color.wpColorPicker();
		}

		// ── Media uploader ────────────────────────────────────────────
		var mediaFrame = null;

		$(document).on('click', '.storzen-swatch-image-upload', function (e) {
			e.preventDefault();
			var $btn     = $(this);
			var $input   = $('#storzen-swatch-image');
			var $preview = $btn.siblings('.storzen-swatch-image-preview').first();
			if (!$preview.length) {
				$preview = $btn.parent().find('.storzen-swatch-image-preview').first();
			}
			var $remove  = $btn.siblings('.storzen-swatch-image-remove').first();

			// Reuse the frame so we don't recreate it on every click.
			if (!mediaFrame) {
				mediaFrame = wp.media({
					title: I18N.chooseImage,
					button: { text: I18N.useImage },
					library: { type: 'image' },
					multiple: false
				});

				mediaFrame.on('select', function () {
					var att = mediaFrame.state().get('selection').first().toJSON();
					$input.val(att.id);

					var thumbUrl = (att.sizes && att.sizes.thumbnail && att.sizes.thumbnail.url) || att.url;
					$preview.html(
						'<img src="' + thumbUrl + '" alt="" style="max-width:80px;height:auto;border-radius:6px;border:1px solid #ddd;display:block;margin-bottom:8px">'
					);
					$remove.show();
				});
			}

			mediaFrame.open();
		});

		// ── Remove image ─────────────────────────────────────────────
		$(document).on('click', '.storzen-swatch-image-remove', function (e) {
			e.preventDefault();
			var $btn = $(this);
			$('#storzen-swatch-image').val('');
			var $preview = $btn.siblings('.storzen-swatch-image-preview').first();
			if (!$preview.length) {
				$preview = $btn.parent().find('.storzen-swatch-image-preview').first();
			}
			$preview.empty();
			$btn.hide();
		});
	});
})(jQuery);
