/* FoodOrd Card - initialization scaffold */

(function (window, document) {
  const BODY_BOTTOM_FALLBACK = 80;
  const BODY_BOTTOM_BUFFER = 16;
  const BODY_BOTTOM_MAX = 256;
  const GAP_STEP = 16;
  const GAP_CLASS_PREFIX = 'wr-card--gap-';
  const I18N = (typeof window.foodordCardI18n === 'object' && window.foodordCardI18n !== null)
    ? window.foodordCardI18n
    : {};
  const getI18nString = (key) => (typeof I18N[key] === 'string') ? I18N[key] : '';
  const isTableOrderingContext = () => !!(window.foodordTableOrdering && window.foodordTableOrdering.token);
  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>';
  const parseToggleValue = (value) => {
    if (value === true || value === 'yes' || value === 'true' || value === 1 || value === '1') {
      return true;
    }
    if (value === false || value === 'no' || value === 'false' || value === 0 || value === '0') {
      return false;
    }
    return Boolean(value);
  };

  let showToppingGroupLabels = true;
  let upsellsEnabled = parseToggleValue(Object.prototype.hasOwnProperty.call(I18N, 'upsellsEnabled') ? I18N.upsellsEnabled : true);
  let lastAppliedCartHash = '';

  const setShowToppingGroupLabels = (value) => {
    showToppingGroupLabels = parseToggleValue(value);
    window.FoodordShowToppingGroupLabels = showToppingGroupLabels;
  };

  const areUpsellsEnabled = () => {
    if (
      typeof window.foodord_modal_vars !== 'undefined' &&
      Object.prototype.hasOwnProperty.call(window.foodord_modal_vars, 'modal_upsells_enabled')
    ) {
      upsellsEnabled = parseToggleValue(window.foodord_modal_vars.modal_upsells_enabled);
    }

    return upsellsEnabled;
  };

  const getUpsellSkeletonHtml = (count = 3) => {
    if (!areUpsellsEnabled()) {
      return '';
    }

    if (!window.FoodordUpsellSkeleton || typeof window.FoodordUpsellSkeleton.buildRail !== 'function') {
      return '';
    }

    return window.FoodordUpsellSkeleton.buildRail({
      context: 'card',
      count: count
    });
  };

  const getCartItemSkeletonCount = (force = false) => {
    const snapshotCount = (typeof window.FoodOrdModalFooter !== 'undefined' && Array.isArray(window.FoodOrdModalFooter.cartSnapshot))
      ? window.FoodOrdModalFooter.cartSnapshot.length
      : 0;
    const domCount = document.querySelectorAll('.wr-card__body .wr-card__item').length;
    const fallbackCount = force ? 1 : 0;
    return Math.max(snapshotCount, domCount, fallbackCount);
  };

  const buildCartItemSkeletonHtml = (count) => {
    const skeletonCount = Math.max(1, count || 0);
    let html = '<div class="wr-card__items wr-card__items--skeleton" aria-hidden="true">';

    for (let index = 0; index < skeletonCount; index += 1) {
      html += `
        <div class="wr-card__item wr-card__item--skeleton">
          <div class="wr-card__item-details">
            <div class="foodord-skeleton wr-card__item-skeleton-title"></div>
            <div class="foodord-skeleton wr-card__item-skeleton-meta"></div>
            <div class="foodord-skeleton wr-card__item-skeleton-meta wr-card__item-skeleton-meta--short"></div>
          </div>
          <div class="wr-card__item-actions">
            <div class="wr-card__item-quantity">
              <div class="foodord-skeleton wr-card__item-skeleton-quantity"></div>
            </div>
          </div>
        </div>
      `;
    }

    html += '</div>';
    return html;
  };

  const hasCartBodyContent = () => Array.from(document.querySelectorAll('.wr-card__body')).some((body) => (
    body.querySelector('.wr-card__items') || body.querySelector('.wr-card__upsells')
  ));

  const showUpsellSkeleton = (force = false) => {
    if (!areUpsellsEnabled()) {
      return;
    }

    const skeletonHtml = getUpsellSkeletonHtml(3);
    const itemsSkeletonHtml = buildCartItemSkeletonHtml(getCartItemSkeletonCount(force));

    if (!skeletonHtml || (!force && !hasCartBodyContent())) {
      return;
    }

    document.querySelectorAll('.wr-card__body').forEach((body) => {
      body.innerHTML = `${itemsSkeletonHtml}<div class="wr-card__upsells wr-card__upsells--loading">${skeletonHtml}</div>`;
    });

    syncCardBodyOffsets();
  };

  if (typeof window.foodord_modal_vars !== 'undefined' && Object.prototype.hasOwnProperty.call(window.foodord_modal_vars, 'show_topping_group_labels')) {
    setShowToppingGroupLabels(window.foodord_modal_vars.show_topping_group_labels);
  }

  window.FoodordShowToppingGroupLabels = showToppingGroupLabels;

  const applyCardGapClass = (card, gap) => {
    const normalized = Math.round(gap / GAP_STEP) * GAP_STEP;
    const clamped = Math.max(BODY_BOTTOM_FALLBACK, Math.min(BODY_BOTTOM_MAX, normalized));
    const gapClasses = Array.from(card.classList).filter((name) => name.indexOf(GAP_CLASS_PREFIX) === 0);
    gapClasses.forEach((name) => card.classList.remove(name));
    card.classList.add(GAP_CLASS_PREFIX + clamped);
  };

  const syncCardEmptyState = (scope) => {
    const root = scope && scope.querySelectorAll ? scope : document;
    const cards = root.matches && root.matches('.wr-card') ? [root] : Array.from(root.querySelectorAll('.wr-card'));

    cards.forEach((card) => {
      const body = card.querySelector('.wr-card__body');
      const hasItems = body ? !!body.querySelector('.wr-card__item') : false;
      const hasEmptyState = body ? !!body.querySelector('.wr-card__empty') : false;

      card.classList.toggle('wr-card--empty', hasEmptyState && !hasItems);
      card.classList.toggle('wr-card--has-items', hasItems);
    });
  };

  const syncCardBodyOffsets = () => {
    const raf = window.requestAnimationFrame || function (cb) { return window.setTimeout(cb, 16); };
    raf(() => {
      const cards = document.querySelectorAll('.wr-card');
      cards.forEach((card) => {
        syncCardEmptyState(card);
        const body = card.querySelector('.wr-card__body');
        if (!body) {
          return;
        }
        const footer = card.querySelector('.wr-card__footer');
        let bottomGap = BODY_BOTTOM_FALLBACK;
        if (footer) {
          const rect = footer.getBoundingClientRect();
          const measured = rect && rect.height ? rect.height : footer.offsetHeight;
          if (measured && !isNaN(measured)) {
            bottomGap = Math.ceil(measured + BODY_BOTTOM_BUFFER);
          }
        }
        applyCardGapClass(card, bottomGap);
      });
    });
  };

  let resizeSyncTimer;
  const scheduleCardBodyOffsetSync = () => {
    if (resizeSyncTimer) {
      window.clearTimeout(resizeSyncTimer);
    }
    resizeSyncTimer = window.setTimeout(syncCardBodyOffsets, 120);
  };

  const initCard = () => {
    const containers = document.querySelectorAll('.wr-card');
    containers.forEach((el) => {
      el.setAttribute('data-ready', 'true');
    });
    syncCardEmptyState();

    // Initialize clear cart functionality
    initClearCartModal();

    // Initialize checkout button functionality
    initCheckoutButton();

    // Initialize cart item editing handlers
    initCartItemEditing();

    // Initialize cart upsell handlers
    initCartUpsells();

    // Update button text based on current page
    updateCheckoutButtonText();

    enforceLocationGateOnCTA(getCurrentOrderMode(true));

    // Load and display current cart items
    loadCartItems();
    syncCardBodyOffsets();
  };

  let eventListenersInitialized = false;
  let checkoutEventListenersInitialized = false;
  let cartItemEditListenersInitialized = false;
  let cartUpsellListenersInitialized = false;

  const initClearCartModal = () => {
    // Prevent duplicate event listeners
    if (eventListenersInitialized) {
      return;
    }
    eventListenersInitialized = true;

    // Handle clear cart button click with event delegation
    document.addEventListener('click', function (e) {
      const clearBtn = e.target.closest('.wr-card__clear-btn');
      if (clearBtn && !clearBtn.disabled) {
        e.preventDefault();
        e.stopPropagation();
        showClearCartModal();
      }
    });

    // Handle modal button clicks with event delegation
    document.addEventListener('click', function (e) {
      const activeModal = e.target.closest('.wr-card__modal-overlay.active');
      const modalIsLoading = activeModal && activeModal.classList.contains('wr-card__modal-overlay--loading');

      if (
        modalIsLoading &&
        (
          e.target.classList.contains('wr-card__modal-overlay') ||
          e.target.closest('.wr-card__modal-btn--confirm')
        )
      ) {
        e.preventDefault();
        e.stopPropagation();
        return;
      }

      if (e.target.closest('.wr-card__modal-btn--cancel') || e.target.closest('.wr-card__modal-close')) {
        e.preventDefault();
        e.stopPropagation();
        hideClearCartModal();
      } else if (e.target.closest('.wr-card__modal-btn--confirm')) {
        e.preventDefault();
        e.stopPropagation();
        clearCart();
      } else if (e.target.classList.contains('wr-card__modal-overlay')) {
        e.preventDefault();
        e.stopPropagation();
        hideClearCartModal();
      }
    });

    // Handle escape key
    document.addEventListener('keydown', function (e) {
      if (e.key === 'Escape') {
        const activeModal = document.querySelector('.wr-card__modal-overlay.active');
        if (activeModal) {
          e.preventDefault();
          if (activeModal.classList.contains('wr-card__modal-overlay--loading')) {
            return;
          }
          hideClearCartModal();
        }
      }
    });
  };

  const initCartItemEditing = () => {
    if (cartItemEditListenersInitialized) {
      return;
    }
    cartItemEditListenersInitialized = true;

    const isEditableClickTarget = (event) => {
      if (!event) {
        return false;
      }
      const titleButton = event.target.closest('.wr-card__item-title-button');
      if (!titleButton) {
        return false;
      }
      return !!titleButton.closest('.wr-card__item');
    };

    const openEditorForItem = (itemEl) => {
      if (!itemEl || typeof window === 'undefined') {
        return;
      }
      if (!window.foodordModal || typeof window.foodordModal.openModal !== 'function') {
        return;
      }

      const productId = parseInt(itemEl.getAttribute('data-product-id'), 10) || 0;
      const cartItemKey = itemEl.getAttribute('data-cart-item-key') || '';
      if (!productId || !cartItemKey) {
        return;
      }
      const variationId = parseInt(itemEl.getAttribute('data-variation-id'), 10) || 0;
      const quantity = parseInt(itemEl.getAttribute('data-quantity'), 10) || 0;
      const toppingsSignature = itemEl.getAttribute('data-toppings-signature') || '';

      window.foodordModal.openModal(productId, {
        trigger: itemEl,
        cartItemKey: cartItemKey,
        variationId: variationId,
        quantity: quantity,
        toppingsSignature: toppingsSignature
      });
    };

    document.addEventListener('click', (event) => {
      const item = event.target.closest('.wr-card__item');
      if (!item || !isEditableClickTarget(event)) {
        return;
      }

      const cartItemKey = item.getAttribute('data-cart-item-key');
      if (!cartItemKey) {
        return;
      }

      event.preventDefault();
      event.stopPropagation();

      openEditorForItem(item);
    }, true);

    document.addEventListener('keydown', (event) => {
      if (!event || (event.key !== 'Enter' && event.key !== ' ')) {
        return;
      }
      const item = event.target.closest('.wr-card__item');
      if (!item || !isEditableClickTarget(event)) {
        return;
      }

      event.preventDefault();
      openEditorForItem(item);
    });
  };

  const updateCardUpsellNavState = (section) => {
    if (!section) {
      return;
    }

    const rail = section.querySelector('.foodord-modal-upsells__grid');
    const nav = section.querySelector('.foodord-modal-upsells__nav');
    const prevButton = section.querySelector('[data-foodord-upsells-scroll="prev"]');
    const nextButton = section.querySelector('[data-foodord-upsells-scroll="next"]');

    if (!rail || !nav || !prevButton || !nextButton) {
      return;
    }

    const cards = Array.from(rail.querySelectorAll('.foodord-modal-upsells__item'));
    const railWidth = Math.ceil(rail.clientWidth);
    const hasOverflow = cards.some((card) => Math.ceil(card.offsetLeft + card.offsetWidth) > (railWidth + 1));

    nav.hidden = !hasOverflow;

    if (!hasOverflow) {
      prevButton.disabled = true;
      nextButton.disabled = true;
      return;
    }

    const maxScrollLeft = Math.max(0, rail.scrollWidth - rail.clientWidth);
    const tolerance = 4;

    prevButton.disabled = rail.scrollLeft <= tolerance;
    nextButton.disabled = rail.scrollLeft >= (maxScrollLeft - tolerance);
  };

  const initCardUpsellSections = (scope = document) => {
    const sections = scope.querySelectorAll('.wr-card__upsells .foodord-modal-upsells');

    sections.forEach((section) => {
      const rail = section.querySelector('.foodord-modal-upsells__grid');
      if (!rail) {
        return;
      }

      if (rail.dataset.foodordUpsellScrollBound !== 'true') {
        rail.addEventListener('scroll', () => updateCardUpsellNavState(section), { passive: true });
        rail.dataset.foodordUpsellScrollBound = 'true';
      }

      updateCardUpsellNavState(section);
    });
  };

  const initCartUpsells = () => {
    if (cartUpsellListenersInitialized) {
      return;
    }

    cartUpsellListenersInitialized = true;

    document.addEventListener('click', (event) => {
      const trigger = event.target.closest('[data-foodord-card-upsell-trigger="true"]');
      if (!trigger || !trigger.closest('.wr-card__body')) {
        return;
      }

      event.preventDefault();
      event.stopPropagation();

      const productId = parseInt(trigger.getAttribute('data-product-id'), 10) || 0;
      if (!productId || !window.foodordModal || typeof window.foodordModal.openModal !== 'function') {
        return;
      }

      window.foodordModal.openModal(productId, { trigger: trigger });
    });

    document.addEventListener('click', (event) => {
      const button = event.target.closest('[data-foodord-upsells-scroll]');
      if (!button || !button.closest('.wr-card__body')) {
        return;
      }

      const section = button.closest('.foodord-modal-upsells');
      const rail = section ? section.querySelector('.foodord-modal-upsells__grid') : null;
      if (!section || !rail) {
        return;
      }

      event.preventDefault();

      const direction = button.getAttribute('data-foodord-upsells-scroll');
      const firstCard = rail.querySelector('.foodord-modal-upsells__item');
      const cardRect = firstCard ? firstCard.getBoundingClientRect() : null;
      const railStyle = window.getComputedStyle(rail);
      const gap = parseFloat(railStyle.gap || railStyle.columnGap || '12') || 12;
      const scrollAmount = cardRect ? Math.round(cardRect.width + gap) : Math.round(rail.clientWidth * 0.8);

      rail.scrollBy({
        left: direction === 'prev' ? -scrollAmount : scrollAmount,
        behavior: 'smooth'
      });

      window.setTimeout(() => updateCardUpsellNavState(section), 220);
    });

    window.addEventListener('resize', () => initCardUpsellSections(document));
  };

  const initCheckoutButton = () => {
    // Prevent duplicate event listeners
    if (checkoutEventListenersInitialized) {
      return;
    }
    checkoutEventListenersInitialized = true;

    // Handle checkout button click with event delegation
    document.addEventListener('click', function (e) {
      const checkoutBtn = e.target.closest('.wr-card__cta');
      if (checkoutBtn && !checkoutBtn.disabled && !checkoutBtn.classList.contains('disabled')) {
        e.preventDefault();
        e.stopPropagation();

        // Get action from data attribute
        const action = checkoutBtn.getAttribute('data-action') || 'checkout';
        const checkoutUrl = checkoutBtn.getAttribute('data-checkout-url');
        const isCheckout = checkoutBtn.getAttribute('data-is-checkout') === 'true';

        if (action === 'order' || isCheckout) {
          // On checkout page: trigger order submission
          triggerOrderSubmission();
        } else {
          // On other pages: navigate to checkout
          if (checkoutUrl) {
            window.location.href = checkoutUrl;
          } else {
            // Fallback to getCheckoutUrl function
            const fallbackUrl = getCheckoutUrl();
            if (fallbackUrl) {
              window.location.href = fallbackUrl;
            }
          }
        }
      }
    });
  };

  const isCheckoutPage = () => {
    // Primary: Check from foodord_modal_vars (WooCommerce is_checkout() function)
    if (typeof foodord_modal_vars !== 'undefined' && typeof foodord_modal_vars.is_checkout_page !== 'undefined') {
      return foodord_modal_vars.is_checkout_page;
    }

    // Fallback: Check URL and body classes
    const currentUrl = window.location.href.toLowerCase();
    const bodyClassList = document.body.classList;

    return (
      currentUrl.includes('/checkout') ||
      currentUrl.includes('/odeme') ||
      currentUrl.includes('/kasa') ||
      bodyClassList.contains('woocommerce-checkout') ||
      bodyClassList.contains('checkout-page')
    );
  };

  const getCheckoutUrl = () => {
    // Primary: Try to get checkout URL from foodord_modal_vars (WooCommerce function)
    if (typeof foodord_modal_vars !== 'undefined' && foodord_modal_vars.checkout_url) {
      return foodord_modal_vars.checkout_url;
    }

    // Fallback 1: try to find WooCommerce checkout links on the page
    const checkoutLinks = document.querySelectorAll('a[href*="checkout"], a[href*="odeme"], a[href*="kasa"]');
    if (checkoutLinks.length > 0) {
      return checkoutLinks[0].href;
    }

    // Fallback 2: check for WooCommerce body classes or meta tags
    const bodyClassList = document.body.classList;
    const currentUrl = new URL(window.location.href);

    // If we're on a WooCommerce site, try common checkout URL patterns
    if (bodyClassList.contains('woocommerce') || bodyClassList.contains('woocommerce-page')) {
      // Try Turkish checkout URLs first
      const turkishPatterns = ['/odeme/', '/kasa/', '/checkout/', '/sepet-odeme/'];
      for (const pattern of turkishPatterns) {
        return currentUrl.origin + pattern;
      }
    }

    // Final fallback: standard checkout URL
    return currentUrl.origin + '/checkout/';
  };

  const triggerOrderSubmission = () => {
    // Priority 1: Try to find WooCommerce Blocks checkout button (new)
    const blocksCheckoutBtn = document.querySelector('.wc-block-components-checkout-place-order-button, .wc-block-components-button.wc-block-components-checkout-place-order-button');
    if (blocksCheckoutBtn && !blocksCheckoutBtn.disabled && blocksCheckoutBtn.offsetParent !== null) {
      blocksCheckoutBtn.click();
      return;
    }

    // Priority 2: Try to find classic WooCommerce place order button (legacy)
    const classicPlaceOrderBtn = document.querySelector('#place_order, button#place_order');
    if (classicPlaceOrderBtn && !classicPlaceOrderBtn.disabled && classicPlaceOrderBtn.offsetParent !== null) {
      classicPlaceOrderBtn.click();
      return;
    }

    // Priority 3: Try to find checkout form and submit it
    const checkoutForm = document.querySelector('form.checkout, form.woocommerce-checkout, form[name="checkout"]');
    if (checkoutForm) {
      // Look for submit buttons within the form
      const submitBtns = checkoutForm.querySelectorAll('button[type="submit"], input[type="submit"]');
      if (submitBtns.length > 0) {
        submitBtns[0].click();
        return;
      }

      // If no submit button found, submit the form directly
      checkoutForm.submit();
      return;
    }

    // Priority 4: Try other common WooCommerce checkout button selectors (both classic and blocks)
    const altButtons = document.querySelectorAll(
      '.wc-block-components-button.wp-element-button, ' +
      '.wc-block-components-button.contained, ' +
      '.wp-block-woocommerce-checkout-place-order-block button, ' +
      'input[name="woocommerce_checkout_place_order"], ' +
      'button[name="woocommerce_checkout_place_order"], ' +
      '.woocommerce-checkout-payment button[type="submit"], ' +
      '.place-order button, ' +
      'button[value="Place order"], ' +
      'button:contains("Place order"), ' +
      'button:contains("Complete order")'
    );

    if (altButtons.length > 0) {
      altButtons[0].click();
      return;
    }

    // Final fallback: Try to scroll to checkout area
    const checkoutArea = document.querySelector('.woocommerce-checkout, #checkout, .checkout');
    if (checkoutArea) {
      checkoutArea.scrollIntoView({ behavior: 'smooth' });
      // Flash the checkout area to draw attention
      checkoutArea.classList.add('wr-checkout-highlight');
      setTimeout(() => {
        checkoutArea.classList.remove('wr-checkout-highlight');
      }, 3000);
    }
  };

  const showClearCartModal = () => {
    // Check if cart has items
    const cartItems = document.querySelectorAll('.wr-card__item');

    if (cartItems.length === 0) {
      return;
    }

    // Check if modal is already active
    const existingModal = document.querySelector('.wr-card__modal-overlay.active');
    if (existingModal) {
      return;
    }

    // Remove any existing modals first
    const oldModals = document.querySelectorAll('.wr-card__modal-overlay');
    oldModals.forEach(modal => modal.remove());

    // Create and show new modal
    const modal = createClearCartModal();
    document.body.appendChild(modal);

    // Force reflow before adding active class
    modal.offsetHeight;

    // Show modal with animation
    requestAnimationFrame(() => {
      modal.classList.add('active');

      // Focus on confirm button for accessibility
      setTimeout(() => {
        const confirmBtn = modal.querySelector('.wr-card__modal-btn--confirm');
        if (confirmBtn) {
          confirmBtn.focus();
        }
      }, 150);
    });
  };

  const hideClearCartModal = () => {
    const modal = document.querySelector('.wr-card__modal-overlay.active');
    if (modal) {
      modal.classList.remove('active');

      // Remove modal after animation completes
      setTimeout(() => {
        if (modal.parentNode) {
          modal.remove();
        }
      }, 300);
    }
  };

  const createClearCartModal = () => {
    const modal = document.createElement('div');
    const message = escapeHtml(
      getI18nString('clearCartConfirmMessage') || 'Are you sure you want to clear all items from your cart?'
    );
    const cancelText = escapeHtml(getI18nString('cancel') || 'Cancel');
    const clearCartText = escapeHtml(getI18nString('clearCart') || 'Clear Cart');

    modal.className = 'wr-card__modal-overlay';
    modal.innerHTML = `
      <div class="wr-card__modal">
        <div class="wr-card__modal-header">
          <p class="wr-card__modal-message">${message}</p>
          <button type="button" class="wr-card__modal-close" aria-label="Close">
            <span class="wr-card__modal-close-icon"></span>
          </button>
        </div>
        <div class="wr-card__modal-actions">
          <button type="button" class="wr-card__modal-btn wr-card__modal-btn--cancel">${cancelText}</button>
          <button type="button" class="wr-card__modal-btn wr-card__modal-btn--confirm">${clearCartText}</button>
        </div>
      </div>
    `;
    return modal;
  };

  const setClearCartModalLoadingState = (isLoading) => {
    const modal = document.querySelector('.wr-card__modal-overlay.active');
    if (!modal) {
      return;
    }

    const confirmButton = modal.querySelector('.wr-card__modal-btn--confirm');

    modal.classList.toggle('wr-card__modal-overlay--loading', isLoading);
    if (isLoading) {
      modal.setAttribute('aria-busy', 'true');
    } else {
      modal.removeAttribute('aria-busy');
    }

    if (confirmButton) {
      confirmButton.disabled = isLoading;
      confirmButton.classList.toggle('is-loading', isLoading);
      if (isLoading) {
        confirmButton.setAttribute('aria-busy', 'true');
      } else {
        confirmButton.removeAttribute('aria-busy');
      }
    }
  };

  const clearCart = () => {
    // Get cart items
    const cartItems = document.querySelectorAll('.wr-card__item');

    if (cartItems.length === 0) {
      hideClearCartModal();
      return;
    }

    // Disable all clear buttons immediately
    const clearButtons = document.querySelectorAll('.wr-card__clear-btn');
    clearButtons.forEach(button => {
      button.disabled = true;
    });
    setClearCartModalLoadingState(true);

    // AJAX call to clear cart first
    if (typeof jQuery !== 'undefined' && typeof foodord_modal_vars !== 'undefined') {
      jQuery.post(foodord_modal_vars.ajax_url, {
        action: 'foodord_clear_cart',
        nonce: foodord_modal_vars.nonce
      }, function (response) {
        if (response.success) {
          // Immediately disable CTA and set total to zero (formatted if available)
          const ctaBtn = document.querySelector('.wr-card__cta');
          if (ctaBtn) {
            ctaBtn.classList.add('disabled');
            ctaBtn.disabled = true;
            ctaBtn.setAttribute('aria-disabled', 'true');
            const totalEl = ctaBtn.querySelector('.wr-card__cta-total');
            if (totalEl) {
              if (typeof window.foodord_modal_vars !== 'undefined' && window.foodord_modal_vars.cart_zero_html) {
                totalEl.innerHTML = window.foodord_modal_vars.cart_zero_html;
              } else {
                totalEl.textContent = '0';
              }
            }
          }

          // Remove all items immediately without animation
          cartItems.forEach((item) => {
            if (item.parentNode) {
              item.remove();
            }
          });
          showEmptyCartState();


          // Update cart fragments if available
          if (response.data && response.data.fragments) {
            jQuery.each(response.data.fragments, function (key, value) {
              jQuery(key).replaceWith(value);
            });
          }

          // Update delivery fee and minimum notice
          if (response.data) {
            updateDeliveryFee(response.data);
            if (typeof updateMinimumNotice === 'function') {
              updateMinimumNotice(response.data);
            }
          }

          // Dispatch custom event for mobile cart
          document.dispatchEvent(new CustomEvent('foodord_cart_updated', { detail: response.data }));
          setClearCartModalLoadingState(false);
          hideClearCartModal();
        } else {
          // Re-enable buttons on error
          clearButtons.forEach(button => {
            button.disabled = false;
          });
          setClearCartModalLoadingState(false);
        }
      }).fail(function () {
        // Re-enable buttons on network error
        clearButtons.forEach(button => {
          button.disabled = false;
        });
        setClearCartModalLoadingState(false);
      });
    } else {
      // Fallback: immediate UI update
      showEmptyCartState();
      setClearCartModalLoadingState(false);
      hideClearCartModal();
    }
  };

  const showEmptyCartState = () => {
    const cartBodies = document.querySelectorAll('.wr-card__body');
    if (cartBodies.length === 0) {
      return;
    }

    cartBodies.forEach(cartBody => {
      const emptyText = escapeHtml(getI18nString('emptyCartText'));
      const emptySubtext = escapeHtml(getI18nString('emptyCartSubtext'));
      cartBody.innerHTML = `
        <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>
      `;
    });
    syncCardEmptyState();

    syncCardBodyOffsets();

    // Remove any minimum notice

    const footers = document.querySelectorAll('.wr-card__footer');
    footers.forEach((footer) => {
      const notice = footer.querySelector('.wr-card__min-notice');
      if (notice) notice.remove();
    });

    // Update footer button
    const ctaButton = document.querySelector('.wr-card__cta');
    if (ctaButton) {
      ctaButton.classList.add('disabled');
      ctaButton.disabled = true;
      ctaButton.setAttribute('aria-disabled', 'true');
      ctaButton.classList.add('wr-card__cta--disabled');

      const totalEl = ctaButton.querySelector('.wr-card__cta-total');
      if (totalEl) {
        if (typeof window.foodord_modal_vars !== 'undefined' && window.foodord_modal_vars.cart_zero_html) {
          totalEl.innerHTML = window.foodord_modal_vars.cart_zero_html;
        } else {
          totalEl.textContent = '0';
        }
      }
      const countEl = ctaButton.querySelector('.wr-card__cta-count');
      if (countEl) {
        countEl.textContent = '0';
      }
      updateCheckoutButtonText();
    }

    // Update clear button state and badge
    updateClearButtonState();
    updateCartCountBadge();
  };

  const normalizeOrderMode = (mode) => {
    if (mode === 'pickup' || mode === 'delivery') {
      return mode;
    }
    return null;
  };

  let cachedOrderMode = null;

  const readOrderModeFromSources = () => {
    let mode = null;

    if (!mode && typeof window !== 'undefined') {
      if (window.foodord_location_vars && window.foodord_location_vars.mode) {
        mode = normalizeOrderMode(window.foodord_location_vars.mode);
      } else if (window.FoodordDeliveryPickup && window.FoodordDeliveryPickup.currentMode) {
        mode = normalizeOrderMode(window.FoodordDeliveryPickup.currentMode);
      }
    }

    if (!mode) {
      const hiddenField = document.querySelector('input[name="foodord_order_mode"]');
      if (hiddenField) {
        mode = normalizeOrderMode(hiddenField.value);
      }
    }
    return mode || 'delivery';
  };

  const setCachedOrderMode = (mode) => {
    const normalized = normalizeOrderMode(mode);
    if (normalized) {
      cachedOrderMode = normalized;
    }
  };

  const getCurrentOrderMode = (forceRefresh = false) => {
    if (forceRefresh || !cachedOrderMode) {
      cachedOrderMode = readOrderModeFromSources();
    }
    return cachedOrderMode;
  };

  let locationGateRetryAttempts = 0;

  const isLocationRequirementMet = (modeCandidate) => {
    if (isTableOrderingContext()) {
      return true;
    }

    const effectiveMode = normalizeOrderMode(modeCandidate) || getCurrentOrderMode(true);
    if (effectiveMode === 'pickup') {
      return true;
    }
    if (typeof window.foodordHasLocation === 'function') {
      try {
        return !!window.foodordHasLocation();
      } catch (err) {
        void err;
        return false;
      }
    }
    return true;
  };

  const shouldGateCTAForLocation = (modeCandidate) => {
    if (isTableOrderingContext()) {
      return false;
    }

    const effectiveMode = normalizeOrderMode(modeCandidate) || getCurrentOrderMode(true);
    if (effectiveMode === 'pickup') {
      return false;
    }
    return !isLocationRequirementMet(effectiveMode);
  };

  const enforceLocationGateOnCTA = (modeCandidate) => {
    const effectiveMode = normalizeOrderMode(modeCandidate) || getCurrentOrderMode(true);
    const shouldDisable = shouldGateCTAForLocation(effectiveMode);
    if (shouldDisable) {
      const ctas = document.querySelectorAll('.wr-card__cta');
      ctas.forEach((ctaBtn) => {
        disableCTAButton(ctaBtn);
      });
    }
    if (typeof window.foodordHasLocation !== 'function' && locationGateRetryAttempts < 10) {
      locationGateRetryAttempts += 1;
      window.setTimeout(() => {
        enforceLocationGateOnCTA(effectiveMode);
      }, 150);
    } else if (typeof window.foodordHasLocation === 'function') {
      locationGateRetryAttempts = 0;
    }
  };

  /**
   * Check if minimum order amount is met
   */
  const isMinimumOrderMet = (mode) => {
    if (isTableOrderingContext()) {
      return true;
    }

    const effectiveMode = normalizeOrderMode(mode) || getCurrentOrderMode();
    if (effectiveMode === 'pickup') {
      return true;
    }
    // Check if we have minimum order params
    if (typeof foodord_block_checkout_params !== 'undefined') {
      const minimumAmount = parseFloat(foodord_block_checkout_params.minimum_order_amount);
      if (minimumAmount && minimumAmount > 0) {
        // Get cart total
        const totalEl = document.querySelector('.wr-card__cta-total');
        if (totalEl) {
          const totalTextRaw = totalEl.textContent;
          let sanitizedText = totalTextRaw.replace(/[^\d.,]/g, '');
          const lastDot = sanitizedText.lastIndexOf('.');
          const lastComma = sanitizedText.lastIndexOf(',');
          
          if (lastComma > lastDot) {
            if (lastDot !== -1 || sanitizedText.length - lastComma - 1 !== 3) {
              sanitizedText = sanitizedText.replace(/\./g, '').replace(',', '.');
            } else {
              sanitizedText = sanitizedText.replace(/,/g, '');
            }
          } else if (lastDot > lastComma) {
            if (lastComma !== -1 || sanitizedText.length - lastDot - 1 !== 3) {
              sanitizedText = sanitizedText.replace(/,/g, '');
            } else {
              sanitizedText = sanitizedText.replace(/\./g, '');
            }
          }
          
          const cartTotal = parseFloat(sanitizedText) || 0;
          return cartTotal >= minimumAmount;
        }
      }
    }
    // If no minimum is set or can't check, return true
    return true;
  };

  const updateClearButtonState = () => {
    syncCardEmptyState();
    const clearButtons = document.querySelectorAll('.wr-card__clear-btn');

    // Simple check: if any .wr-card__empty exists, cart is empty
    const emptyStates = document.querySelectorAll('.wr-card__empty');
    const cartItems = document.querySelectorAll('.wr-card__item');

    // Cart is empty if there's an empty state element OR no cart items
    const isEmpty = emptyStates.length > 0 || cartItems.length === 0;

    // Update Clear buttons
    clearButtons.forEach((clearButton) => {
      if (clearButton) {
        clearButton.disabled = isEmpty;
        if (isEmpty) {
          clearButton.setAttribute('aria-disabled', 'true');
        } else {
          clearButton.removeAttribute('aria-disabled');
        }
      }
    });

    // Update CTA button consistently based on isEmpty and minimum order
    const ctaButton = document.querySelector('.wr-card__cta');
    if (ctaButton) {
      const currentMode = getCurrentOrderMode(true);
      const minimumMet = currentMode === 'pickup' ? true : isMinimumOrderMet(currentMode);

      if (isEmpty) {
        disableCTAButton(ctaButton);
        const totalEl = ctaButton.querySelector('.wr-card__cta-total');
        if (totalEl) {
          if (typeof window.foodord_modal_vars !== 'undefined' && window.foodord_modal_vars.cart_zero_html) {
            totalEl.innerHTML = window.foodord_modal_vars.cart_zero_html;
          } else {
            totalEl.textContent = '0';
          }
        }
      } else if (!minimumMet) {
        disableCTAButton(ctaButton);
      } else {
        enableCTAButton(ctaButton, currentMode);
      }
    }

    // Always update count badge after state check
    updateCartCountBadge();
  };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initCard);
  } else {
    initCard();
  }

  // Listen for WooCommerce cart updates and reload cart items
  if (typeof jQuery !== 'undefined') {
    jQuery(document).on('added_to_cart removed_from_cart updated_cart_totals wc_fragments_refreshed', function () {
      // Reload cart items with delivery fee after a short delay
      setTimeout(function () {
        if (typeof window.FoodordCard !== 'undefined' && window.FoodordCard.loadCartItems) {
          window.FoodordCard.loadCartItems();
        }
      }, 100);
    });
  }
  window.addEventListener('resize', scheduleCardBodyOffsetSync);
  document.addEventListener('foodord_cart_updated', handleCartUpdated);
  document.addEventListener('foodord:locationSelected', function () {
    try {
      if (window.FoodordCard && typeof window.FoodordCard.loadCartItems === 'function') {
        setTimeout(function () { window.FoodordCard.loadCartItems(); }, 80);
      }
    } catch (e) { void e; }
  });

  let cartReloadTimer;
  const scheduleCartReload = (delay, options = {}) => {
    const wait = typeof delay === 'number' ? delay : 200;
    if (cartReloadTimer) {
      window.clearTimeout(cartReloadTimer);
    }
    cartReloadTimer = window.setTimeout(() => {
      cartReloadTimer = null;
      loadCartItems(options);
    }, Math.max(0, wait));
  };

  document.addEventListener('wrc:deliveryModeChange', function (event) {
    if (event && event.detail && (event.detail.mode === 'delivery' || event.detail.mode === 'pickup')) {
      setCachedOrderMode(event.detail.mode);
      enforceLocationGateOnCTA(event.detail.mode);
      if (event.detail.source !== 'init') {
        scheduleCartReload(600, { showSkeleton: false });
      }
    }
  });

  // Helpers to compute and update the CTA badge count
  const computeCartCountFromDOM = () => {
    const items = document.querySelectorAll('.wr-card__item');
    if (!items.length) return 0;
    let total = 0;
    items.forEach((item) => {
      const qtyAttr = item.getAttribute('data-quantity');
      const qty = qtyAttr ? parseInt(qtyAttr, 10) : 1;
      total += isNaN(qty) ? 0 : qty;
    });
    return total;
  };

  const updateCartCountBadge = (forcedCount) => {
    syncCardEmptyState();
    const ctaButton = document.querySelector('.wr-card__cta');
    if (!ctaButton) return;
    const countEl = ctaButton.querySelector('.wr-card__cta-count');
    if (!countEl) return;

    let count = typeof forcedCount === 'number' ? forcedCount : computeCartCountFromDOM();
    if (count < 0 || isNaN(count)) count = 0;
    countEl.textContent = String(count);
  };

  // Reset function for re-initialization
  const resetEventListeners = () => {
    eventListenersInitialized = false;
    checkoutEventListenersInitialized = false;
  };

  // Helper function to update CTA button total
  const updateCTATotal = (totalHtml) => {
    const ctaButtons = document.querySelectorAll('.wr-card__cta');
    ctaButtons.forEach((ctaBtn) => {
      const totalEl = ctaBtn.querySelector('.wr-card__cta-total');
      if (totalEl && totalHtml) {
        totalEl.innerHTML = totalHtml;
      }
    });
  };

  // Helper function to update delivery fee display
  const updateDeliveryFee = (data) => {
    if (!data) {
      return;
    }

    const footers = document.querySelectorAll('.wr-card__footer');
    footers.forEach((footer) => {
      // Remove existing subtotal and delivery fee displays
      const existingSubtotal = footer.querySelector('.wr-card__subtotal');
      const existingFee = footer.querySelector('.wr-card__delivery-fee');
      const existingFeesWrapper = footer.querySelector('.wr-card__fees');
      if (existingSubtotal) {
        existingSubtotal.remove();
      }
      if (existingFee) {
        existingFee.remove();
      }
      if (existingFeesWrapper) {
        existingFeesWrapper.remove();
      }

      const ctaBtn = footer.querySelector('.wr-card__cta');
      if (!ctaBtn) return;
      const cartCount = typeof data.cart_count !== 'undefined' ? Number(data.cart_count) : 0;

      const minimumActive = !isTableOrderingContext() && !!data.minimum_active;
      const minimumPassed = !!data.minimum_passed;
      const minimumRequired = typeof data.minimum_required !== 'undefined' ? Number(data.minimum_required) : 0;
      const gateShowFee = !isTableOrderingContext() && ((!minimumActive) || minimumPassed || minimumRequired === 0);

      // Add subtotal display only when cart has items
      if (cartCount > 0 && data.subtotal_html) {
        const subtotalDiv = document.createElement('div');
        subtotalDiv.className = 'wr-card__subtotal';
        const subtotalLabelText = I18N.subtotal || '';
        subtotalDiv.innerHTML = `
          <div class="wr-card__subtotal-info">
            <span class="wr-card__subtotal-label">${subtotalLabelText}</span>
          </div>
          <span class="wr-card__subtotal-amount">${data.subtotal_html}</span>
        `;
        footer.insertBefore(subtotalDiv, ctaBtn);
      }

      // Add delivery fee display when minimum reached (or no minimum/0) and fee > 0
      if (gateShowFee && data.delivery_fee > 0 && data.delivery_fee_html) {
        const feeDiv = document.createElement('div');
        feeDiv.className = 'wr-card__delivery-fee';
        const deliveryLabelText = I18N.deliveryFee || '';
        feeDiv.innerHTML = `
          <div class="wr-card__delivery-info">
            <span class="wr-card__delivery-label">${deliveryLabelText}</span>
          </div>
          <span class="wr-card__delivery-amount">${data.delivery_fee_html}</span>
        `;
        footer.insertBefore(feeDiv, ctaBtn);
      }

      if (!isTableOrderingContext() && Array.isArray(data.fees) && data.fees.length > 0) {
        const feesWrapper = document.createElement('div');
        feesWrapper.className = 'wr-card__fees';

        data.fees.forEach((fee) => {
          if (!fee || !fee.label || !fee.amount_html) {
            return;
          }
          const feeRow = document.createElement('div');
          feeRow.className = 'wr-card__fee';

          const labelSpan = document.createElement('span');
          labelSpan.className = 'wr-card__fee-label';
          labelSpan.textContent = fee.label;

          const amountSpan = document.createElement('span');
          amountSpan.className = 'wr-card__fee-amount';
          amountSpan.innerHTML = fee.amount_html;

          feeRow.appendChild(labelSpan);
          feeRow.appendChild(amountSpan);
          feesWrapper.appendChild(feeRow);
        });

        if (feesWrapper.children.length > 0) {
          footer.insertBefore(feesWrapper, ctaBtn);
        }
      }
    });

    syncCardBodyOffsets();
  };

  const disableCTAButton = (ctaBtn) => {
    if (!ctaBtn) {
      return;
    }
    if (!ctaBtn.classList.contains('disabled')) {
      ctaBtn.classList.add('disabled');
    }
    ctaBtn.classList.add('wr-card__cta--disabled');
    ctaBtn.disabled = true;
    ctaBtn.setAttribute('aria-disabled', 'true');
  };

  const enableCTAButton = (ctaBtn, modeCandidate) => {
    if (!ctaBtn) {
      return;
    }
    if (shouldGateCTAForLocation(modeCandidate)) {
      disableCTAButton(ctaBtn);
      return;
    }
    ctaBtn.classList.remove('disabled');
    ctaBtn.classList.remove('wr-card__cta--disabled');
    ctaBtn.disabled = false;
    ctaBtn.removeAttribute('aria-disabled');
  };

  // Helper: show/hide minimum order notice and enforce CTA disabled state
  const updateMinimumNotice = (data) => {
    if (!data) return;
    const active = !isTableOrderingContext() && !!data.minimum_active;
    const passed = !!data.minimum_passed;
    const count = typeof data.cart_count !== 'undefined' ? Number(data.cart_count) : null;
    const currentMode = getCurrentOrderMode(true);
    const shouldShow = currentMode === 'delivery' && active && !passed && count !== null && count > 0;
    const minHtml = data.minimum_required_html || '';
    const remainHtml = data.remaining_to_minimum_html || '';
    const startHtml = data.minimum_floor_html || '0';
    const minimumRequired = Number(data.minimum_required);
    const remainingToMinimum = Number(data.remaining_to_minimum);
    const progressValue = Number.isFinite(minimumRequired) && minimumRequired > 0 && Number.isFinite(remainingToMinimum)
      ? Math.max(0, Math.min(100, ((minimumRequired - remainingToMinimum) / minimumRequired) * 100))
      : 0;
    const progressStep = Math.round(progressValue / 5) * 5;

    const footers = document.querySelectorAll('.wr-card__footer');
    footers.forEach((footer) => {
      const ctaBtn = footer.querySelector('.wr-card__cta');
      let notice = footer.querySelector('.wr-card__min-notice');

      if (shouldShow) {
        const minOrderTemplate = I18N.minOrderNotice || '';
        const noticeText = minOrderTemplate
          ? minOrderTemplate
            .replace('%1$s', `<strong class="wr-card__min-notice-amount">${remainHtml}</strong>`)
            .replace(/\s*%2\$s/g, '')
          : `Add <strong class="wr-card__min-notice-amount">${remainHtml}</strong> more to reach the minimum order.`;
        if (!notice) {
          notice = document.createElement('div');
          notice.className = 'wr-card__notice wr-card__notice--warning wr-card__min-notice';
          notice.setAttribute('role', 'status');

          if (ctaBtn) {
            footer.insertBefore(notice, ctaBtn);
          } else {
            footer.appendChild(notice);
          }
        }
        notice.setAttribute('data-foodord-min-progress', String(progressStep));
        notice.innerHTML = `
          <span class="wr-card__notice-text">${noticeText}</span>
          <span class="wr-card__min-progress" aria-hidden="true">
            <span class="wr-card__min-progress-edge wr-card__min-progress-edge--start">${startHtml}</span>
            <span class="wr-card__min-progress-track">
              <span class="wr-card__min-progress-fill"></span>
            </span>
            <span class="wr-card__min-progress-edge wr-card__min-progress-edge--end">${minHtml}</span>
          </span>
        `;

        // Enforce disabled CTA
        disableCTAButton(ctaBtn);
      } else if (notice) {
        notice.remove();
        if (ctaBtn && (count === null || count > 0)) {
          enableCTAButton(ctaBtn, currentMode);
        }
      }
    });

    syncCardBodyOffsets();
  };

  // Helper function to update entire CTA button state
  const updateCTAState = (data) => {
    const ctaButtons = document.querySelectorAll('.wr-card__cta');
    const cartCount = data && typeof data.cart_count !== 'undefined' ? Number(data.cart_count) : null;
    const cartTotalHtml = data && data.cart_total_html ? data.cart_total_html : null;
    const minimumActive = !isTableOrderingContext() && !!(data && data.minimum_active);
    const minimumPassed = !!(data && data.minimum_passed);
    if (data && data.mode) {
      setCachedOrderMode(data.mode);
    }
    const currentMode = getCurrentOrderMode(true);

    ctaButtons.forEach((ctaBtn) => {
      if (cartTotalHtml) {
        const totalEl = ctaBtn.querySelector('.wr-card__cta-total');
        if (totalEl && totalEl.innerHTML !== cartTotalHtml) {
          totalEl.innerHTML = cartTotalHtml;
        }
      }

      if (cartCount !== null) {
        const countEl = ctaBtn.querySelector('.wr-card__cta-count');
        if (countEl && countEl.textContent !== String(cartCount)) {
          countEl.textContent = String(cartCount);
        }

        const isEmpty = cartCount === 0;
        if (isEmpty) {
          disableCTAButton(ctaBtn);
        }

        // Enable CTA only when not empty AND minimum requirement is passed (or not active)
        const shouldDisableForMinimum = !isEmpty && currentMode === 'delivery' && minimumActive && !minimumPassed;
        const shouldDisableForLocation = !isEmpty && shouldGateCTAForLocation(currentMode);
        
        if (!isEmpty) {
          if (shouldDisableForMinimum || shouldDisableForLocation) {
            disableCTAButton(ctaBtn);
          } else {
            enableCTAButton(ctaBtn, currentMode);
          }
        }
      }

    });

    if (data) {
      updateDeliveryFee(data);
      updateMinimumNotice(data);
    }

    enforceLocationGateOnCTA(currentMode);
    updateCheckoutButtonText();
  };

  // Function to update button text based on page context
  function updateCheckoutButtonText() {
    const ctaButtons = document.querySelectorAll('.wr-card__cta');
    const isCheckout = isCheckoutPage();

    ctaButtons.forEach((ctaBtn) => {
      const labelEl = ctaBtn.querySelector('.wr-card__cta-label');
      if (labelEl) {
        // Get text from foodord_modal_vars if available, otherwise use fallback
        let buttonText;
        if (typeof foodord_modal_vars !== 'undefined' && foodord_modal_vars.checkout_btn_text) {
          buttonText = foodord_modal_vars.checkout_btn_text;
        } else {
          if (isCheckout) {
            buttonText = I18N.orderAndPay || '';
          } else {
            buttonText = I18N.checkout || '';
          }
        }
        labelEl.textContent = buttonText;
      }
    });
  }

  // Function to load and display cart items
  const applyCartResponse = (responseData) => {
    if (!responseData) {
      return;
    }

    if (typeof responseData.cart_hash === 'string') {
      lastAppliedCartHash = responseData.cart_hash;
    }

    if (Object.prototype.hasOwnProperty.call(responseData, 'show_topping_group_labels')) {
      setShowToppingGroupLabels(responseData.show_topping_group_labels);
    }

    renderCartItems(responseData.cart_items || [], responseData);
    updateCTAState(responseData);
    updateClearButtonState();
    updateCartCountBadge(responseData.cart_count);
    updateDeliveryFee(responseData);
    updateMinimumNotice(responseData);
  };

  function handleCartUpdated(event) {
    const responseData = event && event.detail ? event.detail : null;

    if (
      responseData &&
      typeof responseData.cart_hash === 'string' &&
      responseData.cart_hash !== '' &&
      responseData.cart_hash === lastAppliedCartHash
    ) {
      scheduleCardBodyOffsetSync();
      return;
    }

    if (
      responseData &&
      (
        Array.isArray(responseData.cart_items) ||
        typeof responseData.card_upsells_html === 'string'
      )
    ) {
      applyCartResponse(responseData);
      return;
    }

    scheduleCardBodyOffsetSync();
  }

  const loadCartItems = (options = {}) => {
    if (typeof jQuery === 'undefined' || typeof foodord_modal_vars === 'undefined') {
      return;
    }

    if (options.showSkeleton !== false) {
      showUpsellSkeleton();
    }

    jQuery.post(foodord_modal_vars.ajax_url, {
      action: 'foodord_get_cart_items',
      nonce: foodord_modal_vars.nonce
    }, function (response) {
      if (response.success && response.data) {
        applyCartResponse(response.data);
      }
    });
  };

  // Function to render cart items in the UI
  const renderCartItems = (cartItems, metadata = null) => {
    if (metadata && Object.prototype.hasOwnProperty.call(metadata, 'show_topping_group_labels')) {
      setShowToppingGroupLabels(metadata.show_topping_group_labels);
    }

    const cartBodies = document.querySelectorAll('.wr-card__body');
    if (cartBodies.length === 0) {
      return;
    }

    if (typeof window.FoodOrdModalFooter !== 'undefined') {
      if (Array.isArray(cartItems)) {
        window.FoodOrdModalFooter.setCartSnapshot(cartItems);
      } else {
        window.FoodOrdModalFooter.setCartSnapshot([]);
      }
    }

    if (!cartItems || cartItems.length === 0) {
      showEmptyCartState();
      return;
    }

    const upsellsHtml = areUpsellsEnabled() && metadata && typeof metadata.card_upsells_html === 'string'
      ? metadata.card_upsells_html
      : '';

    let itemsHtml = '<div class="wr-card__items">';
    cartItems.forEach((item) => {
      const toppingsHtml = renderToppings(item.toppings || []);
      // Calculate line total for display (unit price × quantity)
      const displayPrice = item.price || '';
      const noteMarkup = (window.FoodordCartNotes && typeof window.FoodordCartNotes.renderNoteMarkup === 'function')
        ? window.FoodordCartNotes.renderNoteMarkup(item, 'desktop', { includeToggle: false })
        : '';
      const noteToggleMarkup = (window.FoodordCartNotes && typeof window.FoodordCartNotes.renderNoteToggleMarkup === 'function')
        ? window.FoodordCartNotes.renderNoteToggleMarkup(item, 'desktop')
        : '';
      const cartItemKeyAttr = item && item.cart_item_key ? escapeHtml(String(item.cart_item_key)) : '';
      const noteAttr = item && typeof item.note === 'string' ? escapeHtml(item.note) : '';
      const signatureAttr = item && typeof item.toppings_signature === 'string' ? escapeHtml(item.toppings_signature) : '';
      const rawName = typeof item.name === 'string' ? item.name : '';
      const quantityValue = parseInt(item.quantity, 10) || 1;
      const minusIcon = quantityValue === 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 = quantityValue === 1 ? 'wr-card__quantity-btn minus trash' : 'wr-card__quantity-btn minus';

      const editLabel = escapeHtml(buildEditLabel(rawName));
      const displayName = escapeHtml(rawName);

      itemsHtml += `
        <div class="wr-card__item" data-product-id="${item.product_id}" data-variation-id="${item.variation_id}" data-quantity="${item.quantity}" data-cart-item-key="${cartItemKeyAttr}" data-note="${noteAttr}" data-toppings-signature="${signatureAttr}">
          <div class="wr-card__item-details">
            <h4 class="wr-card__item-title">
              <button type="button" class="wr-card__item-title-button" aria-label="${editLabel}">${displayName}</button>
            </h4>
            ${toppingsHtml}
            ${noteToggleMarkup}
          </div>
          <div class="wr-card__item-actions">
            <div class="wr-card__item-price">${displayPrice}</div>
            <div class="wr-card__item-quantity" data-quantity="${quantityValue}">
              <div class="wr-card__quantity-popover active">
                <button class="${minusClass}" data-action="minus">${minusIcon}</button>
                <span class="wr-card__quantity-value">${quantityValue}</span>
                <button class="wr-card__quantity-btn plus" data-action="plus"></button>
              </div>
            </div>
          </div>
          ${noteMarkup}
        </div>
      `;
    });
    itemsHtml += '</div>';

    if (upsellsHtml) {
      itemsHtml += `<div class="wr-card__upsells">${upsellsHtml}</div>`;
    }

    cartBodies.forEach(cartBody => {
      cartBody.innerHTML = itemsHtml;
      initCardUpsellSections(cartBody);
      if (window.FoodordUpsellSkeleton && typeof window.FoodordUpsellSkeleton.hydrateScope === 'function') {
        window.FoodordUpsellSkeleton.hydrateScope(cartBody);
      }
    });

    syncCardEmptyState();
    syncCardBodyOffsets();
  };

  // Function to render toppings HTML
  const renderToppings = (toppings) => {
    if (!Array.isArray(toppings) || toppings.length === 0) {
      return '';
    }

    const normalizeToppingText = (text) => {
      const raw = typeof text === 'string' ? text : '';
      const withSpacing = raw.replace(/([^\s])\(\+/g, '$1 (+');
      return escapeHtml(withSpacing);
    };

    const setsMarkup = toppings
      .map((set) => {
        if (!set || !Array.isArray(set.items) || set.items.length === 0) {
          return '';
        }

        const titleSource = typeof set.set_label === 'string' && set.set_label !== ''
          ? set.set_label
          : (typeof set.set_name === 'string' && set.set_name !== '' ? set.set_name : 'Toppings');
        const title = escapeHtml(titleSource);

        const itemsMarkup = set.items
          .map((item) => {
            if (typeof item !== 'string' || item === '') {
              return '';
            }
            return `<span class="wr-card__item-topping">${normalizeToppingText(item)}</span>`;
          })
          .filter(Boolean)
          .join('');

        if (!itemsMarkup) {
          return '';
        }

        const titleBlock = showToppingGroupLabels ? `<div class=\"wr-card__item-topping-title\">${title}</div>` : '';

        return `<div class=\"wr-card__item-topping-set\">${titleBlock}<div class=\"wr-card__item-topping-list\">${itemsMarkup}</div></div>`;
      })
      .filter(Boolean)
      .join('');

    if (!setsMarkup) {
      return '';
    }

    return `<div class=\"wr-card__item-toppings\">${setsMarkup}</div>`;
  };

  // Simple HTML escaping function
  const escapeHtml = (text) => {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  };

  const buildEditLabel = (name) => {
    const template = getI18nString('editItem');
    const normalizedName = typeof name === 'string' ? name : '';
    if (template) {
      if (template.indexOf('%s') !== -1) {
        return template.replace('%s', normalizedName);
      }
      return `${template} ${normalizedName}`.trim();
    }
    return `Edit ${normalizedName}`.trim();
  };

  // Expose for potential manual re-init after AJAX updates.
  window.FoodordCard = {
    init: initCard,
    showClearModal: showClearCartModal,
    hideClearModal: hideClearCartModal,
    applyCartResponse: applyCartResponse,
    showUpsellSkeleton: showUpsellSkeleton,
    updateClearButton: updateClearButtonState,
    updateCartCount: updateCartCountBadge,
    updateCTATotal: updateCTATotal,
    updateCTAState: updateCTAState,
    updateMinimumNotice: updateMinimumNotice,
    loadCartItems: loadCartItems,
    syncBodyOffsets: syncCardBodyOffsets,
    initCheckout: initCheckoutButton,
    getCheckoutUrl: getCheckoutUrl,
    isCheckoutPage: isCheckoutPage,
    triggerOrderSubmission: triggerOrderSubmission,
    updateCheckoutButtonText: updateCheckoutButtonText,
    reset: resetEventListeners
  };
})(window, document);
