/* =============================================================================
 * Storzen — Compare Products (frontend)
 *
 * Behavior:
 *   • Click Compare button on a product card → AJAX add to compare list
 *   • If product already added → AJAX remove
 *   • Sticky bar count auto-updates after every change
 *   • "Open" button → either opens modal (with table loaded via AJAX) or
 *     navigates to the configured compare page
 *   • "Clear" → AJAX clear all + refresh state
 *   • Remove buttons inside the compare table → AJAX remove + refresh
 *   • All buttons reflect added/removed state across the whole DOM
 * ========================================================================== */
(function ($) {
	'use strict';

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

	var CMP = {
		list:        szCompare.list || [],
		nonce:       szCompare.nonce,
		ajaxUrl:     szCompare.ajaxUrl,
		max:         szCompare.maxProducts || 4,
		openIn:      szCompare.openIn || 'modal',
		comparePageUrl: szCompare.comparePageUrl || '',
		i18n:        szCompare.i18n || {},

		init: function () {
			this.bindButtons();
			this.bindStickyBar();
			this.bindModal();
			this.refreshUiState();
		},

		// ── Compare button (add / remove) ────────────────────────────────
		bindButtons: function () {
			var self = this;
			$(document).on('click', '.sz-compare-btn', function (e) {
				e.preventDefault();
				var $btn = $(this);
				var pid  = parseInt($btn.data('product-id'), 10);
				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_compare_add' : 'storzen_compare_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 || [];
						self.refreshUiState();
						// If modal was open + we removed/cleared, refresh its body
						if (res.data.table !== undefined) {
							self.updateModalBody(res.data.table);
						}
					} else if (res && res.data && res.data.message) {
						self.toast(res.data.message);
						// Re-sync — server is authoritative.
						if (res.data.list) {
							self.list = res.data.list;
							self.refreshUiState();
						}
					}
				})
				.fail(function () {
					self.toast(self.i18n.error || 'Could not update compare list.');
				})
				.always(function () {
					if ($btn) $btn.prop('disabled', false);
				});
		},

		// ── Sticky bar ───────────────────────────────────────────────────
		bindStickyBar: function () {
			var self = this;

			// "Open" → modal or page navigation
			$(document).on('click', '[data-sz-compare-open]', function (e) {
				e.preventDefault();
				if (self.openIn === 'page' && self.comparePageUrl) {
					window.location.href = self.comparePageUrl;
				} else {
					self.openModal();
				}
			});

			// "Clear"
			$(document).on('click', '[data-sz-compare-clear]', function (e) {
				e.preventDefault();
				$.post(self.ajaxUrl, {
					action: 'storzen_compare_clear',
					nonce:  self.nonce,
				})
					.done(function (res) {
						if (res && res.success && res.data) {
							self.list = [];
							self.refreshUiState();
							if (res.data.table !== undefined) {
								self.updateModalBody(res.data.table);
							}
						}
					});
			});

			// Remove buttons inside the table
			$(document).on('click', '[data-sz-compare-remove]', function (e) {
				e.preventDefault();
				var pid = parseInt($(this).data('sz-compare-remove'), 10);
				if (!pid) return;
				self.toggle(pid, false, null);
			});
		},

		// ── Modal ────────────────────────────────────────────────────────
		bindModal: function () {
			var self = this;
			$(document).on('click', '[data-sz-compare-close]', function (e) {
				e.preventDefault();
				self.closeModal();
			});
			$(document).on('keydown', function (e) {
				if (e.key === 'Escape') {
					var $m = $('#sz-compare-modal');
					if ($m.hasClass('is-open')) {
						self.closeModal();
					}
				}
			});
		},

		openModal: function () {
			var self = this;
			var $modal = $('#sz-compare-modal');
			if (!$modal.length) {
				// Modal not in DOM (sticky_bar disabled or open_in=page) — fallback to navigation.
				if (self.comparePageUrl) {
					window.location.href = self.comparePageUrl;
				}
				return;
			}

			// Fetch fresh table HTML
			$.post(self.ajaxUrl, {
				action: 'storzen_compare_table',
				nonce:  self.nonce,
			})
				.done(function (res) {
					if (res && res.success && res.data) {
						self.updateModalBody(res.data.table);
					}
				});

			$modal.addClass('is-open').attr('aria-hidden', 'false');
			$('body').addClass('sz-compare-modal-open');
		},

		closeModal: function () {
			$('#sz-compare-modal').removeClass('is-open').attr('aria-hidden', 'true');
			$('body').removeClass('sz-compare-modal-open');
		},

		updateModalBody: function (html) {
			var $body = $('#sz-compare-modal [data-sz-compare-body]');
			if ($body.length) {
				$body.html(html);
			}
		},

		// ── State sync across the page ───────────────────────────────────
		refreshUiState: function () {
			var inList = this.list.map(String);

			// Update every Compare button on the page
			$('.sz-compare-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 labelAdd   = $btn.data('label-add');
				var labelAdded = $btn.data('label-added');
				$btn.find('.sz-compare-btn__label').text(isIn ? labelAdded : labelAdd);
			});

			// Update sticky bar count + empty state
			var count = this.list.length;
			$('[data-sz-compare-count]').text(count);
			var $bar = $('.sz-compare-bar');
			if (count === 0) {
				$bar.addClass('is-empty');
			} else {
				$bar.removeClass('is-empty');
			}
		},

		// ── Minimal toast (no library) ───────────────────────────────────
		toast: function (msg) {
			var $t = $('<div class="sz-compare-toast" role="alert"></div>').text(msg);
			$('body').append($t);
			window.setTimeout(function () {
				$t.fadeOut(300, function () { $(this).remove(); });
			}, 2800);
		},
	};

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

	// Public namespace for debugging
	window.StorzenCompare = CMP;

})(jQuery);
