/* =============================================================================
 * Storzen — Currency Switcher (frontend)
 *
 * Switching currency works by redirecting to ?szcur=CODE — PHP detects that
 * param early (priority 5 init), sets the cookie server-side, and all WC price
 * filters then run in the chosen currency. This avoids AJAX/cookie timing
 * issues on local/HTTP environments where Set-Cookie headers can be unreliable.
 * ========================================================================== */
(function ($) {
	'use strict';

	if (typeof szCurrency === 'undefined') { return; }

	var CUR = {
		active: szCurrency.active,

		init: function () {
			this.bindDropdown();
			this.bindButtons();
		},

		// ── Build redirect URL with ?szcur=CODE ──────────────────────────
		buildUrl: function (currency) {
			var url = window.location.href;
			// Remove any existing szcur param.
			url = url.replace(/([?&])szcur=[^&#]*/g, '$1').replace(/[?&]$/, '');
			var sep = url.indexOf('?') !== -1 ? '&' : '?';
			return url + sep + 'szcur=' + encodeURIComponent(currency);
		},

		// ── Dropdown <select> ────────────────────────────────────────────
		bindDropdown: function () {
			var self = this;
			$(document).on('change', '[data-sz-currency-select]', function () {
				var code = $(this).val();
				if (!code || code === self.active) { return; }
				self.switchTo(code);
			});
		},

		// ── Pill / list / flag buttons ───────────────────────────────────
		bindButtons: function () {
			var self = this;
			$(document).on('click', '[data-sz-currency]', function (e) {
				e.preventDefault();
				var code = $(this).data('sz-currency');
				if (!code || code === self.active) { return; }
				self.switchTo(String(code));
			});
		},

		// ── Perform the switch via URL redirect ──────────────────────────
		switchTo: function (currency) {
			$('[data-sz-currency-switcher]').css('opacity', '.65');
			window.location.href = this.buildUrl(currency);
		}
	};

	$(function () { CUR.init(); });
	window.StorzenCurrency = CUR;

})(jQuery);
