/* FoodOrd Mobile Cart */

(function (window, document) {
  'use strict';

  const I18N = (typeof window.foodordMobileCartI18n === 'object' && window.foodordMobileCartI18n !== null)
    ? window.foodordMobileCartI18n
    : {};
  const getI18nString = (key) => (typeof I18N[key] === 'string') ? I18N[key] : '';
  const isTableOrderingContext = () => !!(window.foodordTableOrdering && window.foodordTableOrdering.token);
  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);
  };

  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>';
  let mobileCart = null;
  let isExpanded = false;
  let isInitialized = false;
  let currentCartCount = 0;
  let lastUpsellItemsSignature = '';
  let isPendingAddToCart = false;
  let pendingAddToCartTimer = null;
  let checkoutLoadingResetTimer = null;
  let mobileCartCloseTimer = null;
  const mobileCartAnimationMs = 320;
  let mobileCartItemEditInitialized = false;
  let mobileCartUpsellListenersInitialized = false;
  let upsellsEnabled = parseToggleValue(Object.prototype.hasOwnProperty.call(I18N, 'upsellsEnabled') ? I18N.upsellsEnabled : true);

  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;
  };

  // Check if screen is mobile (1024px and below)
  const isMobileScreen = () => {
    return window.innerWidth <= 1024;
  };

  // Check if current page has foodord products shortcode or block
  const hasFoodordProducts = () => {
    const hasShortcode = document.querySelector('.foodord-products-shortcode');
    const hasBlock = document.querySelector('.wp-block-foodord-card, .wp-block-foodord-products');
    const hasFallbackSidebar = document.querySelector('.foodord-sidebar');
    const hasCard = document.querySelector('.wr-card');
    const hasStandaloneToggle = document.querySelector('.foodord-order-toggle');

    return !!(hasShortcode || hasBlock || hasFallbackSidebar || hasCard || hasStandaloneToggle);
  };

  // Initialize mobile cart
  const initMobileCart = () => {
    if (isInitialized || !isMobileScreen() || !hasFoodordProducts()) {
      return;
    }

    createMobileCart();
    bindEvents();
    loadCartData();
    isInitialized = true;
  };

  let mobileCartModal = null;

  const emitMobileCartStateChange = () => {
    document.dispatchEvent(new CustomEvent('foodord_mobile_cart_state_changed', {
      detail: {
        visible: !!(mobileCart && !mobileCart.classList.contains('foodord-mobile-cart--hidden') && mobileCart.getAttribute('aria-hidden') !== 'true'),
        expanded: isExpanded
      }
    }));
  };

  const setTotalsLoadingState = (isLoading) => {
    if (!mobileCart) {
      return;
    }

    const totalEls = mobileCart.querySelectorAll('.foodord-mobile-cart__total');
    totalEls.forEach((totalEl) => {
      if (!totalEl) {
        return;
      }

      if (isLoading) {
        if (!totalEl.dataset.originalHtml) {
          totalEl.dataset.originalHtml = totalEl.innerHTML;
        }
        totalEl.classList.add('foodord-mobile-cart__total--loading');
        totalEl.setAttribute('aria-busy', 'true');
        totalEl.innerHTML = '<span class="foodord-mobile-cart__total-dots" aria-hidden="true"><span></span><span></span><span></span></span>';
      } else {
        totalEl.classList.remove('foodord-mobile-cart__total--loading');
        totalEl.removeAttribute('aria-busy');
        if (typeof totalEl.dataset.originalHtml === 'string') {
          totalEl.innerHTML = totalEl.dataset.originalHtml;
          delete totalEl.dataset.originalHtml;
        }
      }
    });

    const subtotalEls = mobileCart.querySelectorAll('.foodord-mobile-cart__subtotal-amount');
    subtotalEls.forEach((subtotalEl) => {
      if (!subtotalEl) {
        return;
      }

      if (isLoading) {
        subtotalEl.classList.add('foodord-mobile-cart__subtotal-amount--loading');
        subtotalEl.setAttribute('aria-busy', 'true');
        return;
      }

      subtotalEl.classList.remove('foodord-mobile-cart__subtotal-amount--loading');
      subtotalEl.removeAttribute('aria-busy');
    });
  };

  const clearPendingAddToCartState = () => {
    isPendingAddToCart = false;
    if (pendingAddToCartTimer) {
      window.clearTimeout(pendingAddToCartTimer);
      pendingAddToCartTimer = null;
    }
    setTotalsLoadingState(false);
  };

  const showPendingAddToCartState = () => {
    if (!mobileCart || !isMobileScreen()) {
      return;
    }

    isPendingAddToCart = true;
    mobileCart.classList.remove('foodord-mobile-cart--hidden');
    mobileCart.setAttribute('aria-hidden', 'false');
    document.body.classList.add('has-foodord-mobile-cart');
    emitMobileCartStateChange();
    setTotalsLoadingState(true);

    if (pendingAddToCartTimer) {
      window.clearTimeout(pendingAddToCartTimer);
    }
    pendingAddToCartTimer = window.setTimeout(() => {
      pendingAddToCartTimer = null;
      if (isPendingAddToCart) {
        loadCartData();
      }
    }, 8000);
  };

  const setCheckoutButtonLoadingState = (buttonEl, isLoading) => {
    if (!buttonEl || !buttonEl.classList || !buttonEl.classList.contains('foodord-mobile-cart__checkout-btn')) {
      return;
    }

    if (isLoading) {
      buttonEl.classList.add('is-loading');
      buttonEl.setAttribute('aria-busy', 'true');
      buttonEl.disabled = true;
      return;
    }

    buttonEl.classList.remove('is-loading');
    buttonEl.removeAttribute('aria-busy');
  };

  // Create mobile cart HTML structure
  const createMobileCart = () => {
    // Create the bottom button
    const viewCartText = escapeHtml(getI18nString('viewCart'));
    const checkoutText = escapeHtml(getI18nString('checkout'));
    const yourCartText = escapeHtml(getI18nString('yourCart'));
    const emptyText = escapeHtml(getI18nString('emptyCartText'));
    const emptySubtext = escapeHtml(getI18nString('emptyCartSubtext'));
    const closeCartLabel = escapeHtml(getI18nString('closeCart'));
    const itemsInCartLabel = escapeHtml(getI18nString('itemsInCart'));
    const cartHtml = `
      <div class="foodord-mobile-cart" id="foodord-mobile-cart">
        <div class="foodord-mobile-cart__header" role="button" tabindex="0" aria-expanded="false">
          <div class="foodord-mobile-cart__info">
            <div class="foodord-mobile-cart__count" aria-label="${itemsInCartLabel}">0</div>
            <h3 class="foodord-mobile-cart__title">${viewCartText}</h3>
          </div>
          <div class="foodord-mobile-cart__total">€0.00</div>
        </div>
        <div class="foodord-mobile-cart__bottom-footer">
          <button type="button" class="foodord-mobile-cart__bottom-checkout-btn" disabled>
            <div class="foodord-mobile-cart__info">
              <div class="foodord-mobile-cart__count" aria-label="${itemsInCartLabel}">0</div>
              <h3 class="foodord-mobile-cart__title">${checkoutText}</h3>
            </div>
            <div class="foodord-mobile-cart__total">€0.00</div>
          </button>
        </div>
      </div>
    `;

    // Create the full screen modal separately
    const modalHtml = `
      <div class="foodord-mobile-cart__modal" id="foodord-mobile-cart-modal">
        <div class="foodord-mobile-cart__modal-overlay">
          <div class="foodord-mobile-cart__modal-content">
            <span class="foodord-swipe-dismiss__handle" aria-hidden="true"></span>
            <div class="foodord-mobile-cart__modal-header">
              <h2 class="foodord-mobile-cart__modal-title">${yourCartText}</h2>
              <button type="button" class="foodord-mobile-cart__close-btn" aria-label="${closeCartLabel}">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <line x1="18" y1="6" x2="6" y2="18"></line>
                  <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
              </button>
            </div>
            <div class="foodord-mobile-cart__modal-body">
              <div class="foodord-mobile-cart__empty">
                ${emptyCartSvg}
                <div class="foodord-mobile-cart__empty-text">${emptyText}</div>
                <div class="foodord-mobile-cart__empty-subtext">${emptySubtext}</div>
              </div>
            </div>
            <div class="foodord-mobile-cart__footer-upsells"></div>
            <div class="foodord-mobile-cart__footer">
              <div class="foodord-mobile-cart__summary">
                <!-- Subtotal and delivery fee will be inserted here dynamically -->
              </div>
              <div class="foodord-mobile-cart__actions">
                <button type="button" class="foodord-mobile-cart__checkout-btn" disabled>
                  <div class="foodord-mobile-cart__info">
                    <div class="foodord-mobile-cart__count" aria-label="${itemsInCartLabel}">0</div>
                    <h3 class="foodord-mobile-cart__title">${checkoutText}</h3>
                  </div>
                  <div class="foodord-mobile-cart__total">€0.00</div>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    `;

    document.body.insertAdjacentHTML('beforeend', cartHtml);
    document.body.insertAdjacentHTML('beforeend', modalHtml);

    mobileCart = document.getElementById('foodord-mobile-cart');
    mobileCartModal = document.getElementById('foodord-mobile-cart-modal');

    if (mobileCart) {
      mobileCart.classList.add('foodord-mobile-cart--hidden');
      mobileCart.setAttribute('aria-hidden', 'true');
      emitMobileCartStateChange();
    }
  };

  // Bind event listeners
  const bindEvents = () => {
    if (!mobileCart || !mobileCartModal) return;

    const header = mobileCart.querySelector('.foodord-mobile-cart__header');
    const closeBtn = mobileCartModal.querySelector('.foodord-mobile-cart__close-btn');
    const checkoutBtn = mobileCartModal.querySelector('.foodord-mobile-cart__checkout-btn');
    const bottomCheckoutBtn = mobileCart.querySelector('.foodord-mobile-cart__bottom-checkout-btn');
    const modalOverlay = mobileCartModal.querySelector('.foodord-mobile-cart__modal-overlay');

    // Toggle cart expansion
    header.addEventListener('click', toggleCart);
    header.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' || e.key === ' ') {
        e.preventDefault();
        toggleCart();
      }
    });

    // Close button
    if (closeBtn) {
      closeBtn.addEventListener('click', collapseCart);
    }

    // Checkout
    if (checkoutBtn) {
      checkoutBtn.addEventListener('click', (event) => goToCheckout(event));
    }

    // Bottom checkout button
    if (bottomCheckoutBtn) {
      bottomCheckoutBtn.addEventListener('click', (event) => goToCheckout(event));
    }

    // Close cart when clicking on overlay
    if (modalOverlay) {
      modalOverlay.addEventListener('click', (e) => {
        if (e.target === modalOverlay) {
          collapseCart();
        }
      });
    }

    // Handle escape key
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape' && isExpanded) {
        collapseCart();
      }
    });

    // Listen for cart updates from main FoodordCard
    document.addEventListener('foodord_cart_updated', handleCartUpdate);

    // Make mobile cart visible immediately on add-to-cart start (slow network feedback).
    document.addEventListener('click', (event) => {
      const trigger = event.target.closest(
        '.foodord-add-to-cart-btn, .foodord-modal-upsells__button[data-foodord-upsell-direct-add="1"], .add_to_cart_button.ajax_add_to_cart, .single_add_to_cart_button'
      );
      if (!trigger) {
        return;
      }
      if (trigger.disabled || trigger.getAttribute('aria-disabled') === 'true') {
        return;
      }
      showPendingAddToCartState();
    }, true);

    initMobileCartItemEditing();
    initMobileCartUpsells();
  };

  const initMobileCartItemEditing = () => {
    if (mobileCartItemEditInitialized) {
      return;
    }
    if (!mobileCartModal) {
      return;
    }

    mobileCartItemEditInitialized = true;

    const isEditableTarget = (event) => {
      if (!event) {
        return false;
      }
      if (event.target.closest('.foodord-mobile-cart__item-quantity')) {
        return false;
      }
      if (event.target.closest('.foodord-mobile-cart__item-remove')) {
        return false;
      }
      if (event.target.closest('.wr-card__note-btn')) {
        return false;
      }
      if (event.target.closest('[data-foodord-note-wrapper]')) {
        return false;
      }
      if (event.target.closest('button, a')) {
        return false;
      }
      return true;
    };

    const openEditorForMobileItem = (itemEl) => {
      if (!itemEl || typeof window === 'undefined' || !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') || '';

      collapseCart();

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

    mobileCartModal.addEventListener('click', (event) => {
      const item = event.target.closest('.foodord-mobile-cart__item');
      if (!item || !isEditableTarget(event)) {
        return;
      }

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

      event.preventDefault();
      event.stopPropagation();
      openEditorForMobileItem(item);
    }, true);

    mobileCartModal.addEventListener('keydown', (event) => {
      if (!event || (event.key !== 'Enter' && event.key !== ' ')) {
        return;
      }
      const item = event.target.closest('.foodord-mobile-cart__item');
      if (!item || !isEditableTarget(event)) {
        return;
      }

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

  const updateMobileUpsellNavState = (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 initMobileUpsellSections = (scope = document) => {
    const sections = scope.querySelectorAll('.foodord-mobile-cart__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', () => updateMobileUpsellNavState(section), { passive: true });
        rail.dataset.foodordUpsellScrollBound = 'true';
      }

      updateMobileUpsellNavState(section);
    });
  };

  const initMobileCartUpsells = () => {
    if (mobileCartUpsellListenersInitialized || !mobileCartModal) {
      return;
    }

    mobileCartUpsellListenersInitialized = true;

    mobileCartModal.addEventListener('click', (event) => {
      const trigger = event.target.closest('[data-foodord-card-upsell-trigger="true"]');
      if (!trigger || !trigger.closest('.foodord-mobile-cart__upsells')) {
        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;
      }

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

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

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

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

      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(() => updateMobileUpsellNavState(section), 220);
    });

    window.addEventListener('resize', () => initMobileUpsellSections(mobileCartModal));
  };

  const closeMobileCartNoteEditors = () => {
    if (!mobileCartModal) {
      return;
    }

    if (window.FoodordCartNotes && typeof window.FoodordCartNotes.closeOpenForms === 'function') {
      window.FoodordCartNotes.closeOpenForms(mobileCartModal);
      return;
    }

    const openNotes = mobileCartModal.querySelectorAll('[data-foodord-note-wrapper].is-editing');
    openNotes.forEach((container) => {
      const itemEl = container.closest('[data-cart-item-key]');
      const note = itemEl ? (itemEl.getAttribute('data-note') || '') : '';
      const form = container.querySelector('[data-foodord-note-form]');
      const display = container.querySelector('[data-foodord-note-display]');

      container.classList.remove('is-editing');
      if (form) {
        form.hidden = true;
      }
      if (display) {
        display.hidden = !note;
      }
    });
  };

  const buildUpsellItemsSignature = (cartItems) => {
    if (!Array.isArray(cartItems) || cartItems.length === 0) {
      return '';
    }

    const stableKeys = cartItems.map((item) => {
      const cartItemKey = item && item.cart_item_key ? String(item.cart_item_key) : '';
      if (cartItemKey) {
        return cartItemKey;
      }
      const productId = item && item.product_id ? String(item.product_id) : '0';
      const variationId = item && item.variation_id ? String(item.variation_id) : '0';
      const toppingsSignature = item && item.toppings_signature ? String(item.toppings_signature) : '';
      return `${productId}:${variationId}:${toppingsSignature}`;
    });

    stableKeys.sort();
    return stableKeys.join('|');
  };

  const renderMobileUpsells = (metadata = null, forceRefresh = false) => {
    if (!mobileCartModal) {
      return;
    }

    const upsellSlot = mobileCartModal.querySelector('.foodord-mobile-cart__footer-upsells');
    if (!upsellSlot) {
      return;
    }

    if (!areUpsellsEnabled()) {
      upsellSlot.innerHTML = '';
      return;
    }

    const hasUpsellPayload = !!(metadata && Object.prototype.hasOwnProperty.call(metadata, 'card_upsells_html'));
    const upsellsHtml = hasUpsellPayload && typeof metadata.card_upsells_html === 'string'
      ? metadata.card_upsells_html
      : '';
    const hasRenderedUpsells = !!upsellSlot.querySelector('.foodord-mobile-cart__upsells .foodord-modal-upsells');

    // Quantity +/- events emit partial cart payloads without upsell HTML.
    // Preserve the currently rendered rail until a full payload arrives.
    if (!hasUpsellPayload) {
      return;
    }

    if (!upsellsHtml) {
      upsellSlot.innerHTML = '';
      return;
    }

    if (!forceRefresh && hasRenderedUpsells) {
      return;
    }

    upsellSlot.innerHTML = `<div class="foodord-mobile-cart__upsells">${upsellsHtml}</div>`;
    initMobileUpsellSections(upsellSlot);
    if (window.FoodordUpsellSkeleton && typeof window.FoodordUpsellSkeleton.hydrateScope === 'function') {
      window.FoodordUpsellSkeleton.hydrateScope(upsellSlot);
    }
  };

  // Toggle cart expansion
  const toggleCart = () => {
    if (isExpanded) {
      collapseCart();
    } else {
      expandCart();
    }
  };

  // Set dynamic viewport height for mobile devices
  const setViewportHeight = () => {
    const vh = window.innerHeight * 0.01;
    document.documentElement.style.setProperty('--foodord-vh', `${vh}px`);
  };

  // Expand cart (full screen modal)
  const expandCart = () => {
    if (!mobileCart || !mobileCartModal) return;

    // Set dynamic viewport height
    setViewportHeight();

    if (mobileCartCloseTimer) {
      window.clearTimeout(mobileCartCloseTimer);
      mobileCartCloseTimer = null;
    }

    isExpanded = true;
    mobileCartModal.classList.remove('is-closing');
    mobileCartModal.classList.add('active');
    mobileCartModal.setAttribute('aria-hidden', 'false');
    document.body.classList.add('mobile-cart-expanded');

    const header = mobileCart.querySelector('.foodord-mobile-cart__header');
    if (header) {
      header.setAttribute('aria-expanded', 'true');
    }

    // Update button text to "Checkout"
    updateHeaderText();

    // Load fresh cart data when expanding
    loadCartData();
    emitMobileCartStateChange();

    // Update viewport height on resize and orientation change
    window.addEventListener('resize', setViewportHeight);
    window.addEventListener('orientationchange', setViewportHeight);
  };

  // Collapse cart
  const collapseCart = () => {
    if (!mobileCart || !mobileCartModal) return;

    const shouldAnimate = mobileCartModal.classList.contains('active') || mobileCartModal.classList.contains('is-closing');

    if (mobileCartCloseTimer) {
      window.clearTimeout(mobileCartCloseTimer);
      mobileCartCloseTimer = null;
    }

    isExpanded = false;
    closeMobileCartNoteEditors();
    mobileCartModal.classList.remove('active');

    if (shouldAnimate) {
      mobileCartModal.classList.add('is-closing');
      mobileCartCloseTimer = window.setTimeout(() => {
        mobileCartModal.classList.remove('is-closing');
        mobileCartModal.setAttribute('aria-hidden', 'true');
        document.body.classList.remove('mobile-cart-expanded');
        mobileCartCloseTimer = null;
      }, mobileCartAnimationMs);
    } else {
      mobileCartModal.classList.remove('is-closing');
      mobileCartModal.setAttribute('aria-hidden', 'true');
      document.body.classList.remove('mobile-cart-expanded');
    }

    const header = mobileCart.querySelector('.foodord-mobile-cart__header');
    if (header) {
      header.setAttribute('aria-expanded', 'false');
    }

    // Update button text to "View Cart"
    updateHeaderText();
    emitMobileCartStateChange();

    // Remove viewport height event listeners
    window.removeEventListener('resize', setViewportHeight);
    window.removeEventListener('orientationchange', setViewportHeight);
  };

  // Update header text based on cart state
  const updateHeaderText = () => {
    if (!mobileCart) return;

    const titleEl = mobileCart.querySelector('.foodord-mobile-cart__title');
    if (titleEl) {
      titleEl.textContent = isExpanded ? getI18nString('checkout') : getI18nString('viewCart');
    }
  };

  const getMobileUpsellSkeletonHtml = (count = 2) => {
    if (!areUpsellsEnabled()) {
      return '';
    }

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

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

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

    if (!mobileCartModal || !isExpanded) {
      return;
    }

    const upsellSlot = mobileCartModal.querySelector('.foodord-mobile-cart__footer-upsells');
    const skeletonHtml = getMobileUpsellSkeletonHtml(2);
    const hasLoadingState = !!(upsellSlot && upsellSlot.querySelector('.foodord-mobile-cart__upsells--loading'));
    const hasRenderedUpsells = !!(upsellSlot && upsellSlot.querySelector('.foodord-mobile-cart__upsells .foodord-modal-upsells'));

    if (!upsellSlot || !skeletonHtml || (!force && currentCartCount <= 0)) {
      return;
    }

    // Avoid re-triggering skeleton on quantity +/- updates when upsells are already rendered.
    if (!force && (hasLoadingState || hasRenderedUpsells)) {
      return;
    }

    upsellSlot.innerHTML = `<div class="foodord-mobile-cart__upsells foodord-mobile-cart__upsells--loading">${skeletonHtml}</div>`;
    initMobileCartUpsells(upsellSlot);
  };

  // Load cart data from existing FoodOrd card system
  const loadCartData = () => {
    if (!mobileCart) return;

    // Try to get data from existing FoodOrd card system
    if (typeof window.FoodordCard !== 'undefined' && window.FoodordCard.getCartData) {
      const cartData = window.FoodordCard.getCartData();
      if (cartData) {
        updateCartDisplay(cartData);
        return;
      }
    }

    // Try to load cart data via AJAX if available
    if (typeof jQuery !== 'undefined' && typeof foodord_modal_vars !== 'undefined') {
      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) {
          updateCartDisplay(response.data);
        } else {
          // Fallback to DOM reading if AJAX fails
          loadCartDataFromDOM();
        }
      }).fail(function () {
        // Fallback to DOM reading if AJAX fails
        loadCartDataFromDOM();
      });
    } else {
      // Fallback to DOM reading if AJAX not available
      loadCartDataFromDOM();
    }
  };

  // Fallback function to read cart data from DOM elements
  const loadCartDataFromDOM = () => {
    const existingCartCount = document.querySelector('.wr-card__cta-count');
    const existingCartTotal = document.querySelector('.wr-card__cta-total');

    if (existingCartCount && existingCartTotal) {
      const cartCount = parseInt(existingCartCount.textContent) || 0;
      const cartTotal = existingCartTotal.innerHTML || '€0.00';

      updateCartDisplay({
        cart_count: cartCount,
        cart_total_html: cartTotal,
        cart_items: [] // Items will be loaded when expanded
      });
      return;
    }

    if (isPendingAddToCart) {
      clearPendingAddToCartState();
    }
  };

  const updateCartItemPrice = (data) => {
    if (!mobileCartModal || !data || !data.updated_cart_item_key || !data.updated_item_line_total) {
      return;
    }

    const targetKey = String(data.updated_cart_item_key);
    const cartItems = mobileCartModal.querySelectorAll('.foodord-mobile-cart__item');
    cartItems.forEach((itemEl) => {
      if (!itemEl || itemEl.getAttribute('data-cart-item-key') !== targetKey) {
        return;
      }

      const priceEl = itemEl.querySelector('.foodord-mobile-cart__item-price');
      if (priceEl) {
        priceEl.innerHTML = data.updated_item_line_total;
      }

      if (typeof data.updated_item_quantity !== 'undefined') {
        itemEl.setAttribute('data-quantity', String(data.updated_item_quantity));
      }
    });
  };

  // Update cart display with data
  const updateCartDisplay = (data) => {
    if (!mobileCart) return;
    clearPendingAddToCartState();

    const countEl = mobileCart.querySelector('.foodord-mobile-cart__count');
    const totalEl = mobileCart.querySelector('.foodord-mobile-cart__total');
    const checkoutBtn = mobileCartModal.querySelector('.foodord-mobile-cart__checkout-btn');
    const bottomCheckoutBtn = mobileCart.querySelector('.foodord-mobile-cart__bottom-checkout-btn');
    const summaryEl = mobileCartModal.querySelector('.foodord-mobile-cart__summary');

    // Update count and total
    const cartCount = data.cart_count || 0;
    const cartTotal = data.cart_total_html || '€0.00';

    // Minimum order gating
    const minimumActive = !isTableOrderingContext() && !!data.minimum_active;
    const minimumPassed = !!data.minimum_passed;
    const minimumRequired = typeof data.minimum_required !== 'undefined' ? Number(data.minimum_required) : 0;
    const remainingToMinimum = typeof data.remaining_to_minimum !== 'undefined' ? Number(data.remaining_to_minimum) : 0;
    const remainingHtml = data.remaining_to_minimum_html || '';
    const minimumHtml = data.minimum_required_html || '';
    const minimumFloorHtml = data.minimum_floor_html || '0';
    const minimumProgress = minimumRequired > 0 && Number.isFinite(remainingToMinimum)
      ? Math.max(0, Math.min(100, ((minimumRequired - remainingToMinimum) / minimumRequired) * 100))
      : 0;
    const minimumProgressStep = Math.round(minimumProgress / 5) * 5;
    const shouldDisableForMinimum = cartCount > 0 && minimumActive && !minimumPassed;
    const gateShowFee = !isTableOrderingContext() && ((!minimumActive) || minimumPassed || minimumRequired === 0);

    currentCartCount = cartCount;

    countEl.textContent = cartCount;
    totalEl.innerHTML = cartTotal;

    // Update checkout button counts and totals
    if (checkoutBtn) {
      const checkoutCountEl = checkoutBtn.querySelector('.foodord-mobile-cart__count');
      const checkoutTotalEl = checkoutBtn.querySelector('.foodord-mobile-cart__total');
      if (checkoutCountEl) checkoutCountEl.textContent = cartCount;
      if (checkoutTotalEl) checkoutTotalEl.innerHTML = cartTotal;
      checkoutBtn.disabled = !cartCount || shouldDisableForMinimum;
    }

    if (bottomCheckoutBtn) {
      const bottomCountEl = bottomCheckoutBtn.querySelector('.foodord-mobile-cart__count');
      const bottomTotalEl = bottomCheckoutBtn.querySelector('.foodord-mobile-cart__total');
      if (bottomCountEl) bottomCountEl.textContent = cartCount;
      if (bottomTotalEl) bottomTotalEl.innerHTML = cartTotal;
      bottomCheckoutBtn.disabled = !cartCount || shouldDisableForMinimum;
    }

    // Update summary (subtotal, delivery fee, discounts)
    if (summaryEl) {
      let summaryHtml = '';

      // Add subtotal if available
      if (data.subtotal_html) {
        const subtotalLabel = escapeHtml(getI18nString('subtotal'));
        summaryHtml += `
          <div class="foodord-mobile-cart__subtotal">
            <div class="foodord-mobile-cart__subtotal-info">
              <span class="foodord-mobile-cart__subtotal-label">${subtotalLabel}</span>
            </div>
            <span class="foodord-mobile-cart__subtotal-amount">${data.subtotal_html}</span>
          </div>
        `;
      }

      // Add delivery fee if available and > 0, gated by minimum rule (or minimum 0)
      if (gateShowFee && data.delivery_fee > 0 && data.delivery_fee_html) {
        const deliveryLabel = escapeHtml(getI18nString('deliveryFee'));
        summaryHtml += `
          <div class="foodord-mobile-cart__delivery-fee">
            <div class="foodord-mobile-cart__delivery-info">
              <span class="foodord-mobile-cart__delivery-label">${deliveryLabel}</span>
            </div>
            <span class="foodord-mobile-cart__delivery-amount">${data.delivery_fee_html}</span>
          </div>
        `;
      }

      // List applied discounts/fees if available
      if (!isTableOrderingContext() && Array.isArray(data.fees) && data.fees.length > 0) {
        const feeRows = data.fees
          .filter((fee) => fee && fee.amount_html)
          .map((fee) => {
            const label = fee.label ? escapeHtml(fee.label) : '';
            const amountHtml = fee.amount_html;
            return `
              <div class="foodord-mobile-cart__fee">
                <span class="foodord-mobile-cart__fee-label">${label}</span>
                <span class="foodord-mobile-cart__fee-amount">${amountHtml}</span>
              </div>
            `;
          })
          .join('');
        if (feeRows) {
          summaryHtml += `
            <div class="foodord-mobile-cart__fees">
              ${feeRows}
            </div>
          `;
        }
      }

      // Minimum notice when not passed
      if (cartCount > 0 && minimumActive && !minimumPassed && remainingHtml) {
        const minimumNoticeText = (() => {
          const template = getI18nString('minOrderNotice');
          if (template) {
            return template
              .replace('%1$s', `<strong class="foodord-mobile-cart__min-notice-amount">${remainingHtml}</strong>`)
              .replace(/\s*%2\$s/g, '');
          }
          return `Add <strong class="foodord-mobile-cart__min-notice-amount">${remainingHtml}</strong> more to reach the minimum order.`;
        })();
        summaryHtml += `
          <div class="foodord-mobile-cart__notice foodord-mobile-cart__notice--warning foodord-mobile-cart__min-notice" role="status">
            <span class="foodord-mobile-cart__notice-text">${minimumNoticeText}</span>
            <span class="foodord-mobile-cart__min-progress" aria-hidden="true">
              <span class="foodord-mobile-cart__min-progress-edge foodord-mobile-cart__min-progress-edge--start">${minimumFloorHtml}</span>
              <span class="foodord-mobile-cart__min-progress-track">
                <span class="foodord-mobile-cart__min-progress-fill"></span>
              </span>
              <span class="foodord-mobile-cart__min-progress-edge foodord-mobile-cart__min-progress-edge--end">${minimumHtml}</span>
            </span>
          </div>
        `;
      }

      summaryEl.innerHTML = summaryHtml;
      const minimumNoticeEl = summaryEl.querySelector('.foodord-mobile-cart__min-notice');
      if (minimumNoticeEl) {
        minimumNoticeEl.setAttribute('data-foodord-min-progress', String(minimumProgressStep));
      }
    }

    const hasCartItemsPayload = Array.isArray(data.cart_items);
    const cartItemsForSignature = hasCartItemsPayload ? data.cart_items : null;
    const nextUpsellItemsSignature = hasCartItemsPayload
      ? buildUpsellItemsSignature(cartItemsForSignature)
      : lastUpsellItemsSignature;
    const shouldRefreshUpsells = hasCartItemsPayload && nextUpsellItemsSignature !== lastUpsellItemsSignature;

    renderMobileUpsells(data, shouldRefreshUpsells);
    if (hasCartItemsPayload) {
      lastUpsellItemsSignature = nextUpsellItemsSignature;
    }

    // Update cart items
    if (cartCount === 0) {
      showEmptyState();
    } else if (Array.isArray(data.cart_items) && data.cart_items.length > 0) {
      // Quantity popovers are now persistent/always visible, so active-popover guard
      // would block all subsequent renders (2nd+ add-to-cart) and leave stale items.
      renderCartItems(data.cart_items, data);
    } else {
      updateCartItemPrice(data);
    }

    setCartVisibility(cartCount);
  };

  const setCartVisibility = (cartCount) => {
    if (!mobileCart || !mobileCartModal) {
      return;
    }

    const hasItems = cartCount > 0;

    if (!hasItems) {
      collapseCart();
      mobileCart.classList.add('foodord-mobile-cart--hidden');
      mobileCart.setAttribute('aria-hidden', 'true');
      mobileCartModal.classList.remove('active');
      document.body.classList.remove('has-foodord-mobile-cart', 'mobile-cart-expanded');
      emitMobileCartStateChange();
      return;
    }

    mobileCart.classList.remove('foodord-mobile-cart--hidden');
    mobileCart.setAttribute('aria-hidden', 'false');
    document.body.classList.add('has-foodord-mobile-cart');
    emitMobileCartStateChange();
  };

  // Render cart items
  const renderCartItems = (cartItems) => {
    const modalBodyEl = mobileCartModal.querySelector('.foodord-mobile-cart__modal-body');

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

    let itemsHtml = '<div class="foodord-mobile-cart__items">';
    cartItems.forEach((item) => {
      const toppingsHtml = renderToppings(item.toppings || []);
      const unitPrice = item.unit_price_numeric || 0;
      const noteMarkup = (window.FoodordCartNotes && typeof window.FoodordCartNotes.renderNoteMarkup === 'function')
        ? window.FoodordCartNotes.renderNoteMarkup(item, 'mobile', { includeToggle: false })
        : '';
      const noteToggleMarkup = (window.FoodordCartNotes && typeof window.FoodordCartNotes.renderNoteToggleMarkup === 'function')
        ? window.FoodordCartNotes.renderNoteToggleMarkup(item, 'mobile')
        : '';
      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 editLabel = escapeHtml(buildEditLabel(rawName));
      const displayName = escapeHtml(rawName);
      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 ? 'minus trash' : 'minus';
      itemsHtml += `
        <div class="foodord-mobile-cart__item" role="button" tabindex="0" aria-label="${editLabel}" data-product-id="${item.product_id}" data-variation-id="${item.variation_id}" data-unit-price="${unitPrice}" data-cart-item-key="${cartItemKeyAttr}" data-note="${noteAttr}" data-toppings-signature="${signatureAttr}" data-quantity="${item.quantity}">
          <div class="foodord-mobile-cart__item-details">
            <h4 class="foodord-mobile-cart__item-title">${displayName}</h4>
            ${toppingsHtml}
            ${noteToggleMarkup}
          </div>
          <div class="foodord-mobile-cart__item-actions">
            <div class="foodord-mobile-cart__item-price">${item.price}</div>
            <div class="foodord-mobile-cart__item-quantity active" data-quantity="${quantityValue}">
              <div class="mobile-popover active">
                <button class="${minusClass}" data-action="minus">${minusIcon}</button>
                <span>${quantityValue}</span>
                <button class="plus" data-action="plus"></button>
              </div>
            </div>
          </div>
          ${noteMarkup}
        </div>
      `;
    });
    itemsHtml += '</div>';

    modalBodyEl.innerHTML = itemsHtml;
  };

  // Render toppings HTML
  const renderToppings = (toppings) => {
    if (!toppings || toppings.length === 0) {
      return '';
    }

    const allToppingItems = [];
    toppings.forEach((set) => {
      if (set.items && set.items.length > 0) {
        set.items.forEach((item) => {
          allToppingItems.push(escapeHtml(item));
        });
      }
    });

    if (allToppingItems.length === 0) {
      return '';
    }

    return `<div class="foodord-mobile-cart__item-toppings">${allToppingItems.join('<br>')}</div>`;
  };

  // Show empty cart state
  const showEmptyState = () => {
    const modalBodyEl = mobileCartModal.querySelector('.foodord-mobile-cart__modal-body');
    const upsellSlot = mobileCartModal.querySelector('.foodord-mobile-cart__footer-upsells');
    const emptyText = escapeHtml(getI18nString('emptyCartText') || 'Your cart is empty');
    const emptySubtext = escapeHtml(getI18nString('emptyCartSubtext') || 'Add items to get started');
    modalBodyEl.innerHTML = `
      <div class="foodord-mobile-cart__empty">
        ${emptyCartSvg}
        <div class="foodord-mobile-cart__empty-text">${emptyText}</div>
        <div class="foodord-mobile-cart__empty-subtext">${emptySubtext}</div>
      </div>
    `;
    if (upsellSlot) {
      upsellSlot.innerHTML = '';
    }
  };


  // Go to checkout
  const goToCheckout = (event) => {
    const trigger = event && event.currentTarget ? event.currentTarget : null;
    setCheckoutButtonLoadingState(trigger, true);

    if (checkoutLoadingResetTimer) {
      window.clearTimeout(checkoutLoadingResetTimer);
    }
    checkoutLoadingResetTimer = window.setTimeout(() => {
      checkoutLoadingResetTimer = null;
      setCheckoutButtonLoadingState(trigger, false);
    }, 6000);

    const checkoutUrl = getCheckoutUrl();
    if (checkoutUrl) {
      window.location.href = checkoutUrl;
      return;
    }

    setCheckoutButtonLoadingState(trigger, false);
  };

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

    // Fallback: look for checkout links
    const checkoutLinks = document.querySelectorAll('a[href*="checkout"], a[href*="odeme"], a[href*="kasa"]');
    if (checkoutLinks.length > 0) {
      return checkoutLinks[0].href;
    }

    // Final fallback
    return window.location.origin + '/checkout/';
  };

  // Handle cart updates from main FoodordCard
  const handleCartUpdate = (event) => {
    if (event.detail && typeof event.detail.cart_count !== 'undefined') {
      // Use the data from the event directly instead of re-loading
      updateCartDisplay(event.detail);
    }
  };

  // Simple HTML escaping
  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();
  };

  // Handle window resize
  const handleResize = () => {
    if (!mobileCart) {
      return;
    }

    if (!isMobileScreen()) {
      collapseCart();
      document.body.classList.remove('has-foodord-mobile-cart', 'mobile-cart-expanded');
      mobileCart.classList.add('foodord-mobile-cart--hidden');
      mobileCart.setAttribute('aria-hidden', 'true');
      if (mobileCartModal) {
        if (mobileCartCloseTimer) {
          window.clearTimeout(mobileCartCloseTimer);
          mobileCartCloseTimer = null;
        }
        mobileCartModal.classList.remove('active', 'is-closing');
        mobileCartModal.setAttribute('aria-hidden', 'true');
      }
      emitMobileCartStateChange();
      return;
    }

    if (hasFoodordProducts()) {
      setCartVisibility(currentCartCount);
    }
  };

  // Cleanup function
  const cleanup = () => {
    if (mobileCart) {
      mobileCart.remove();
      mobileCart = null;
    }
    document.body.classList.remove('has-foodord-mobile-cart', 'mobile-cart-expanded');
    currentCartCount = 0;
    clearPendingAddToCartState();
    if (mobileCartCloseTimer) {
      window.clearTimeout(mobileCartCloseTimer);
      mobileCartCloseTimer = null;
    }
    if (checkoutLoadingResetTimer) {
      window.clearTimeout(checkoutLoadingResetTimer);
      checkoutLoadingResetTimer = null;
    }
    isInitialized = false;
    isExpanded = false;
    emitMobileCartStateChange();
  };

  // Initialize when DOM is ready
  const init = () => {
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', initMobileCart);
    } else {
      initMobileCart();
    }

    // Handle window resize
    window.addEventListener('resize', handleResize);

    // Listen for FoodOrd cart updates via direct payload handler (already registered elsewhere)
    // Removed extra loadData listener to prevent unnecessary re-renders causing popover to close

    // Watch for changes in existing cart elements
    const observeCartChanges = () => {
      const existingCartCount = document.querySelector('.wr-card__cta-count');
      const existingCartTotal = document.querySelector('.wr-card__cta-total');

      if (existingCartCount || existingCartTotal) {
        const observer = new MutationObserver(() => {
          setTimeout(loadCartData, 100);
        });

        if (existingCartCount) {
          observer.observe(existingCartCount, { childList: true, characterData: true, subtree: true });
        }
        if (existingCartTotal) {
          observer.observe(existingCartTotal, { childList: true, characterData: true, subtree: true });
        }
      }
    };

    // Start observing after a short delay to ensure elements are loaded
    setTimeout(observeCartChanges, 500);

    // Also listen for standard WooCommerce events as backup
    document.addEventListener('added_to_cart', () => setTimeout(loadCartData, 300));
    document.addEventListener('removed_from_cart', () => setTimeout(loadCartData, 300));

    // React to location selection changes
    document.addEventListener('foodord:locationSelected', () => setTimeout(loadCartData, 120));
  };

  // Public API
  window.FoodordMobileCart = {
    init: initMobileCart,
    expand: expandCart,
    collapse: collapseCart,
    toggle: toggleCart,
    loadData: loadCartData,
    showUpsellSkeleton: showUpsellSkeleton,
    cleanup: cleanup,
    isExpanded: () => isExpanded,
    isMobile: isMobileScreen
  };

  // Auto-initialize
  init();

})(window, document);
