/* =============================================================================
 * Storzen — Wishlist (frontend)
 * ========================================================================== */
(function ($) {
	'use strict';

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

	var WL = {
		list:        (szWishlist.list || []).map(String),
		nonce:       szWishlist.nonce,
		ajaxUrl:     szWishlist.ajaxUrl,
		wishlistUrl: szWishlist.wishlistUrl || '',
		shareableUrl: szWishlist.shareableUrl || '',
		i18n:        szWishlist.i18n || {},

		init: function () {
			this.bindHeartButtons();
			this.bindPageActions();
			this.refreshUiState();
		},

		// ── Heart button (add / remove) ─────────────────────────────────
		bindHeartButtons: function () {
			var self = this;
			$(document).on('click', '.sz-wishlist-btn', function (e) {
				e.preventDefault();
				var $btn = $(this);
				var pid  = String($btn.data('product-id'));
				if (!pid) return;
				var isAdded = $btn.hasClass('is-added');
				self.toggle(pid, !isAdded, $btn);
			});
		},

		toggle: function (productId, add, $btn) {
			var self = this;
			var action = add ? 'storzen_wishlist_add' : 'storzen_wishlist_remove';

			if ($btn) { $btn.prop('disabled', true); }

			$.post(this.ajaxUrl, {
				action:     action,
				nonce:      this.nonce,
				product_id: productId
			})
				.done(function (res) {
					if (res && res.success && res.data) {
						self.list = (res.data.list || []).map(String);

						// Pop animation on add
						if (add && $btn) {
							$btn.addClass('is-just-added');
							window.setTimeout(function () {
								$btn.removeClass('is-just-added');
							}, 500);
						}

						self.refreshUiState();

						// If wishlist page is currently open and server sent a fresh
						// rendered page, replace the existing wrap with it.
						if (res.data.page !== undefined) {
							self.replaceWishlistPage(res.data.page);
						}
					} else if (res && res.data && res.data.message) {
						self.toast(res.data.message);
					}
				})
				.fail(function () {
					self.toast(self.i18n.error || 'Could not update wishlist.');
				})
				.always(function () {
					if ($btn) { $btn.prop('disabled', false); }
				});
		},

		// ── Wishlist page interactions ──────────────────────────────────
		bindPageActions: function () {
			var self = this;

			// Remove from item card
			$(document).on('click', '[data-sz-wishlist-remove]', function (e) {
				e.preventDefault();
				var pid = String($(this).data('sz-wishlist-remove'));
				self.toggle(pid, false, null);
			});

			// Clear all
			$(document).on('click', '[data-sz-wishlist-clear]', function (e) {
				e.preventDefault();
				$.post(self.ajaxUrl, {
					action: 'storzen_wishlist_clear',
					nonce:  self.nonce
				})
					.done(function (res) {
						if (res && res.success && res.data) {
							self.list = [];
							self.refreshUiState();
							if (res.data.page !== undefined) {
								self.replaceWishlistPage(res.data.page);
							}
						}
					});
			});

			// Share button (copies URL to clipboard)
			$(document).on('click', '[data-sz-wishlist-share]', function (e) {
				e.preventDefault();
				if (!self.shareableUrl) { return; }
				self.copyToClipboard(self.shareableUrl)
					.then(function () {
						self.toast(self.i18n.shareCopied || 'Link copied!', 'success');
					})
					.catch(function () {
						self.toast(self.i18n.shareError || 'Could not copy link.');
					});
			});
		},

		// ── Replace the wishlist page wrapper after AJAX changes ────────
		replaceWishlistPage: function (html) {
			var $wrap = $('.sz-wishlist-wrap').first();
			if (!$wrap.length) { return; }
			// The server-rendered HTML wraps in .sz-wishlist-wrap or
			// .sz-wishlist-empty. Parse + replace cleanly.
			var $new = $(html);
			if ($new.length) {
				$wrap.replaceWith($new);
			}
		},

		// ── Cross-page UI state sync ────────────────────────────────────
		refreshUiState: function () {
			var inList = this.list;

			$('.sz-wishlist-btn').each(function () {
				var $btn = $(this);
				var pid  = String($btn.data('product-id'));
				var isIn = inList.indexOf(pid) !== -1;
				$btn.toggleClass('is-added', isIn);
				$btn.attr('aria-pressed', isIn ? 'true' : 'false');
				var label = isIn ? (szWishlist.i18n.remove || 'Remove from wishlist')
				                 : (szWishlist.i18n.add    || 'Add to wishlist');
				$btn.attr('aria-label', label).attr('title', label);
			});

			// Update counter shortcode instances.
			var count = inList.length;
			$('[data-sz-wishlist-count]').each(function () {
				$(this).text(count).attr('data-empty', count === 0 ? '1' : '0');
			});
		},

		// ── Clipboard helper with legacy fallback ───────────────────────
		copyToClipboard: function (text) {
			if (navigator.clipboard && navigator.clipboard.writeText) {
				return navigator.clipboard.writeText(text);
			}
			// Fallback for non-HTTPS / older browsers.
			return new Promise(function (resolve, reject) {
				try {
					var $ta = $('<textarea>').css({ position: 'fixed', top: '-1000px' }).val(text);
					$('body').append($ta);
					$ta[0].select();
					var ok = document.execCommand('copy');
					$ta.remove();
					if (ok) { resolve(); } else { reject(); }
				} catch (e) {
					reject(e);
				}
			});
		},

		// ── Minimal toast ───────────────────────────────────────────────
		toast: function (msg, type) {
			var cls = 'sz-wishlist-toast';
			if (type === 'success') { cls += ' sz-wishlist-toast--success'; }
			var $t = $('<div role="alert"></div>').addClass(cls).text(msg);
			$('body').append($t);
			window.setTimeout(function () {
				$t.fadeOut(300, function () { $(this).remove(); });
			}, 2600);
		}
	};

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

	// Public namespace for debugging
	window.StorzenWishlist = WL;

})(jQuery);
