/* =============================================================================
 * Storzen — Cart Cross-Sell Popup
 *
 * Listens for WC's `added_to_cart` event, fetches suggestions for the just-
 * added product, and shows them in a modal.
 *
 * The "trigger" setting decides which event opens the modal:
 *   after_add_to_cart  — show right after WC's `added_to_cart` (default)
 *   before_checkout    — show when clicking "Proceed to Checkout" button
 *   cart_page_view     — show once on the cart page (sessionStorage flag)
 * ========================================================================== */
(function ($) {
	'use strict';

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

	var XS = {
		ajaxUrl:    szCrossSell.ajaxUrl,
		nonce:      szCrossSell.nonce,
		trigger:    szCrossSell.trigger || 'after_add_to_cart',
		i18n:       szCrossSell.i18n || {},

		init: function () {
			this.bindModal();

			switch (this.trigger) {
				case 'after_add_to_cart':
					this.bindAfterAddToCart();
					break;
				case 'before_checkout':
					this.bindBeforeCheckout();
					break;
				case 'cart_page_view':
					this.bindCartPageView();
					break;
			}
		},

		// ── Modal open/close ────────────────────────────────────────────
		bindModal: function () {
			var self = this;

			$(document).on('click', '[data-sz-xs-close]', function (e) {
				e.preventDefault();
				self.close();
			});
			$(document).on('keydown', function (e) {
				if (e.key === 'Escape' && $('#sz-xs-modal').hasClass('is-open')) {
					self.close();
				}
			});

			// Add-to-cart button INSIDE the modal — adds the suggestion via WC AJAX.
			$(document).on('click', '.sz-xs-item__atc', function (e) {
				e.preventDefault();
				var $btn = $(this);
				var pid  = parseInt($btn.data('product-id'), 10);
				if (!pid) return;
				self.addToCartFromModal(pid, $btn);
			});
		},

		open: function () {
			$('#sz-xs-modal').addClass('is-open').attr('aria-hidden', 'false');
			$('body').addClass('sz-xs-modal-open');
		},

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

		// ── Trigger: after_add_to_cart ──────────────────────────────────
		bindAfterAddToCart: function () {
			var self = this;

			// (1) Archive / shop loop — WC fires `added_to_cart` on AJAX add.
			$(document.body).on('added_to_cart', function (event, fragments, cart_hash, $button) {
				if (!$button || !$button.length) { return; }

				// Skip the modal's OWN add-to-cart button to prevent infinite recursion.
				if ($button.hasClass('sz-xs-item__atc')) { return; }

				var pid = parseInt($button.data('product_id') || $button.attr('data-product_id'), 10);
				if (!pid) { return; }

				self.fetchAndOpen(pid);
			});

			// (2) Single product page — the main ATC button submits the form and
			// reloads, so `added_to_cart` never fires. Intercept the submit,
			// remember the product, and open the modal on the next page load.
			$(document).on('submit', 'form.cart', function () {
				var $form = $(this);
				// Skip ajax-add variations handled by event (1) and modal buttons.
				if ($form.closest('.sz-xs-modal').length) { return; }

				var pid = parseInt(
					$form.find('[name="add-to-cart"]').val() ||
					$form.find('button[name="add-to-cart"]').val() ||
					$form.find('[name="product_id"]').val() ||
					0,
					10
				);
				if (!pid) { return; }

				try {
					window.sessionStorage.setItem('sz_xs_pending_pid', String(pid));
				} catch (err) { /* ignore */ }
			});

			// On load, if a product was just added via a single-product form
			// submit, open the modal for it once.
			this.maybeOpenPending();
		},

		// Open the modal for a product remembered from a single-product form submit.
		maybeOpenPending: function () {
			var self = this;
			var pid;
			try {
				pid = parseInt(window.sessionStorage.getItem('sz_xs_pending_pid'), 10);
			} catch (err) { pid = 0; }

			if (!pid) { return; }

			try { window.sessionStorage.removeItem('sz_xs_pending_pid'); } catch (err) { /* ignore */ }

			// Small delay so the page (and any theme cart UI) settles.
			window.setTimeout(function () { self.fetchAndOpen(pid); }, 700);
		},

		// ── Trigger: before_checkout ────────────────────────────────────
		bindBeforeCheckout: function () {
			var self = this;
			$(document).on('click', '.wc-proceed-to-checkout .checkout-button, a.checkout-button', function (e) {
				// Only show once per session.
				try {
					if (window.sessionStorage.getItem('sz_xs_seen_checkout') === '1') { return; }
					window.sessionStorage.setItem('sz_xs_seen_checkout', '1');
				} catch (err) { /* ignore */ }

				// Use the first cart item as the "anchor" for suggestions.
				var pid = self.firstCartItemId();
				if (!pid) { return; }

				e.preventDefault();
				var href = $(this).attr('href');

				self.fetchAndOpen(pid, function () {
					// After modal closes, continue to checkout if user didn't change cart.
					$('#sz-xs-modal').one('sz-xs-closed', function () {
						if (href) { window.location.href = href; }
					});
				});
			});
		},

		// ── Trigger: cart_page_view ─────────────────────────────────────
		bindCartPageView: function () {
			// Body class detection — WC adds .woocommerce-cart on the cart page.
			if (!document.body.classList.contains('woocommerce-cart')) { return; }
			try {
				if (window.sessionStorage.getItem('sz_xs_seen_cart') === '1') { return; }
				window.sessionStorage.setItem('sz_xs_seen_cart', '1');
			} catch (err) { /* ignore */ }

			var pid = this.firstCartItemId();
			if (!pid) { return; }
			var self = this;
			// Slight delay so the page is settled.
			window.setTimeout(function () { self.fetchAndOpen(pid); }, 1200);
		},

		// ── First cart item as "anchor" for suggestions ─────────────────
		firstCartItemId: function () {
			// WC renders cart items with .remove[data-product_id="123"] on the cart page,
			// and on mini-cart with .remove_from_cart_button[data-product_id="..."].
			var $remove = $('.cart_item .remove, .woocommerce-mini-cart-item .remove_from_cart_button').first();
			if ($remove.length) {
				return parseInt($remove.data('product_id') || $remove.attr('data-product_id'), 10) || 0;
			}
			return 0;
		},

		// ── Fetch + open ────────────────────────────────────────────────
		fetchAndOpen: function (productId, onClose) {
			var self = this;
			var $body = $('#sz-xs-modal [data-sz-xs-body]');

			$body.html('<div class="sz-xs-loading">' + (self.i18n.loading || 'Loading…') + '</div>');
			self.open();

			$.post(self.ajaxUrl, {
				action:     'storzen_cross_sell_fetch',
				nonce:      self.nonce,
				product_id: productId
			})
				.done(function (res) {
					if (res && res.success && res.data && res.data.html) {
						$body.html(res.data.html);

						// If the server says zero suggestions, auto-close so the
						// user isn't blocked by an empty popup.
						if (res.data.count !== undefined && res.data.count === 0) {
							window.setTimeout(self.close.bind(self), 800);
						}
					} else {
						$body.html('<p class="sz-xs-empty">' + (self.i18n.noItems || 'No suggestions.') + '</p>');
					}
				})
				.fail(function () {
					$body.html('<p class="sz-xs-empty">' + (self.i18n.noItems || 'No suggestions.') + '</p>');
				});

			if (typeof onClose === 'function') {
				onClose();
			}
		},

		// ── Add suggestion to cart (WC AJAX) ────────────────────────────
		addToCartFromModal: function (productId, $btn) {
			var self = this;
			$btn.prop('disabled', true).text(self.i18n.adding || 'Adding…');

			// Build standard WC add-to-cart form data.
			$.post(self.ajaxUrl, {
				action:     'woocommerce_add_to_cart',
				product_id: productId,
				quantity:   1
			})
				.done(function (res) {
					if (res && (res.fragments || res.success !== false)) {
						$btn.text(self.i18n.added || 'Added!').addClass('is-added');

						// Refresh WC fragments so theme mini-cart / floating cart update.
						if (res.fragments) {
							$.each(res.fragments, function (selector, html) {
								$(selector).replaceWith(html);
							});
							$(document.body).trigger('wc_fragments_refreshed');
						}
					} else {
						$btn.prop('disabled', false).text(self.i18n.error || 'Error');
					}
				})
				.fail(function () {
					$btn.prop('disabled', false).text(self.i18n.error || 'Error');
				});
		}
	};

	$(function () { XS.init(); });
	window.StorzenCrossSell = XS;

})(jQuery);
