/**
 * FoodOrd Cart Quantity Popover
 *
 * @package FoodOrd
 * @since 1.0
 */

(function ($) {
	'use strict';

	const I18N = (typeof window.foodordCardI18n === 'object' && window.foodordCardI18n !== null) ? window.foodordCardI18n : {};
	const getI18nString = (key, fallback) => {
		if (I18N && typeof I18N[key] === 'string' && I18N[key].length) {
			return I18N[key];
		}
		return fallback;
	};
	const escapeText = (value) => $('<div></div>').text(value || '').html();
	const emptyCartSvg = '<svg class="wr-card__empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"></path><line x1="3" y1="6" x2="21" y2="6"></line><path d="M16 10a4 4 0 0 1-8 0"></path></svg>';

	/**
	 * Cart Quantity Popover Handler
	 */
	class FoodOrdPopover {
		constructor() {
			this.latestCartMutationRequestId = 0;
			this.init();
		}

		startCartMutationRequest() {
			this.latestCartMutationRequestId += 1;
			return this.latestCartMutationRequestId;
		}

		isLatestCartMutationRequest(requestId) {
			return requestId === this.latestCartMutationRequestId;
		}

		setCtaTotalLoadingState(isLoading, options = {}) {
			const restoreOriginal = options.restoreOriginal !== false;
			const $ctaTotals = $('.wr-card__cta .wr-card__cta-total');

			$ctaTotals.each(function () {
				const $total = $(this);

				if (isLoading) {
					if ($total.hasClass('wr-card__cta-total--loading')) {
						return;
					}
					$total.data('foodord-original-html', $total.html());
					$total
						.addClass('wr-card__cta-total--loading')
						.attr('aria-busy', 'true')
						.html('<span class="wr-card__cta-total-dots" aria-hidden="true"><span></span><span></span><span></span></span>');
					return;
				}

				$total.removeClass('wr-card__cta-total--loading').removeAttr('aria-busy');
				if (restoreOriginal && typeof $total.data('foodord-original-html') !== 'undefined') {
					$total.html($total.data('foodord-original-html'));
				}
				$total.removeData('foodord-original-html');
			});
		}

		setSubtotalLoadingState(isLoading) {
			const $subtotalAmounts = $('.wr-card__subtotal-amount');

			$subtotalAmounts.each(function () {
				const $subtotalAmount = $(this);
				if (isLoading) {
					$subtotalAmount.addClass('wr-card__subtotal-amount--loading').attr('aria-busy', 'true');
					return;
				}
				$subtotalAmount.removeClass('wr-card__subtotal-amount--loading').removeAttr('aria-busy');
			});
		}

		init() {
			this.bindEvents();
		}

		bindEvents() {
			const self = this;

			// Handle popover button clicks
			$(document).on('click', '.wr-card__quantity-btn', function (e) {
				e.stopPropagation();
				self.handleButtonClick($(this));
			});

			// Prevent popover from closing when clicking inside it
			$(document).on('click', '.wr-card__quantity-popover', function (e) {
				e.stopPropagation();
			});

		}

		showPopover($quantityElement) {
			const $item = $quantityElement.closest('.wr-card__item');
			const currentQuantity = parseInt($item.attr('data-quantity') || 1, 10);

			// Close any open popovers with enhanced animation
			this.closeAllPopovers();

			// Store original text
			$quantityElement.attr('data-original-text', $quantityElement.text());

			// Add active state to quantity element
			$quantityElement.addClass('active');

			// Create popover HTML with enhanced icons
			const minusIcon = currentQuantity === 1 ?
				'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg>' :
				'';
			const minusClass = currentQuantity === 1 ? 'minus trash' : 'minus';

			const popoverHtml =
				'<div class="wr-card__quantity-popover">' +
				'<button class="wr-card__quantity-btn ' + minusClass + '" data-action="minus">' + minusIcon + '</button>' +
				'<span class="wr-card__quantity-value">' + currentQuantity + '</span>' +
				'<button class="wr-card__quantity-btn plus" data-action="plus"></button>' +
				'</div>';

			// Append popover with initial opacity for smooth entrance
			$quantityElement.append(popoverHtml);

			// Trigger animation with small delay for smooth entrance
			requestAnimationFrame(() => {
				$quantityElement.find('.wr-card__quantity-popover').addClass('active');
			});

		}


		handleButtonClick($button) {
			const action = $button.data('action');
			const $popover = $button.closest('.wr-card__quantity-popover');
			const $quantitySpan = $popover.closest('.wr-card__item-quantity');
			const $item = $quantitySpan.closest('.wr-card__item');
			const productId = $item.data('product-id');
			const variationId = parseInt($item.data('variation-id'), 10) || 0;
			let currentQuantity = parseInt($item.attr('data-quantity') || 1, 10);

			if (action === 'plus') {
				currentQuantity++;
				this.updateCartQuantity(productId, variationId, currentQuantity, $item, $popover, $quantitySpan);
			} else if (action === 'minus') {
				if (currentQuantity > 1) {
					currentQuantity--;
					this.updateCartQuantity(productId, variationId, currentQuantity, $item, $popover, $quantitySpan);
				} else {
					// Remove item from cart
					this.removeCartItem(productId, variationId, $item);
				}
			}
		}



		/**
		 * Animate counter value change (Sayaç Efekti)
		 */
		animateCounter($el, newValue) {
			const currentVal = parseInt($el.data('last-val'), 10);
			const oldValue = !isNaN(currentVal) ? currentVal : (parseInt($el.text(), 10) || 0);

			if (oldValue === newValue) return;

			// Clear any existing animation cleanup timers
			const existingTimer = $el.data('animation-timer');
			if (existingTimer) {
				clearTimeout(existingTimer);
			}

			const direction = newValue > oldValue ? 'is-incrementing' : 'is-decrementing';

			// Create animation structure
			const $container = $('<span>', { class: 'foodord-counter-animate ' + direction });
			const $oldNum = $('<span>', { class: 'foodord-counter-number foodord-counter-number--old' }).text(oldValue);
			const $newNum = $('<span>', { class: 'foodord-counter-number foodord-counter-number--new' }).text(newValue);

			$container.append($oldNum).append($newNum);
			$el.data('last-val', newValue).empty().append($container);

			// Trigger animation
			requestAnimationFrame(() => {
				$container.addClass('animate-active');
			});

			// Cleanup after animation
			const timer = setTimeout(() => {
				if ($el.data('last-val') === newValue) {
					$el.text(newValue);
				}
				$el.removeData('animation-timer');
			}, 400);

			$el.data('animation-timer', timer);
		}


		updateCartQuantity(productId, variationId, newQuantity, $item, $popover, $quantitySpan) {
			const self = this;
			// Update UI immediately
			$item.attr('data-quantity', newQuantity);
			$quantitySpan.attr('data-original-text', newQuantity);

			// Update only the stored text, not the actual element text
			// This preserves the popover
			const $valueEl = $popover.find('.wr-card__quantity-value');
			if ($valueEl.length) {
				this.animateCounter($valueEl, newQuantity);
			}

			// Update minus button icon
			const $minusBtn = $popover.find('.wr-card__quantity-btn.minus');
			if (newQuantity === 1) {
				$minusBtn.html('<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg>').addClass('trash');
			} else {
				$minusBtn.html('').removeClass('trash');
			}


			// AJAX call to update cart
			if (typeof foodord_modal_vars !== 'undefined') {
				const requestId = this.startCartMutationRequest();
				this.setCtaTotalLoadingState(true);
				this.setSubtotalLoadingState(true);
				const request = $.post(foodord_modal_vars.ajax_url, {
					action: 'foodord_update_cart_quantity',
					product_id: productId,
					variation_id: variationId,
					quantity: newQuantity,
					nonce: foodord_modal_vars.nonce
				}, function (response) {
					if (!self.isLatestCartMutationRequest(requestId)) {
						return;
					}

					if (response.success) {
						self.setCtaTotalLoadingState(false, { restoreOriginal: false });
						self.setSubtotalLoadingState(false);
						// Update item-specific price if provided by server
						if (response.data && response.data.item_line_total) {
							const $itemPrice = $item.find('.wr-card__item-price');
							if ($itemPrice.length) {
								$itemPrice.html(response.data.item_line_total);
							}
						}

						// Update cart fragments if available
						if (response.data && response.data.fragments) {
							$.each(response.data.fragments, function (key, value) {
								const selector = String(key || '');
								// Keep desktop quantity popover stable: avoid replacing cart body/items while adjusting quantity.
								if (
									selector.indexOf('.wr-card__body') !== -1 ||
									selector.indexOf('.wr-card__items') !== -1 ||
									selector.indexOf('.wr-card__upsells') !== -1
								) {
									return;
								}
								$(key).replaceWith(value);
							});
						}

						// Update clear button state after quantity change
						if (typeof window.FoodordCard !== 'undefined' && window.FoodordCard.updateClearButton) {
							window.FoodordCard.updateClearButton();
						}
						// Update count badge
						if (typeof window.FoodordCard !== 'undefined' && window.FoodordCard.updateCartCount) {
							// Prefer server-provided count if available
							const forcedCount = response.data && typeof response.data.cart_count !== 'undefined' ? parseInt(response.data.cart_count, 10) : undefined;
							window.FoodordCard.updateCartCount(forcedCount);
						}

						// Update CTA state comprehensively
						if (typeof window.FoodordCard !== 'undefined' && window.FoodordCard.updateCTAState) {
							window.FoodordCard.updateCTAState(response.data);
						} else if (response.data && response.data.cart_total_html) {
							// Fallback: direct update
							jQuery('.wr-card__cta .wr-card__cta-total').html(response.data.cart_total_html);
						}

						// Keep modal prefill snapshot in sync with latest quantity changes from cart popover.
						if (
							typeof window.FoodOrdModalFooter !== 'undefined' &&
							window.FoodOrdModalFooter &&
							typeof window.FoodOrdModalFooter.setCartSnapshot === 'function' &&
							response.data &&
							Array.isArray(response.data.cart_items)
						) {
							window.FoodOrdModalFooter.setCartSnapshot(response.data.cart_items);
						}

						// Dispatch event without cart_items while popover is active to prevent desktop re-render and popover close.
						const eventDetail = Object.assign({}, response.data || {});
						delete eventDetail.cart_items;
						delete eventDetail.card_upsells_html;
						document.dispatchEvent(new CustomEvent('foodord_cart_updated', { detail: eventDetail }));
					} else {
						self.setCtaTotalLoadingState(false, { restoreOriginal: true });
						self.setSubtotalLoadingState(false);
					}
				});
				request.fail(function () {
					if (!self.isLatestCartMutationRequest(requestId)) {
						return;
					}
					self.setCtaTotalLoadingState(false, { restoreOriginal: true });
					self.setSubtotalLoadingState(false);
				});
			}
		}

		removeCartItem(productId, variationId, $item) {
			const self = this;

			// Close popover first
			self.closeAllPopovers();

			// Remove item with animation
			$item.fadeOut(300, function () {
				$item.remove();

				// Check if cart is empty
				if ($('.wr-card__item').length === 0) {
					const emptyText = escapeText(getI18nString('emptyCartText', 'Your cart is empty'));
					const emptySubtext = escapeText(getI18nString('emptyCartSubtext', 'Add items to get started'));
					const $body = $('.wr-card__body');
					$body.html(
						'<div class="wr-card__empty">' +
						'<div class="wr-card__empty-icon-wrap">' + emptyCartSvg + '</div>' +
						(emptyText ? '<h3 class="wr-card__empty-text">' + emptyText + '</h3>' : '') +
						(emptySubtext ? '<p class="wr-card__empty-subtext">' + emptySubtext + '</p>' : '') +
						'</div>'
					);

					// Update footer button
					$('.wr-card__cta').addClass('disabled').attr('disabled', true).attr('aria-disabled', 'true');
				}

				// Update clear button state after removal (wait for DOM update)
				setTimeout(function () {
					if (typeof window.FoodordCard !== 'undefined' && window.FoodordCard.updateClearButton) {
						window.FoodordCard.updateClearButton();
					}
					if (typeof window.FoodordCard !== 'undefined' && window.FoodordCard.updateCartCount) {
						window.FoodordCard.updateCartCount();
					}
				}, 10);
			});

			// AJAX call to remove from cart
			if (typeof foodord_modal_vars !== 'undefined') {
				const requestId = this.startCartMutationRequest();
				this.setCtaTotalLoadingState(true);
				this.setSubtotalLoadingState(true);
				const request = $.post(foodord_modal_vars.ajax_url, {
					action: 'foodord_remove_cart_item',
					product_id: productId,
					variation_id: variationId,
					nonce: foodord_modal_vars.nonce
				}, function (response) {
					if (!self.isLatestCartMutationRequest(requestId)) {
						return;
					}

					if (response.success) {
						self.setCtaTotalLoadingState(false, { restoreOriginal: false });
						self.setSubtotalLoadingState(false);
						// Update cart fragments if available
						if (response.data && response.data.fragments) {
							$.each(response.data.fragments, function (key, value) {
								$(key).replaceWith(value);
							});
						}

						// Update clear button state after item removal
						if (typeof window.FoodordCard !== 'undefined' && window.FoodordCard.updateClearButton) {
							window.FoodordCard.updateClearButton();
						}
						// Update count badge
						if (typeof window.FoodordCard !== 'undefined' && window.FoodordCard.updateCartCount) {
							const forcedCount = response.data && typeof response.data.cart_count !== 'undefined' ? parseInt(response.data.cart_count, 10) : undefined;
							window.FoodordCard.updateCartCount(forcedCount);
						}

						// Update CTA state comprehensively
						if (typeof window.FoodordCard !== 'undefined' && window.FoodordCard.updateCTAState) {
							window.FoodordCard.updateCTAState(response.data);
						} else if (response.data) {
							// Fallback: direct updates
							if (response.data.cart_total_html) {
								jQuery('.wr-card__cta .wr-card__cta-total').html(response.data.cart_total_html);
							}
							if (response.data.cart_count === 0) {
								jQuery('.wr-card__cta')
									.addClass('disabled')
									.attr('aria-disabled', 'true')
									.prop('disabled', true);
								jQuery('.wr-card__cta .wr-card__cta-total').html(typeof foodord_modal_vars !== 'undefined' && foodord_modal_vars.cart_zero_html ? foodord_modal_vars.cart_zero_html : '0');
							}
						}

						// Dispatch custom event for mobile cart
						document.dispatchEvent(new CustomEvent('foodord_cart_updated', { detail: response.data }));
					} else {
						self.setCtaTotalLoadingState(false, { restoreOriginal: true });
						self.setSubtotalLoadingState(false);
					}
				});
				request.fail(function () {
					if (!self.isLatestCartMutationRequest(requestId)) {
						return;
					}
					self.setCtaTotalLoadingState(false, { restoreOriginal: true });
					self.setSubtotalLoadingState(false);
				});
			}
		}

		closeAllPopovers() {
			$('.wr-card__item-quantity').removeClass('active');
			$('.wr-card__quantity-popover').removeClass('closing').addClass('active');
		}
	}

	// Initialize when DOM is ready
	$(document).ready(function () {
		new FoodOrdPopover();
	});

})(jQuery);
