/* =============================================================================
 * Storzen — Free Shipping Progress Bar (frontend)
 *
 * Light wrapper around WooCommerce's own cart-fragment system. The PHP side
 * registers the bar as a fragment, so WC auto-replaces it whenever the cart
 * changes. We only need to:
 *   1. Add a body class when a sticky bar is present (for layout offset)
 *   2. Re-trigger the fill animation from 0 → target after fragment refresh
 *
 * Depends on: jQuery (already shipped with WP).
 * ========================================================================== */
(function ($) {
	'use strict';

	var SZSB = {

		init: function () {
			this.applyStickyOffset();
			this.bindCartEvents();
			this.animateInitialFill();
		},

		/**
		 * Toggle body classes so themes / our CSS can push content down/up
		 * to make room for the sticky banner.
		 */
		applyStickyOffset: function () {
			var top    = document.querySelector('.sz-sb--sticky-top');
			var bottom = document.querySelector('.sz-sb--sticky-bottom');

			document.body.classList.toggle('sz-sb-has-sticky-top',    !!top);
			document.body.classList.toggle('sz-sb-has-sticky-bottom', !!bottom);
		},

		/**
		 * Listen to all the cart events WooCommerce dispatches and re-apply
		 * our sticky/animation hooks after fragments swap in fresh markup.
		 */
		bindCartEvents: function () {
			$(document.body).on(
				'wc_fragments_refreshed updated_cart_totals updated_wc_div',
				function () {
					SZSB.applyStickyOffset();
					SZSB.animateInitialFill();
				}
			);

			$(document.body).on('added_to_cart removed_from_cart', function () {
				SZSB.applyStickyOffset();
			});
		},

		/**
		 * Animate the progress fill from 0 → target percentage. We force a
		 * reflow between the two width values so the CSS transition fires.
		 *
		 * `data-szsb-animated` ensures we only do this once per bar element.
		 */
		animateInitialFill: function () {
			document.querySelectorAll('.sz-sb').forEach(function (bar) {
				// Skip if explicit no-animate variant.
				if (bar.classList.contains('sz-sb--no-animate')) { return; }

				var fill = bar.querySelector('.sz-sb__progress-fill');
				if (!fill || fill.dataset.szsbAnimated === '1') { return; }

				var target = parseFloat(bar.dataset.percentage) || 0;

				// Reset to 0 for the transition to register.
				fill.style.width = '0%';
				// Force reflow so the next width assignment animates.
				/* eslint-disable no-unused-expressions */
				fill.offsetWidth;
				/* eslint-enable no-unused-expressions */

				setTimeout(function () {
					fill.style.width = target + '%';
					fill.dataset.szsbAnimated = '1';
				}, 30);
			});
		}
	};

	$(function () { SZSB.init(); });

	// Public namespace (debugging / theme integrations).
	window.StorzenShippingBar = SZSB;

})(jQuery);
