/* =============================================================================
 * Storzen — Stock Scarcity (frontend)
 *
 * Watches WooCommerce's `found_variation` event on the variable product
 * form. When the user picks a variation that's at or below the configured
 * low-stock threshold, swaps in the pre-rendered bar markup. Resets when
 * the form is cleared.
 *
 * Variation → HTML map is built server-side and injected via
 * wp_localize_script (window.szStockScarcity.variations).
 *
 * Depends on: jQuery (already shipped with WP).
 * ========================================================================== */
(function ($) {
	'use strict';

	// If the localize call didn't run (no qualifying variations), bail.
	if (typeof szStockScarcity === 'undefined' || !szStockScarcity.variations) {
		return;
	}

	var map = szStockScarcity.variations;

	$(function () {
		var $wrap = $('.sz-ss-wrap');
		if (!$wrap.length) { return; }

		// WC fires this with the resolved variation object.
		$(document).on('found_variation', 'form.variations_form', function (event, variation) {
			if (!variation || !variation.variation_id) { return; }

			var data = map[String(variation.variation_id)];
			if (data && data.html) {
				$wrap.html(data.html).prop('hidden', false);
			} else {
				$wrap.empty().prop('hidden', true);
			}
		});

		// User cleared the variation selection — hide the message.
		$(document).on('reset_data', 'form.variations_form', function () {
			$wrap.empty().prop('hidden', true);
		});
	});

	// Public namespace (debugging).
	window.StorzenStockScarcity = { map: map };

})(jQuery);
