/* =============================================================================
 * Storzen — Quick View (frontend)
 * Handles modal open/close, AJAX fetch, gallery switching, variation resolver,
 * and AJAX add-to-cart.
 *
 * Depends on: jQuery (already shipped with WP)
 * ========================================================================== */
(function ($) {
	'use strict';

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

	var QV = {

		$modal:      null,
		$content:    null,
		lastFocused: null,

		init: function () {
			this.$modal   = $('#sz-qv-modal');
			if (!this.$modal.length) { return; }
			this.$content = this.$modal.find('.sz-qv-modal__content');

			this.bindTriggers();
			this.bindModalClose();
			this.bindKeyboard();
			this.bindGalleryThumbs();
			this.bindVariationSelectors();
			this.bindAddToCart();
		},

		/* ───── Trigger button click ───── */
		bindTriggers: function () {
			$(document).on('click', '.sz-qv-btn', function (e) {
				e.preventDefault();
				e.stopPropagation();
				var $btn = $(this);
				QV.openModal($btn.data('product-id'), $btn.data('nonce'), this);
			});
		},

		/* ───── Open / Close ───── */
		openModal: function (productId, nonce, triggerEl) {
			if (!productId || !nonce) { return; }

			this.lastFocused = triggerEl || document.activeElement;

			this.$modal.prop('hidden', false);
			this.$content.html(this.loadingHTML());
			document.body.style.overflow = 'hidden';

			// Focus the close button for keyboard users.
			setTimeout(function () {
				QV.$modal.find('.sz-qv-modal__close').focus();
			}, 50);

			$.post(szQuickView.ajaxUrl, {
				action:     'storzen_quick_view',
				product_id: productId,
				nonce:      nonce
			})
				.done(function (res) {
					if (res && res.success && res.data && res.data.html) {
						QV.$content.html(res.data.html);
						QV.afterContentLoad();
					} else {
						var msg = (res && res.data && res.data.message) || szQuickView.i18n.error;
						QV.showErrorInModal(msg);
					}
				})
				.fail(function () {
					QV.showErrorInModal(szQuickView.i18n.error);
				});
		},

		closeModal: function () {
			this.$modal.prop('hidden', true);
			this.$content.empty();
			document.body.style.overflow = '';

			if (this.lastFocused && typeof this.lastFocused.focus === 'function') {
				this.lastFocused.focus();
			}
		},

		bindModalClose: function () {
			$(document).on('click', '[data-sz-qv-close="1"]', function (e) {
				e.preventDefault();
				QV.closeModal();
			});
		},

		bindKeyboard: function () {
			$(document).on('keydown', function (e) {
				if (QV.$modal.prop('hidden')) { return; }
				if (e.key === 'Escape') {
					QV.closeModal();
				}
			});
		},

		/* ───── After content loads ───── */
		afterContentLoad: function () {
			// Notify any listeners (themes, mini-carts) — fragment refresh is fine here.
			$(document.body).trigger('wc_fragment_refresh');
		},

		showErrorInModal: function (message) {
			var $err = $('<div>')
				.css({ padding: '40px 20px', textAlign: 'center', color: '#dc2626', fontSize: '14px' })
				.text(message);
			this.$content.empty().append($err);
		},

		loadingHTML: function () {
			return '<div class="sz-qv-modal__loading">' +
				'<div class="sz-qv-spinner" aria-hidden="true"></div>' +
				'<span class="screen-reader-text">' + szQuickView.i18n.loading + '</span>' +
				'</div>';
		},

		/* ───── Gallery thumbnails ───── */
		bindGalleryThumbs: function () {
			$(document).on('click', '.sz-qv-gallery__thumb', function () {
				var $thumb   = $(this);
				var newSrc   = $thumb.data('image');
				if (!newSrc) { return; }

				var $gallery = $thumb.closest('.sz-qv-gallery');
				$gallery.find('.sz-qv-gallery__main-img').attr('src', newSrc).attr('srcset', '');
				$gallery.find('.sz-qv-gallery__thumb').removeClass('is-active');
				$thumb.addClass('is-active');
			});
		},

		/* ───── Variation selector ───── */
		bindVariationSelectors: function () {
			$(document).on('change', '.sz-qv-attribute__select', function () {
				var $form = $(this).closest('.sz-qv-cart-form--variable');
				QV.resolveVariation($form);
			});
		},

		resolveVariation: function ($form) {
			var variations = $form.data('variations');
			if (!variations) { return; }

			var chosen = {};
			var allSet = true;

			$form.find('.sz-qv-attribute__select').each(function () {
				var name = $(this).attr('name');
				var val  = $(this).val();
				if (!val) { allSet = false; }
				chosen[name] = val;
			});

			var $btn    = $form.find('.sz-qv-add-btn');
			var $hidden = $form.find('.sz-qv-variation-id');
			var $info   = $form.find('.sz-qv-variation-info');

			if (!allSet) {
				$hidden.val(0);
				$btn.prop('disabled', true).text(szQuickView.i18n.selectOptions);
				$info.prop('hidden', true);
				return;
			}

			// Match the chosen attributes against the available variations.
			var match = null;
			for (var i = 0; i < variations.length; i++) {
				var v   = variations[i];
				var ok  = true;
				for (var k in chosen) {
					if (!Object.prototype.hasOwnProperty.call(chosen, k)) { continue; }
					var vk = v.attributes[k];
					// A blank attribute on the variation matches "any".
					if (vk !== '' && vk !== chosen[k]) { ok = false; break; }
				}
				if (ok) { match = v; break; }
			}

			if (match) {
				$hidden.val(match.variation_id);
				$info.prop('hidden', false);
				$info.find('.sz-qv-variation-price').html(match.price_html || '');

				var stockText = '';
				if (match.availability_html) {
					stockText = $('<div>').html(match.availability_html).text();
				}
				$info.find('.sz-qv-variation-stock').text(stockText);

				if (match.is_in_stock && match.is_purchasable) {
					$btn.prop('disabled', false).text(szQuickView.i18n.addToCart);
				} else {
					$btn.prop('disabled', true).text(szQuickView.i18n.outOfStock);
				}
			} else {
				$hidden.val(0);
				$btn.prop('disabled', true).text(szQuickView.i18n.outOfStock);
				$info.prop('hidden', true);
			}
		},

		/* ───── Add to cart submission ───── */
		bindAddToCart: function () {
			$(document).on('submit', '.sz-qv-cart-form', function (e) {
				e.preventDefault();

				var $form        = $(this);
				var productId    = $form.data('product-id');
				var type         = $form.data('type');
				var $btn         = $form.find('.sz-qv-add-btn');
				var originalText = $btn.text();

				var data = {
					action:     'storzen_quick_view_add_to_cart',
					product_id: productId,
					nonce:      QV.findNonce(productId),
					quantity:   parseInt($form.find('input[name="quantity"]').val(), 10) || 1
				};

				if (type === 'variable') {
					data.variation_id = parseInt($form.find('.sz-qv-variation-id').val(), 10) || 0;
					if (!data.variation_id) { return; }

					data.variation = {};
					$form.find('.sz-qv-attribute__select').each(function () {
						data.variation[$(this).attr('name')] = $(this).val();
					});
				}

				$btn.addClass('is-loading').prop('disabled', true).text(szQuickView.i18n.adding);

				$.post(szQuickView.ajaxUrl, data)
					.done(function (res) {
						if (res && res.success) {
							var d = res.data || {};
							$(document.body).trigger('added_to_cart', [d.fragments || {}, d.cart_hash || '']);

							if (d.fragments) {
								$.each(d.fragments, function (key, value) {
									$(key).replaceWith(value);
								});
							}

							$btn.removeClass('is-loading').addClass('is-success').text(szQuickView.i18n.added);

							setTimeout(function () {
								$btn.removeClass('is-success').text(originalText).prop('disabled', false);
							}, 2000);
						} else {
							var msg = (res && res.data && res.data.message) || szQuickView.i18n.error;
							$btn.removeClass('is-loading').prop('disabled', false).text(originalText);
							QV.showInlineError($form, msg);
						}
					})
					.fail(function () {
						$btn.removeClass('is-loading').prop('disabled', false).text(originalText);
						QV.showInlineError($form, szQuickView.i18n.error);
					});
			});
		},

		/**
		 * Find the per-product nonce from the original trigger button.
		 */
		findNonce: function (productId) {
			var $btn = $('.sz-qv-btn[data-product-id="' + productId + '"]').first();
			return $btn.data('nonce') || '';
		},

		showInlineError: function ($form, message) {
			$form.find('.sz-qv-form-error').remove();
			var $err = $('<div class="sz-qv-form-error" role="alert"></div>').text(message);
			$form.append($err);
			setTimeout(function () {
				$err.fadeOut(300, function () { $(this).remove(); });
			}, 4000);
		}
	};

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

	// Public namespace (debugging).
	window.StorzenQuickView = QV;

})(jQuery);
