/* Mobile Cart Popover - Exact Copy of Desktop Logic */

(function ($) {
  'use strict';

  if (typeof $ === 'undefined') return;

  const I18N = (typeof window.foodordMobileCartI18n === 'object' && window.foodordMobileCartI18n !== null)
    ? window.foodordMobileCartI18n
    : {};
  const getI18nString = (key, fallback) => {
    if (I18N && typeof I18N[key] === 'string' && I18N[key].length) {
      return I18N[key];
    }
    return fallback;
  };
  const emptyCartSvg = '<svg class="foodord-mobile-cart__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>';

  class MobileCartPopover {
    constructor() {
      this.quantitySyncStates = new Map();
      this.activeTotalsLoadingRequests = 0;
      this.init();
    }

    getItemMutationKey($item, productId, variationId) {
      const cartItemKey = ($item && $item.attr('data-cart-item-key')) ? String($item.attr('data-cart-item-key')) : '';
      if (cartItemKey) {
        return `cart:${cartItemKey}`;
      }
      return `pv:${parseInt(productId, 10) || 0}:${parseInt(variationId, 10) || 0}`;
    }

    getOrCreateQuantitySyncState(mutationKey, productId, variationId, cartItemKey) {
      if (!this.quantitySyncStates.has(mutationKey)) {
        this.quantitySyncStates.set(mutationKey, {
          inFlight: false,
          desiredQuantity: 0,
          lastSentQuantity: 0,
          productId: parseInt(productId, 10) || 0,
          variationId: parseInt(variationId, 10) || 0,
          cartItemKey: cartItemKey || ''
        });
      }

      return this.quantitySyncStates.get(mutationKey);
    }

    beginTotalsLoading() {
      this.activeTotalsLoadingRequests += 1;
      if (this.activeTotalsLoadingRequests === 1) {
        this.setTotalsLoadingState(true);
        this.setSubtotalLoadingState(true);
      }
    }

    endTotalsLoading(options = {}) {
      const restoreOriginal = options.restoreOriginal === true;
      this.activeTotalsLoadingRequests = Math.max(0, this.activeTotalsLoadingRequests - 1);
      if (this.activeTotalsLoadingRequests === 0) {
        this.setTotalsLoadingState(false, { restoreOriginal: restoreOriginal });
        this.setSubtotalLoadingState(false);
      }
    }

    setTotalsLoadingState(isLoading, options = {}) {
      const restoreOriginal = options.restoreOriginal !== false;
      const $totals = $('.foodord-mobile-cart__total');

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

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

        $total.removeClass('foodord-mobile-cart__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 = $('.foodord-mobile-cart__subtotal-amount');

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

    init() {
      this.bindEvents();
    }

    bindEvents() {
      const self = this;

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

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

    }

    showPopover($quantityEl) {
      const quantity = parseInt($quantityEl.text()) || 1;
      const minusIcon = quantity === 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>' : '';

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

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

      const popoverHtml = `
        <div class="mobile-popover">
          <button class="minus ${quantity === 1 ? 'trash' : ''}" data-action="minus">${minusIcon}</button>
          <span>${quantity}</span>
          <button class="plus" data-action="plus"></button>
        </div>
      `;

      $quantityEl.append(popoverHtml);

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

      // Add subtle scale animation to quantity value
      const $value = $quantityEl.find('.mobile-popover span');
      $value.css('transform', 'scale(0.8)');
      setTimeout(() => {
        $value.css('transform', 'scale(1)');
      }, 50);
    }

    handleButtonClick($btn) {
      const action = $btn.data('action');
      const $popover = $btn.closest('.mobile-popover');
      const $quantityEl = $popover.parent();
      const $item = $quantityEl.closest('.foodord-mobile-cart__item');
      const productId = $item.data('product-id');
      const variationId = $item.data('variation-id') || 0;
      let quantity = parseInt($popover.find('span').text()) || 1;

      if (action === 'plus') {
        quantity++;
        this.updateQuantity(productId, variationId, quantity, $popover);
      } else if (action === 'minus') {
        if (quantity > 1) {
          quantity--;
          this.updateQuantity(productId, variationId, quantity, $popover);
        } else {
          this.removeItem(productId, variationId, $item);
        }
      }
    }

    updateQuantity(productId, variationId, newQuantity, $popover) {
      // Update UI immediately in the popover
      $popover.find('span').text(newQuantity);
      const $minusBtn = $popover.find('[data-action="minus"]');

      if (newQuantity === 1) {
        $minusBtn.addClass('trash');
        $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>');
      } else {
        $minusBtn.removeClass('trash');
        $minusBtn.html('');
      }

      // Update quantity in the main element (both data attribute and text)
      const $quantityEl = $popover.parent();
      $quantityEl.attr('data-quantity', newQuantity);

      // Get item elements for price update
      const $item = $quantityEl.closest('.foodord-mobile-cart__item');
      $item.attr('data-quantity', newQuantity);
      const cartItemKey = $item.attr('data-cart-item-key') ? String($item.attr('data-cart-item-key')) : '';
      const mutationKey = this.getItemMutationKey($item, productId, variationId);
      const state = this.getOrCreateQuantitySyncState(mutationKey, productId, variationId, cartItemKey);
      state.desiredQuantity = newQuantity;

      // Try to get unit price for immediate feedback (only if we have reliable data)
      const $itemPrice = $item.find('.foodord-mobile-cart__item-price');
      const unitPrice = parseFloat($item.data('unit-price')) || 0;
      if (unitPrice > 0 && $itemPrice.length) {
        const totalPrice = unitPrice * newQuantity;
        const currentPriceText = $itemPrice.text().replace(/[^\\d.,]/g, '');
        const currentPrice = parseFloat(currentPriceText.replace(',', '.')) || 0;
        const priceDiff = Math.abs(totalPrice - currentPrice);
        const maxAllowedDiff = unitPrice * 0.5;
        if (priceDiff <= maxAllowedDiff) {
          $itemPrice.text('€' + totalPrice.toFixed(2));
        }
      }

      this.flushQuantitySync(mutationKey);
    }

    flushQuantitySync(mutationKey) {
      const state = this.quantitySyncStates.get(mutationKey);
      if (!state || state.inFlight || typeof foodord_modal_vars === 'undefined') {
        return;
      }

      const requestQuantity = parseInt(state.desiredQuantity, 10) || 1;
      state.inFlight = true;
      state.lastSentQuantity = requestQuantity;

      this.beginTotalsLoading();

      $.post(foodord_modal_vars.ajax_url, {
        action: 'foodord_update_cart_quantity',
        product_id: state.productId,
        variation_id: state.variationId,
        quantity: requestQuantity,
        nonce: foodord_modal_vars.nonce
      }).done((response) => {
        this.endTotalsLoading({ restoreOriginal: !response || !response.success });
        state.inFlight = false;

        if (response && response.success) {
          // Update mobile cart totals
          if (response.data && response.data.cart_total_html) {
            $('.foodord-mobile-cart__total').html(response.data.cart_total_html);
          }
          if (response.data && typeof response.data.cart_count !== 'undefined') {
            $('.foodord-mobile-cart__count').text(response.data.cart_count);
          }

          // Update subtotal in mobile cart
          if (response.data && response.data.subtotal_html) {
            $('.foodord-mobile-cart__subtotal-amount').html(response.data.subtotal_html);
          }

          // Update delivery fee in mobile cart (only show if cart has items)
          if (response.data && response.data.cart_count > 0 && response.data.delivery_fee_html) {
            $('.foodord-mobile-cart__delivery-fee').show();
            $('.foodord-mobile-cart__subtotal').show();
            $('.foodord-mobile-cart__delivery-amount').html(response.data.delivery_fee_html);
          }

          // Keep modal prefill snapshot in sync with latest quantity changes from mobile 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);
          }

          try {
            const eventDetail = Object.assign({}, response.data || {});
            delete eventDetail.cart_items;
            delete eventDetail.card_upsells_html;
            eventDetail.updated_cart_item_key = state.cartItemKey;
            eventDetail.updated_item_line_total = response.data && response.data.item_line_total ? response.data.item_line_total : '';
            eventDetail.updated_item_quantity = requestQuantity;
            document.dispatchEvent(new CustomEvent('foodord_cart_updated', {
              detail: eventDetail
            }));
          } catch {
            // Fail silently if CustomEvent is not supported
          }
        } else if (window.FoodordMobileCart && typeof window.FoodordMobileCart.loadData === 'function') {
          window.FoodordMobileCart.loadData();
        }

        if (state.desiredQuantity !== state.lastSentQuantity) {
          this.flushQuantitySync(mutationKey);
          return;
        }

        this.quantitySyncStates.delete(mutationKey);
      }).fail(() => {
        this.endTotalsLoading({ restoreOriginal: true });
        state.inFlight = false;
        this.quantitySyncStates.delete(mutationKey);
        if (window.FoodordMobileCart && typeof window.FoodordMobileCart.loadData === 'function') {
          window.FoodordMobileCart.loadData();
        }
      });
    }

    removeItem(productId, variationId, $item) {
      this.closeAllPopovers();

      if (typeof foodord_modal_vars !== 'undefined') {
        this.beginTotalsLoading();
        $.post(foodord_modal_vars.ajax_url, {
          action: 'foodord_remove_cart_item',
          product_id: productId,
          variation_id: variationId,
          nonce: foodord_modal_vars.nonce
        }).done(function (response) {
          if (response.success) {
            this.endTotalsLoading({ restoreOriginal: false });
            $item.remove();

            // Update mobile cart totals without reloading the entire modal
            if (response.data && response.data.cart_total_html) {
              $('.foodord-mobile-cart__total').html(response.data.cart_total_html);
            }
            if (response.data && typeof response.data.cart_count !== 'undefined') {
              $('.foodord-mobile-cart__count').text(response.data.cart_count);
            }

            // Update subtotal in mobile cart
            if (response.data && response.data.subtotal_html) {
              $('.foodord-mobile-cart__subtotal-amount').html(response.data.subtotal_html);
            }

            // Update or hide delivery fee based on cart status
            if (response.data && response.data.cart_count === 0) {
              // Hide delivery fee when cart is empty
              $('.foodord-mobile-cart__delivery-fee').hide();
              $('.foodord-mobile-cart__subtotal').hide();
            } else if (response.data && response.data.delivery_fee_html) {
              // Show and update delivery fee when cart has items
              $('.foodord-mobile-cart__delivery-fee').show();
              $('.foodord-mobile-cart__subtotal').show();
              $('.foodord-mobile-cart__delivery-amount').html(response.data.delivery_fee_html);
            }

            // Check if cart is empty and show empty message
            if (response.data && response.data.cart_count === 0) {
              const emptyText = $('<div></div>').text(getI18nString('emptyCartText', 'Your cart is empty')).html();
              const emptySubtext = $('<div></div>').text(getI18nString('emptyCartSubtext', 'Add items to get started')).html();
              const emptyHtml = `
                <div class="foodord-mobile-cart__empty">
                  ${emptyCartSvg}
                  <p class="foodord-mobile-cart__empty-text">${emptyText}</p>
                  <p class="foodord-mobile-cart__empty-subtext">${emptySubtext}</p>
                </div>
              `;
              $('.foodord-mobile-cart__modal-body').html(emptyHtml);
              $('.foodord-mobile-cart__summary').html(''); // Clear summary when empty
            }

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

            try {
              document.dispatchEvent(new CustomEvent('foodord_cart_updated', {
                detail: response.data || {}
              }));
            } catch {
              // Fail silently if CustomEvent is not supported
            }

            if (window.FoodordMobileCart && typeof window.FoodordMobileCart.loadData === 'function') {
              window.FoodordMobileCart.loadData();
            }
          } else {
            this.endTotalsLoading({ restoreOriginal: true });
          }
        }.bind(this)).fail(function () {
          this.endTotalsLoading({ restoreOriginal: true });
        }.bind(this));
      }
    }

    closeAllPopovers() {
      $('.foodord-mobile-cart__item-quantity').removeClass('active');
      $('.mobile-popover').removeClass('closing').addClass('active');
    }
  }

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

})(jQuery);
