/* Get RestroPress Cookie */
function rp_getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1);
    if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
  }
  return "";
}
function remove_show_service_options() {
  jQuery('#rpressModal')
    .removeClass('show-service-options');
}
/* Set default addons */
function rp_checked_default_subaddon() {
  if (jQuery('#fooditem-details .rp-addons-data-wrapper .food-item-list.active').length > 0) {
    jQuery('#fooditem-details .rp-addons-data-wrapper .food-item-list.active').each(function () {
      var element = jQuery(this).find('input');
      if (element.hasClass('checked')) {
        jQuery(this).find('input').prop('checked', true);
      }
    });
  }
}
/* Set RestroPress Cookie */
function rp_setCookie(cname, cvalue, ex_time) {
  var d = new Date();
  d.setTime(d.getTime() + (ex_time * 60 * 1000));
  var expires = "expires=" + d.toUTCString();
  document.cookie = cname + "=" + cvalue + "; " + expires + ";path=/";
}
function rp_clearCookie(cname) {
  document.cookie = cname + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/";
}
function rp_is_old_ui_ux_enabled() {
  return (typeof rp_scripts !== 'undefined') && String(rp_scripts.old_ui_ux || '') === '1';
}
function rp_clear_old_ui_service_cookies() {
  var cookieKeys = [
    'service_type',
    'service_time',
    'service_time_text',
    'service_date',
    'delivery_date',
    'delivery_zip',
    'delivery_location',
    'delivery_address',
    'branch',
    'branch_name'
  ];
  for (var i = 0; i < cookieKeys.length; i++) {
    rp_clearCookie(cookieKeys[i]);
  }
}
/* Get RestroPress Storage Data */
function rp_get_storage_data() {
  var serviceType = (rp_getCookie('service_type') || '')
    .toString()
    .trim()
    .toLowerCase();
  if (!serviceType || (serviceType !== 'delivery' && serviceType !== 'pickup')) {
    return false;
  }

  if (!rp_is_old_ui_ux_enabled()) {
    return true;
  }

  var $ = (typeof jQuery !== 'undefined') ? jQuery : null;
  var serviceTime = (rp_getCookie('service_time') || '')
    .toString()
    .trim();
  var serviceDate = (rp_getCookie('service_date') || rp_getCookie('delivery_date') || '')
    .toString()
    .trim();
  var deliveryZip = (rp_getCookie('delivery_zip') || '')
    .toString()
    .trim();
  var deliveryLocation = (rp_getCookie('delivery_location') || '')
    .toString()
    .trim();
  var deliveryAddress = (rp_getCookie('delivery_address') || '')
    .toString()
    .trim();
  var branchId = (rp_getCookie('branch') || '')
    .toString()
    .trim();
  var branchName = (rp_getCookie('branch_name') || '')
    .toString()
    .trim();

  var hasDateSelect = false;
  var hasTimeSelect = false;
  var hasBranchSelector = false;
  var hasLocationField = false;
  var hasZipField = false;
  var hasAddressField = false;

  if ($) {
    var $servicePanel = $('.delivery-settings-wrapper#nav-' + serviceType);
    if (!$servicePanel.length) {
      $servicePanel = $('.delivery-settings-wrapper.active, .delivery-settings-wrapper.show').first();
    }
    if (!$servicePanel.length) {
      $servicePanel = $(document);
    }

    hasDateSelect = $servicePanel.find('.rpress_get_delivery_dates').length > 0;
    hasTimeSelect = $servicePanel.find('.rpress_get_delivery_hours, .rpress-pickup-hours, #rpress-' + serviceType + '-hours, .rpress-allowed-delivery-hrs').length > 0;
    hasBranchSelector = $('select[name="branch"], #rp-location, #rpress_location').length > 0;
    hasLocationField = $('input#rp_delivery_location, input[name="rp_delivery_location"]').length > 0;
    hasZipField = $('input#rp_delivery_zone, input[name="rp_delivery_zone"]').length > 0;
    hasAddressField = $('input#rp_delivery_address, input[name="rp_delivery_address"], input#rp_street_address').length > 0;
  }

  var isServiceTimeDisabled = false;
  if (window.rp_otil_vars) {
    isServiceTimeDisabled =
      (serviceType === 'pickup' && window.rp_otil_vars.disable_pickup_time === '1') ||
      (serviceType === 'delivery' && window.rp_otil_vars.disable_delivery_time === '1');
  }

  if (hasDateSelect && !serviceDate) {
    return false;
  }

  if (hasTimeSelect && !isServiceTimeDisabled && !serviceTime) {
    return false;
  }

  if (hasBranchSelector && !branchId && !branchName) {
    return false;
  }

  if (serviceType === 'delivery') {
    if (hasLocationField && !deliveryLocation) {
      return false;
    }

    if (hasZipField && !deliveryZip) {
      return false;
    }

    if (hasAddressField && !deliveryAddress && !branchName) {
      return false;
    }
  }

  return true;
}
/* Display Dynamic Addon Price Based on Selected Variation */
function show_dymanic_pricing(container, ele) {
  var price_key = ele.val();
  if (price_key !== 'undefined') {
    var $wrapper = jQuery('#' + container + ' .rp-addons-data-wrapper');
    jQuery('#' + container + ' .rp-addons-data-wrapper .food-item-list')
      .removeClass('active');
    jQuery('#' + container + ' .rp-addons-data-wrapper .food-item-list.list_' + price_key)
      .addClass('active');
    // remove border from the last active only
    $wrapper.find('.food-item-list.active').last().css('border-bottom', '0');
  }
}
/* Calculate Live Price On Click */
function update_modal_live_price(fooditem_container) {
  //Add changes code
  var single_price = parseFloat(jQuery('#rpressModal .cart-item-price')
    .attr('data-price'));
  var quantity = parseInt(jQuery('input[name=quantity]')
    .val());
  /* Act on the variations */
  jQuery('#' + fooditem_container + ' .rp-variable-price-wrapper .food-item-list')
    .each(function () {
      var element = jQuery(this)
        .find('input');
      if (element.is(':checked')) {
        // Dynamic addon Price
        show_dymanic_pricing(fooditem_container, element);
        var attrs = element.attr('data-value');
        var attrs_arr = attrs.split('|');
        var price = attrs_arr[2];
        single_price = parseFloat(price);
      }
    });
  /* Act on the addons */
  jQuery('#' + fooditem_container + ' .rp-addons-data-wrapper .food-item-list.active')
    .each(function () {
      var element = jQuery(this)
        .find('input');
      if (element.is(':checked')) {
        var attrs = element.val();
        var attrs_arr = attrs.split('|');
        var price = attrs_arr[2];
        if (price != '') {
          single_price = parseFloat(single_price) + parseFloat(price);
        }
      }
    });
  /* Updating as per current quantity */
  total_price = single_price * quantity;
  /* Update the price in Submit Button */
  if (rp_scripts.decimal_separator == ',') {
    total_price_v = total_price.toFixed(2)
      .split('.')
      .join(',');
  } else {
    total_price_v = total_price.toFixed(2);
  }
  if (rp_scripts.currency_pos === 'before') {
    jQuery('#rpressModal .cart-item-price')
      .html(rp_scripts.currency_sign + total_price_v);
  }
  else {
    jQuery('#rpressModal .cart-item-price')
      .html(total_price_v + rp_scripts.currency_sign);
  }

  jQuery('#rpressModal .cart-item-price')
    .attr('data-current', single_price.toFixed(2));
}
function isStoreOpen() {
  if (typeof rp_scripts === 'undefined') return true; // fail-safe

  if (rp_scripts.always_open === '1') return true;

  if (rp_scripts.open_hours === '' || rp_scripts.close_hours === '') return false; // no hours set, assume close

  var open = rp_scripts.open_hours;
  var close = rp_scripts.close_hours;

  function parseTime(t) {
    if (typeof t !== 'string') return null;

    var d = new Date();
    var time = t.toLowerCase().replace(/\s/g, '');
    var match12 = time.match(/^(\d{1,2}):(\d{2})(am|pm)$/);
    var match24 = time.match(/^(\d{1,2}):(\d{2})$/);
    var hours;
    var minutes;

    if (match12) {
      hours = parseInt(match12[1], 10);
      minutes = parseInt(match12[2], 10);
      if (match12[3] === 'pm' && hours < 12) hours += 12;
      if (match12[3] === 'am' && hours === 12) hours = 0;
    } else if (match24) {
      hours = parseInt(match24[1], 10);
      minutes = parseInt(match24[2], 10);
    } else {
      return null;
    }

    if (hours > 23 || minutes > 59) return null;

    d.setHours(hours, minutes, 0, 0);
    return d;
  }

  var now = new Date();
  var openTime = parseTime(open);
  var closeTime = parseTime(close);

  if (!openTime || !closeTime) return false;

  if (closeTime.getTime() === openTime.getTime()) return false;

  // Handle overnight windows (for example 18:00 to 02:00).
  if (closeTime < openTime) {
    return (now >= openTime || now <= closeTime);
  }

  return (now >= openTime && now <= closeTime);
}
/* RestroPress Frontend Functions */
jQuery(function ($) {
  if (rp_is_old_ui_ux_enabled()) {
    $('body').addClass('rp-old-ui-ux-enabled');
  } else {
    $('body').removeClass('rp-old-ui-ux-enabled');
  }

  function rp_has_rpress_interactive_ui() {
    return $('#rpressDateTime, #rpressModal, #rpress_checkout_wrap, .rpress-section').length > 0;
  }

  function rp_has_visible_open_modal($modals) {
    var hasVisible = false;
    $modals.each(function () {
      var $modal = $(this);
      var isOpen = $modal.hasClass('is-open') || $modal.attr('aria-hidden') === 'false';
      if (!isOpen) {
        return;
      }
      if ($modal.find('.modal__container:visible').length > 0 || $modal.is(':visible')) {
        hasVisible = true;
      }
    });
    return hasVisible;
  }

  function rp_reset_stuck_modal_state() {
    if (!rp_has_rpress_interactive_ui()) {
      return;
    }

    var $serviceModal = $('#rpressDateTime');
    var $itemModal = $('#rpressModal');
    var $modals = $serviceModal.add($itemModal);
    var $overlays = $('.modal__overlay, .micromodal-overlay, .modal-overlay');
    var modalVisible = rp_has_visible_open_modal($modals);
    var hasStaleOpenState = $modals.filter(function () {
      var $modal = $(this);
      return (
        $modal.hasClass('is-open') ||
        $modal.attr('aria-hidden') === 'false' ||
        $modal.hasClass('show-service-options') ||
        $modal.hasClass('show-order-details')
      );
    }).length > 0;
    var bodyLocked = $('body').hasClass('modal-open') || $('body').css('overflow') === 'hidden' || $('html').css('overflow') === 'hidden';

    // If no modal is actually visible, force-clear stale overlays/locks.
    if (!modalVisible && (hasStaleOpenState || $overlays.length > 0 || bodyLocked)) {
      $modals
        .removeClass('is-open loading show-service-options show-order-details')
        .attr('aria-hidden', 'true');

      $('html, body')
        .removeClass('modal-open')
        .css('overflow', '');
    }
  }

  rp_reset_stuck_modal_state();
  setTimeout(rp_reset_stuck_modal_state, 200);
  setTimeout(rp_reset_stuck_modal_state, 600);

  $(document).on('rpress_checked_slots rp-checkout-update-service-option', function () {
    setTimeout(rp_reset_stuck_modal_state, 100);
  });

  function rp_fix_footer_click_intercept() {
    var footer = document.getElementById('site-footer');
    if (!footer) {
      return;
    }

    var selectors = [
      '#editDateTime',
      '.rpress-category-link',
      '.rpress-checkout-cart',
      '.rpress_go_to_checkout',
      '.rpress-cart .rpress_checkout a',
      '#rpress_purchase_form input[type="text"]',
      '#rpress_checkout_wrap'
    ];

    var candidate = null;
    for (var i = 0; i < selectors.length; i++) {
      var node = document.querySelector(selectors[i]);
      if (!node) {
        continue;
      }
      var rect = node.getBoundingClientRect();
      if (rect.width > 0 && rect.height > 0) {
        candidate = node;
        break;
      }
    }

    if (!candidate) {
      return;
    }

    var r = candidate.getBoundingClientRect();
    var hit = document.elementFromPoint(r.left + (r.width / 2), r.top + (r.height / 2));
    if (hit && (hit === footer || footer.contains(hit))) {
      var main = document.querySelector('main, #content, .site-main');
      if (main) {
        main.style.position = 'relative';
        main.style.zIndex = '3';
      }
      footer.style.position = 'relative';
      footer.style.zIndex = '1';
    }
  }

  rp_fix_footer_click_intercept();
  setTimeout(rp_fix_footer_click_intercept, 120);
  $(window).on('resize.rpFooterFix load.rpFooterFix', rp_fix_footer_click_intercept);
  $(document).ajaxComplete(function () {
    setTimeout(rp_fix_footer_click_intercept, 60);
  });

  function rp_update_mobile_cart_summary(total, quantity) {
    var parsedQty = parseInt(quantity, 10);
    if (isNaN(parsedQty) || parsedQty < 0) {
      parsedQty = 0;
    }

    var formattedTotal = (typeof total === 'string' && total.length)
      ? total
      : (rp_scripts.currency_sign + '0.00');

    $('.rp-mb-price').text(formattedTotal);
    $('.rp-mb-quantity').text(parsedQty);
    $('span.rpress-cart-quantity').text(parsedQty);

    var hasItems = parsedQty > 0;
    if (hasItems) {
      $('.rpress-mobile-cart-icons').css('display', 'flex');
      $('.rpress.item-order').show();
    } else {
      $('.rpress-mobile-cart-icons').hide();
    }

    $('.container-actionmenu').toggleClass('cart-has-items', hasItems);
  }

  // Show order details on popup
  $(document)
    .on('click', '.rpress-view-order-btn', function (e) {
      e.preventDefault();
      var self = $(this);
      var action = 'rpress_show_order_details';
      var order_id = self.attr('data-order-id');
      var data = {
        action: action,
        order_id: order_id,
        security: rp_scripts.order_details_nonce
      };
      $('#rpressModal')
        .addClass('show-order-details');
      $.ajax({
        type: "POST",
        data: data,
        dataType: "json",
        url: rp_scripts.ajaxurl,
        beforeSend: (jqXHR, object) => {
          self.addClass('rp-loading');
          self.find('.rp-ajax-toggle-text')
            .addClass('rp-text-visibility');
        },
        complete: (jqXHR, object) => {
          self.removeClass('rp-loading');
          self.find('.rp-ajax-toggle-text')
            .removeClass('rp-text-visibility');
        },
        success: function (response) {
          $('#rpressModal .modal__container')
            .html(response.data.html);
          MicroModal.show('rpressModal', {
            disableScroll: true
          });
        }
      })
    });
  // Sticky category menu on mobile
  $(window)
    .resize(function () {
      if ($(window)
        .width() > 769) {
        $('.sticky-sidebar.cat-lists')
          .removeClass('rp-mobile-cat');
      } else {
        $('.sticky-sidebar.cat-lists')
          .addClass('rp-mobile-cat');
      }
    })
    .resize();
  // Hide Mneu on Click Float Cart
  $(document)
    .on('click', '.rpress-category-item', function () {
      $('.rp-mb-cat-ft-btn')
        .click();
    });
  // Hide Mneu on Click Items
  $(document)
    .on('click', '.rpress-mobile-cart-icons', function () {
      $('.rp-cat-overlay')
        .click();
    });
  // RP Hide overlay
  $(document)
    .on('click', '.rp-cat-overlay', function () {
      $('.rp-mb-cat-ft-btn')
        .click();
    });
  // Toggel mobile category menu
  $('.rp-mb-cat-ft-btn')
    .on('click', function () {
      $('.rp-mb-cat-ft-btn')
        .toggleClass('rp-close-menu');
      $('.sticky-sidebar.cat-lists')
        .toggleClass('rp-hide');
      $('body')
        .toggleClass('rp-cat-no-scroll');
      if ($('.sticky-sidebar.cat-lists')
        .hasClass('rp-hide'))
        $('body')
          .append('<div class="rp-cat-overlay"></div>');
      else
        $('.rp-cat-overlay')
          .remove();
    });
  $('.rp-mb-cat-ft-btn')
    .click(function () {
      $('.rp-mobile-cat')
        .toggle('fast');
      if ($(this)
        .hasClass('rp-close-menu')) {
        $('.rp-mb-cat-txt')
          .html(`<i class="fa fa-cutlery" aria-hidden="true"></i> ${rpress_scripts.close}`);
      } else {
        $('.rp-mb-cat-txt')
          .html(`<i class="fa fa-cutlery" aria-hidden="true"></i> ${rpress_scripts.menu}`);
      }
    });
  //Remove loading from modal
  $('#rpressModal')
    .removeClass('loading');
  //Remove service options from modal
  $('#rpressModal')
    .removeClass('show-service-options');
  $('#rpressModal')
    .removeClass('minimum-order-notice');
  $('#rpressModal')
    .on('hidden.bs.modal', function () {
      $('#rpressModal')
        .removeClass('show-service-options');
      $('#rpressModal')
        .removeClass('minimum-order-notice');
    });
  var ServiceType = rp_scripts.service_options;
  if (ServiceType == 'delivery_and_pickup') {
    ServiceType = 'delivery';
  }
  function rp_get_active_service_time_select($scope, preferredServiceType) {
    var $root = ($scope && $scope.length) ? $scope : $(document);
    var serviceType = (preferredServiceType || '')
      .toLowerCase();
    var $select = $();

    if (serviceType) {
      $select = $root.find('.delivery-settings-wrapper#nav-' + serviceType + ' .rpress-hrs')
        .first();
      if ($select.length) {
        return $select;
      }

      // Service pane exists but does not render a time selector (for example closed service).
      // Do not fall back to another service selector in this case.
      if ($root.find('.delivery-settings-wrapper#nav-' + serviceType).length) {
        return $select;
      }
    }

    $select = $root.find('.delivery-settings-wrapper.active .rpress-hrs')
      .first();
    if ($select.length) {
      return $select;
    }

    $select = $root.find('.delivery-settings-wrapper.show .rpress-hrs')
      .first();
    if ($select.length) {
      return $select;
    }

    $select = $root.find('.delivery-settings-wrapper:visible .rpress-hrs')
      .first();
    if ($select.length) {
      return $select;
    }

    return $root.find('#rpress-delivery-hours, .rpress-hrs')
      .first();
  }
  function rp_restore_service_time_select($select, serviceTime, allowFallbackSelection) {
    if (!$select || !$select.length) {
      return '';
    }

    var requestedTime = (serviceTime || '')
      .trim();
    var selectedValue = '';
    var shouldFallback = (allowFallbackSelection !== false);

    if (requestedTime && $select.find('option[value="' + requestedTime + '"]').length) {
      selectedValue = requestedTime;
    } else if (requestedTime) {
      var $matchingOption = $select.find('option')
        .filter(function () {
          return $(this)
            .text()
            .trim() === requestedTime;
        })
        .first();
      if ($matchingOption.length) {
        selectedValue = $matchingOption.val();
      }
    }

    if (!selectedValue) {
      var currentSelectedTime = ($select.val() || '')
        .toString()
        .trim();
      if (currentSelectedTime && $select.find('option[value="' + currentSelectedTime + '"]').length) {
        selectedValue = currentSelectedTime;
      }
    }

    if (!selectedValue && shouldFallback) {
      var $firstSelectableOption = $select.find('option')
        .filter(function () {
          var optionValue = ($(this)
            .val() || '')
            .toString()
            .trim();
          return optionValue !== '' && !$(this)
            .prop('disabled');
        })
        .first();

      if (!$firstSelectableOption.length) {
        $firstSelectableOption = $select.find('option')
          .first();
      }

      selectedValue = $firstSelectableOption.val() || '';
    }

    $select.val(selectedValue || '');

    return selectedValue;
  }
  function rp_restore_service_date_select($select, serviceDate, allowFallbackSelection) {
    if (!$select || !$select.length) {
      return '';
    }

    var requestedDate = (serviceDate || '')
      .toString()
      .trim();
    var selectedValue = '';
    var shouldFallback = (allowFallbackSelection !== false);

    if (requestedDate && $select.find('option[value="' + requestedDate + '"]').length) {
      selectedValue = requestedDate;
    } else if (requestedDate) {
      var $matchingOption = $select.find('option')
        .filter(function () {
          return ($(this)
            .text() || '')
            .toString()
            .trim() === requestedDate;
        })
        .first();
      if ($matchingOption.length) {
        selectedValue = $matchingOption.val();
      }
    }

    if (!selectedValue) {
      var currentSelectedDate = ($select.val() || '')
        .toString()
        .trim();
      if (currentSelectedDate && $select.find('option[value="' + currentSelectedDate + '"]').length) {
        selectedValue = currentSelectedDate;
      }
    }

    if (!selectedValue && shouldFallback) {
      var $firstSelectableOption = $select.find('option')
        .filter(function () {
          var optionValue = ($(this)
            .val() || '')
            .toString()
            .trim();
          return optionValue !== '' && !$(this)
            .prop('disabled');
        })
        .first();

      if (!$firstSelectableOption.length) {
        $firstSelectableOption = $select.find('option')
          .first();
      }

      selectedValue = ($firstSelectableOption.val() || '')
        .toString()
        .trim();
    }

    $select.val(selectedValue || '');

    return selectedValue;
  }
  function rp_ensure_select_placeholder($select, placeholderText) {
    if (!$select || !$select.length) {
      return;
    }

    var $existingPlaceholder = $select.find('option[data-rp-placeholder="1"]').first();
    if ($existingPlaceholder.length) {
      return;
    }

    var text = (placeholderText || '').toString().trim();
    if (!text) {
      text = 'Select an option';
    }

    var $placeholder = $('<option />', {
      value: '',
      text: text
    })
      .attr('data-rp-placeholder', '1');

    $select.prepend($placeholder);
  }
  function rp_prepare_old_ui_modal_selection($scope) {
    if (!rp_is_old_ui_ux_enabled()) {
      return;
    }

    var $root = ($scope && $scope.length) ? $scope : $(document);
    var selectedServiceType = (rp_getCookie('service_type') || '')
      .toString()
      .trim()
      .toLowerCase();
    var selectedServiceDate = (rp_getCookie('service_date') || rp_getCookie('delivery_date') || '')
      .toString()
      .trim();
    var selectedServiceTime = (rp_getCookie('service_time') || rp_getCookie('service_time_text') || '')
      .toString()
      .trim();
    var requiresServiceChoice = $root.find('#rpressdeliveryTab .single-service-selected').length > 1;

    if (!selectedServiceType && requiresServiceChoice) {
      var $firstServiceTab = $root.find('#rpressdeliveryTab .single-service-selected')
        .first();
      if ($firstServiceTab.length) {
        selectedServiceType = String($firstServiceTab.data('service-type') || '')
          .toLowerCase();
      }
    }

    if (selectedServiceType) {
      rp_sync_service_ui_state($root, selectedServiceType, false);
    }

    $root.find('.rpress_get_delivery_dates').each(function () {
      var $dateSelect = $(this);
      rp_ensure_select_placeholder($dateSelect, 'Select a date');
      if (!selectedServiceDate) {
        $dateSelect.val('');
      }
    });

    $root.find('.delivery-settings-wrapper').each(function () {
      var $pane = $(this);
      var paneServiceType = String($pane.attr('id') || '')
        .replace(/^nav-/, '')
        .toLowerCase();

      $pane.find('.rpress-hrs').each(function () {
        var $timeSelect = $(this);
        if (rp_is_service_time_hidden(paneServiceType)) {
          return;
        }
        rp_ensure_select_placeholder($timeSelect, 'Select a time');
        if (!selectedServiceTime) {
          $timeSelect.val('');
        }
      });
    });
  }
  function rp_is_service_time_hidden(serviceType) {
    var normalizedServiceType = String(serviceType || '')
      .toLowerCase();
    if (!window.rp_otil_vars) {
      return false;
    }

    return (
      (normalizedServiceType === 'pickup' && window.rp_otil_vars.disable_pickup_time === '1') ||
      (normalizedServiceType === 'delivery' && window.rp_otil_vars.disable_delivery_time === '1')
    );
  }
  function rp_get_asap_fallback_time(serviceType) {
    var normalizedServiceType = String(serviceType || '')
      .toLowerCase();
    var fallbackTime = 'ASAP';

    if (normalizedServiceType === 'pickup' && window.rp_otil_vars && window.rp_otil_vars.pickup_asap_text) {
      fallbackTime += ' ' + window.rp_otil_vars.pickup_asap_text;
    } else if (normalizedServiceType === 'delivery' && window.rp_otil_vars && window.rp_otil_vars.delivery_asap_text) {
      fallbackTime += ' ' + window.rp_otil_vars.delivery_asap_text;
    }

    return fallbackTime;
  }
  function rp_apply_service_defaults($scope, preferredServiceType, persistCookies, requireExplicitSelection, preferCurrentSelection) {
    var shouldPersistCookies = (persistCookies !== false);
    var enforceManualSelection = (requireExplicitSelection === true);
    var shouldPreferCurrentSelection = (preferCurrentSelection === true);
    var $root = ($scope && $scope.length) ? $scope : $(document);
    var serviceType = rp_get_active_service_type($root, preferredServiceType);
    serviceType = rp_sync_service_ui_state($root, serviceType, shouldPersistCookies) || serviceType;

    var requestedServiceDate = (rp_getCookie('service_date') || rp_getCookie('delivery_date') || '')
      .toString()
      .trim();
    var $activeDateSelect = rp_get_active_service_date_select($root, serviceType);
    var serviceDate = '';
    var serviceDateText = '';

    if (shouldPreferCurrentSelection && $activeDateSelect.length) {
      requestedServiceDate = ($activeDateSelect.val() || '')
        .toString()
        .trim();
    }

    if ($activeDateSelect.length) {
      serviceDate = rp_restore_service_date_select(
        $activeDateSelect,
        requestedServiceDate,
        !enforceManualSelection
      );
      serviceDateText = ($activeDateSelect.find('option:selected')
        .text() || '')
        .toString()
        .trim();
    } else {
      serviceDate = requestedServiceDate;
      serviceDateText = requestedServiceDate;
    }

    if (!$activeDateSelect.length) {
      var fallbackDateText = ($('#deliveryDate').first().text() || '')
        .toString()
        .trim()
        .replace(/,\s*$/, '');
      if (fallbackDateText) {
        serviceDateText = fallbackDateText;
      }
    }

    if (serviceDate && shouldPersistCookies) {
      rp_setCookie('service_date', serviceDate, rp_scripts.expire_cookie_time);
      rp_setCookie('delivery_date', serviceDateText || serviceDate, rp_scripts.expire_cookie_time);
    }

    var requestedServiceTime = (rp_getCookie('service_time') || rp_getCookie('service_time_text') || '')
      .toString()
      .trim();
    var $activeTimeSelect = rp_get_active_service_time_select($root, serviceType);
    var serviceTime = '';
    var serviceTimeText = '';
    var isServiceTimeHidden = rp_is_service_time_hidden(serviceType);

    if (shouldPreferCurrentSelection && $activeTimeSelect.length) {
      requestedServiceTime = ($activeTimeSelect.val() || '')
        .toString()
        .trim();
    }

    if (isServiceTimeHidden) {
      serviceTime = rp_get_asap_fallback_time(serviceType);
      serviceTimeText = serviceTime;
    } else if ($activeTimeSelect.length) {
      serviceTime = rp_restore_service_time_select(
        $activeTimeSelect,
        requestedServiceTime,
        !enforceManualSelection
      );
      serviceTimeText = ($activeTimeSelect.find('option:selected')
        .text() || '')
        .toString()
        .trim();
    } else {
      serviceTime = requestedServiceTime;
      serviceTimeText = requestedServiceTime;
    }

    if (!$activeTimeSelect.length) {
      var fallbackTimeText = ($('#deliveryTime').first().text() || '')
        .toString()
        .trim();
      if (fallbackTimeText) {
        serviceTimeText = fallbackTimeText;
      }
    }

    if (serviceTime && shouldPersistCookies) {
      rp_setCookie('service_time', serviceTime, rp_scripts.expire_cookie_time);
      rp_setCookie('service_time_text', serviceTimeText || serviceTime, rp_scripts.expire_cookie_time);
    }

    return {
      serviceType: serviceType,
      serviceDate: serviceDate,
      serviceDateText: serviceDateText,
      serviceTime: serviceTime,
      serviceTimeText: serviceTimeText
    };
  }
  function rp_get_active_service_type($scope, fallbackServiceType) {
    var $root = ($scope && $scope.length) ? $scope : $(document);
    var serviceType = '';
    var $activeServiceTab = $root.find('#rpressdeliveryTab .single-service-selected[aria-selected="true"]')
      .first();

    if (!$activeServiceTab.length) {
      $activeServiceTab = $root.find('#rpressdeliveryTab .nav-item.active .single-service-selected')
        .first();
    }

    if (!$activeServiceTab.length) {
      $activeServiceTab = $root.find('#rpressdeliveryTab .single-service-selected.active')
        .first();
    }

    if ($activeServiceTab.length) {
      serviceType = String($activeServiceTab.data('service-type') || '')
        .toLowerCase();
    }

    if (!serviceType) {
      var $activeServicePane = $root.find('.delivery-settings-wrapper.active[id^="nav-"], .delivery-settings-wrapper.show[id^="nav-"]')
        .first();
      if ($activeServicePane.length) {
        serviceType = String($activeServicePane.attr('id') || '')
          .replace(/^nav-/, '')
          .toLowerCase();
      }
    }

    if (!serviceType) {
      var $serviceTabsWrapper = $root.find('.rpress-tabs-wrapper.service-option-delivery, .rpress-tabs-wrapper.service-option-pickup')
        .first();
      if ($serviceTabsWrapper.length) {
        if ($serviceTabsWrapper.hasClass('service-option-delivery')) {
          serviceType = 'delivery';
        } else if ($serviceTabsWrapper.hasClass('service-option-pickup')) {
          serviceType = 'pickup';
        }
      }
    }

    if (!serviceType) {
      serviceType = String(
        fallbackServiceType || rp_getCookie('service_type') || rp_scripts.default_service || 'delivery'
      )
        .toLowerCase();
    }

    if (serviceType !== 'delivery' && serviceType !== 'pickup') {
      serviceType = 'delivery';
    }

    return serviceType;
  }
  function rp_sync_service_ui_state($scope, serviceType, persistCookie) {
    var normalizedServiceType = String(serviceType || '')
      .toLowerCase();

    if (normalizedServiceType !== 'delivery' && normalizedServiceType !== 'pickup') {
      return '';
    }

    var $root = ($scope && $scope.length) ? $scope : $(document);
    var $wrappers = $root.find('.rpress-tabs-wrapper');

    if (!$wrappers.length && $root.hasClass('rpress-tabs-wrapper')) {
      $wrappers = $root;
    }

    $wrappers.each(function () {
      var $wrapper = $(this);
      var $serviceTab = $wrapper.find('#rpressdeliveryTab .single-service-selected[data-service-type="' + normalizedServiceType + '"]')
        .first();

      $wrapper.removeClass('service-option-delivery service-option-pickup')
        .addClass('service-option-' + normalizedServiceType);

      if ($serviceTab.length) {
        $wrapper.find('#rpressdeliveryTab .nav-item').removeClass('active');
        $wrapper.find('#rpressdeliveryTab .single-service-selected')
          .removeClass('active')
          .attr('aria-selected', 'false');

        $serviceTab
          .addClass('active')
          .attr('aria-selected', 'true');
        $serviceTab.closest('.nav-item').addClass('active');

        var targetPane = $serviceTab.attr('href');
        if (targetPane && targetPane.charAt(0) === '#') {
          $wrapper.find('.delivery-settings-wrapper').removeClass('active show');
          $wrapper.find(targetPane).addClass('active show');
        }
      }
    });

    if (persistCookie !== false) {
      rp_setCookie('service_type', normalizedServiceType, rp_scripts.expire_cookie_time);
    }

    return normalizedServiceType;
  }
  function rp_sync_service_selection_cookies($scope, preferredServiceType) {
    var defaults = rp_apply_service_defaults($scope, preferredServiceType);
    if (!defaults.serviceTimeText) {
      defaults.serviceTimeText = ($('#deliveryTime')
        .first()
        .text() || '')
        .toString()
        .trim();
      if (defaults.serviceTimeText) {
        rp_setCookie('service_time_text', defaults.serviceTimeText, rp_scripts.expire_cookie_time);
      }
    }

    return defaults;
  }
  function rp_get_active_service_date_select($scope, preferredServiceType) {
    var $root = ($scope && $scope.length) ? $scope : $(document);
    var serviceType = (preferredServiceType || '')
      .toLowerCase();
    var $select = $();

    if (serviceType) {
      $select = $root.find('.delivery-settings-wrapper#nav-' + serviceType + ' .rpress_get_delivery_dates')
        .first();
      if ($select.length) {
        return $select;
      }
    }

    $select = $root.find('.delivery-settings-wrapper.active .rpress_get_delivery_dates')
      .first();
    if ($select.length) {
      return $select;
    }

    $select = $root.find('.delivery-settings-wrapper.show .rpress_get_delivery_dates')
      .first();
    if ($select.length) {
      return $select;
    }

    $select = $root.find('.delivery-settings-wrapper:visible .rpress_get_delivery_dates')
      .first();
    if ($select.length) {
      return $select;
    }

    return $root.find('.rpress_get_delivery_dates')
      .first();
  }
  // Expose helpers for other frontend blocks that execute in separate jQuery scopes.
  window.rp_get_active_service_type = rp_get_active_service_type;
  window.rp_sync_service_ui_state = rp_sync_service_ui_state;
  window.rp_sync_service_selection_cookies = rp_sync_service_selection_cookies;
  window.rp_get_active_service_time_select = rp_get_active_service_time_select;
  window.rp_restore_service_time_select = rp_restore_service_time_select;
  window.rp_restore_service_date_select = rp_restore_service_date_select;
  window.rp_apply_service_defaults = rp_apply_service_defaults;
  window.rp_is_service_time_hidden = rp_is_service_time_hidden;
  window.rp_is_old_ui_ux_enabled = rp_is_old_ui_ux_enabled;
  window.rp_clear_old_ui_service_cookies = rp_clear_old_ui_service_cookies;
  window.rp_prepare_old_ui_modal_selection = rp_prepare_old_ui_modal_selection;
  // Add to Cart
  $('.rpress-add-to-cart')
    .click(function (e) {
      e.preventDefault();
      var _self = $(this);
      var fooditem_id = _self.attr('data-fooditem-id');
      var oldUiUxEnabled = rp_is_old_ui_ux_enabled();
      var hasRequiredServiceContext = rp_get_storage_data();

      if (oldUiUxEnabled && !hasRequiredServiceContext) {
        $('#rpressModal')
          .removeClass('rpress-delivery-options rpress-food-options checkout-error')
          .addClass('show-service-options');

        $.ajax({
          type: "POST",
          data: {
            action: 'rpress_show_delivery_options',
            fooditem_id: fooditem_id,
            security: rp_scripts.service_type_nonce
          },
          dataType: "json",
          url: rp_scripts.ajaxurl,
          beforeSend: function () {
            _self.addClass('rp-loading');
            _self.find('.add-icon').addClass('icon-loading-toggle');
            _self.find('.rp-ajax-toggle-text').addClass('rp-text-visibility');
          },
          complete: function () {
            _self.removeClass('rp-loading');
            _self.find('.add-icon').removeClass('icon-loading-toggle');
            _self.find('.rp-ajax-toggle-text').removeClass('rp-text-visibility');
          },
          success: function (response) {
            if (!response || !response.data) {
              return;
            }
            $('#rpressModal .modal-title').html(response.data.html_title || '');
            $('#rpressModal .modal-body').html(response.data.html || '');
            if (typeof window.rp_prepare_old_ui_modal_selection === 'function') {
              window.rp_prepare_old_ui_modal_selection($('#rpressModal .modal-body'));
            }
            MicroModal.show('rpressModal', {
              disableScroll: true
            });
            $(document.body).trigger('opened_service_options', [response.data]);
          }
        });
        return;
      }

      var $serviceTypeScope = $('.rpress-delivery-wrap .rpress-tabs-wrapper:visible').first();
      var activeServiceTypeForValidation = rp_get_active_service_type(
        $serviceTypeScope.length ? $serviceTypeScope : $(document),
        rp_getCookie('service_type') || rp_scripts.default_service || 'delivery'
      );
      activeServiceTypeForValidation = rp_sync_service_ui_state($(document), activeServiceTypeForValidation) || activeServiceTypeForValidation;

      if (activeServiceTypeForValidation === 'delivery') {
        var delivery_zip = rp_getCookie('delivery_zip');
        var delivery_location = rp_getCookie('delivery_location');
        var delivery_address = rp_getCookie('delivery_address');

        if (!delivery_zip) {
          var $rp_delivery_zone = $('input#rp_delivery_zone'); // adjust selector if needed
          // Check if the delivery zone input exists and has a value
          if ($rp_delivery_zone.length > 0 && !$rp_delivery_zone.val().trim()) {
            // Show error
            tata.error('Error', 'Please enter ZIP code', { position: "tr" });

            // Trigger Edit button click after 1 second
            setTimeout(function () {
              $('#editDateTime').trigger('click');
            }, 500);

            return; // stop further execution
          }
        }

        if (!delivery_location) {
          var $rp_delivery_location = $('input#rp_delivery_location'); // adjust selector if needed
          if (!delivery_address) {
            // Check if the delivery zone input exists and has a value
            if ($rp_delivery_location.length > 0 && !$rp_delivery_location.val().trim()) {
              // Show error
              tata.error('Error', 'Please enter location', { position: "tr" });

              // Trigger Edit button click after 1 second
              setTimeout(function () {
                $('#editDateTime').trigger('click');
              }, 500);

              return; // stop further execution
            }
          }
        }
      }

      var $serviceScope = $('.rpress-delivery-wrap .rpress-tabs-wrapper:visible')
        .first();
      var syncedSelection = rp_sync_service_selection_cookies(
        $serviceScope.length ? $serviceScope : $(document)
      );
      var serviceType = syncedSelection.serviceType;

      var $serviceControlsScope = $('#rpressDateTime-content');
      if (!$serviceControlsScope.length) {
        $serviceControlsScope = $('#rpressDateTime');
      }
      if (!$serviceControlsScope.length) {
        $serviceControlsScope = $(document);
      }

      var normalizedSelection = rp_apply_service_defaults($serviceControlsScope, serviceType);
      serviceType = normalizedSelection.serviceType || serviceType;
      var serviceDate = (normalizedSelection.serviceDate || '')
        .toString()
        .trim();
      var serviceTime = (normalizedSelection.serviceTime || '')
        .toString()
        .trim();

      var getClosedMessage = function () {
        var selectors = [
          '.rpress_order-address-wrap #deliveryDate.rp-store-timing-notice:visible',
          '.rpress_order-address-wrap .rp-store-timing-notice:visible',
          '.delivery-settings-wrapper#nav-' + serviceType + ' .rpress-service-closed-message:visible',
          '#rpressDateTime .rpress-service-closed-message:visible',
          '.rpress_order-address-wrap #deliveryDate.rp-store-timing-notice',
          '.rpress_order-address-wrap .rp-store-timing-notice',
          '.delivery-settings-wrapper#nav-' + serviceType + ' .rpress-service-closed-message',
          '#rpressDateTime .rpress-service-closed-message'
        ];
        for (var i = 0; i < selectors.length; i++) {
          var message = $(selectors[i])
            .first()
            .text()
            .trim();
          if (message) {
            return message;
          }
        }
        return '';
      };

      var serviceClosedMessage = getClosedMessage();
      if (serviceClosedMessage) {
        tata.error('Error', serviceClosedMessage, { position: "tr" });
        return;
      }

      var isServiceTimeDisabled = rp_is_service_time_hidden(serviceType);

      if (!isServiceTimeDisabled && !serviceTime) {
        var closedMessage = serviceClosedMessage || getClosedMessage();
        if (closedMessage) {
          tata.error('Error', closedMessage, { position: "tr" });
        } else {
          $('#editDateTime').trigger('click');
          var $serviceDateModal = $('#rpressDateTime');
          var isDateTimeModalVisible = $serviceDateModal.length &&
            ($serviceDateModal.hasClass('is-open') || $serviceDateModal.attr('aria-hidden') === 'false') &&
            $serviceDateModal.find('.modal__container:visible').length > 0;

          if (!isDateTimeModalVisible) {
            var $legacyServiceChange = $('.delivery-change:visible').first();
            if (!$legacyServiceChange.length) {
              $legacyServiceChange = $('.delivery-change').first();
            }
            if ($legacyServiceChange.length) {
              $legacyServiceChange.trigger('click');
            }
          }
        }
        return;
      }
      var rp_get_delivery_data = rp_get_storage_data();
      $('#rpressModal')
        .removeClass('rpress-delivery-options rpress-food-options checkout-error');
      $('#rpressModal .qty')
        .val('1');
      $('#rpressModal')
        .find('.cart-action-text')
        .html(rp_scripts.add_to_cart);
      if (!rp_get_delivery_data) {
        var action = 'rpress_show_delivery_options';
        var security = rp_scripts.service_type_nonce;
        $('#rpressModal')
          .addClass('show-service-options');
      } else {
        $('#rpressModal')
          .removeClass('show-service-options');
        var action = 'rpress_show_products';
        var security = rp_scripts.show_products_nonce;
      }
      var foodItemName = _self.attr('data-title');
      var price = _self.attr('data-price');
      var variable_price = _self.attr('data-variable-price');
      var data = {
        action: action,
        fooditem_id: fooditem_id,
        security: security,
        service_type: serviceType,
        selected_date: serviceDate,
        selected_time: serviceTime
      };
      $.ajax({
        type: "POST",
        data: data,
        dataType: "json",
        url: rp_scripts.ajaxurl,
        beforeSend: (jqXHR, status) => {
          _self.addClass('rp-loading');
          _self.find('.add-icon').addClass('icon-loading-toggle');
          _self.find('.rp-ajax-toggle-text')
            .addClass('rp-text-visibility');
        },
        xhrFields: {
          withCredentials: true
        },
        complete: (jqXHR, object) => {
          _self.removeClass('rp-loading');
          _self.find('.add-icon').removeClass('icon-loading-toggle');
          _self.find('.rp-ajax-toggle-text')
            .removeClass('rp-text-visibility');

        },
        success: function (response) {
          if (response?.success === false && response?.data?.status === 'error') {
            tata.error('Error', response?.data?.error_msg, { position: "tr" });
            return;
          }
          MicroModal.show('rpressModal', {
            disableScroll: true
          });
          $('#rpressModal').removeClass('loading');

          $('#rpressModal .modal-title')
            .html(response.data.html_title);
          $('#rpressModal .modal-body')
            .html(response.data.html);
          $('#rpressModal .cart-item-price')
            .html(response.data.price);
          $('#rpressModal .item-description')
            .html(response.data.description);

          $('#rpressModal .item-image').attr('src', '');
          if (response.data.image_url) {
            $('#rpressModal .item-image').attr('src', response.data.image_url);
          }
          $('#rpressModal .cart-item-price')
            .attr('data-price', response.data.price_raw);
          // Trigger event so themes can refresh other areas.
          $(document.body)
            .trigger('opened_service_options', [response.data]);
          $('#rpressModal')
            .find('.submit-fooditem-button')
            .attr('data-cart-action', 'add-cart');
          $('#rpressModal')
            .find('.cart-action-text')
            .html(rp_scripts.add_to_cart);
          if (fooditem_id !== '' && price !== '') {
            $('#rpressModal')
              .find('.submit-fooditem-button')
              .attr('data-item-id', fooditem_id);
            $('#rpressModal')
              .find('.submit-fooditem-button')
              .attr('data-title', foodItemName);
            $('#rpressModal')
              .find('.submit-fooditem-button')
              .attr('data-item-price', price);
            $('#rpressModal')
              .find('.submit-fooditem-button')
              .attr('data-item-qty', 1);
          }
          update_modal_live_price('fooditem-details');
          rp_checked_default_subaddon();
        }
      });
    });
  // Update Cart
  $('.rpress-sidebar-cart')
    .on('click', 'a.rpress-edit-from-cart', function (e) {
      e.preventDefault();
      var _self = $(this);
      _self.parents('.rpress-cart-item')
        .addClass('edited');
      var CartItemId = _self.attr('data-remove-item');
      var FoodItemId = _self.attr('data-item-id');
      var FoodItemName = _self.attr('data-item-name');
      var FoodQuantity = _self.parents('.rpress-cart-item')
        .find('.rpress-cart-item-qty')
        .text();
      var action = 'rpress_edit_cart_fooditem';
      var security = rp_scripts.edit_cart_fooditem_nonce;
      var data = {
        action: action,
        cartitem_id: CartItemId,
        fooditem_id: FoodItemId,
        fooditem_name: FoodItemName,
        security: security,
      };
      if (CartItemId !== '') {
        $.ajax({
          type: "POST",
          data: data,
          dataType: "json",
          url: rp_scripts.ajaxurl,
          beforeSend: (jqXHR, status) => {
            _self.addClass('rp-loading');
            _self.find('.rp-ajax-toggle-text')
              .addClass('rp-text-visibility');
          },
          complete: (jqXHR, object) => {
            _self.removeClass('rp-loading');
            _self.find('.rp-ajax-toggle-text')
              .removeClass('rp-text-visibility');
          },
          xhrFields: {
            withCredentials: true
          },
          success: function (response) {
            MicroModal.show('rpressModal', {
              disableScroll: true
            });
            $('#rpressModal')
              .removeClass('checkout-error');
            $('#rpressModal')
              .removeClass('show-service-options');
            $('#rpressModal')
              .removeClass('loading');
            $('#rpressModal .modal-title')
              .html(response.data.html_title);
            $('#rpressModal')
              .find(".qty")
              .val(FoodQuantity);
            $('#rpressModal .item-description').html(response.data.description);
            $('#rpressModal')
              .find('.submit-fooditem-button')
              .attr('data-item-id', FoodItemId);
            $('#rpressModal')
              .find('.submit-fooditem-button')
              .attr('data-title', FoodItemName);
            $('#rpressModal .item-image').attr('src', '');
            if (response.data.image_url) {
              $('#rpressModal .item-image').attr('src', response.data.image_url);
            }
            $('#rpressModal')
              .find('.submit-fooditem-button')
              .attr('data-cart-key', CartItemId);
            $('#rpressModal')
              .find('.submit-fooditem-button')
              .attr('data-cart-action', 'update-cart');
            $('#rpressModal')
              .find('.submit-fooditem-button')
              .find('.cart-action-text')
              .html(rp_scripts.update_cart);
            $('#rpressModal')
              .find('.submit-fooditem-button')
              .find('.cart-item-price')
              .html(response.data.price);
            $('#rpressModal')
              .find('.submit-fooditem-button')
              .find('.cart-item-price')
              .attr('data-price', response.data.price_raw);
            $('#rpressModal')
              .find('.submit-fooditem-button')
              .attr('data-item-qty', FoodQuantity);
            $('#rpressModal .modal-body')
              .html(response.data.html);

            // Auto-check addons that were already selected.
            if (response.data.addon_items) {
              $.each(response.data.addon_items, function (i, addon) {
                var addonId = addon.addon_id;
                var qty = addon.quantity;

                // Find all checkboxes that belong to this addon_id (multiple clones may exist)
                var $checkboxes = $('#rpressModal .modal-body input[type="checkbox"][value^="' + addonId + '|"]');

                if ($checkboxes.length) {
                  $checkboxes.each(function (index, checkbox) {
                    var $cb = $(checkbox);
                    $cb.prop('checked', true);

                    // Go to its quantity input inside .food-item-list
                    var $qtyInput = $cb.closest('.food-item-list').find('.addon_qty');

                    if ($qtyInput.length) {
                      $qtyInput.val(qty);   // set correct quantity

                      // Ã°Å¸â€Â¥ Optional: also mark its parent .food-item-list as "active" if your UI needs it
                      $cb.closest('.food-item-list').addClass('active');
                    }
                  });
                }
              });
            }
            update_modal_live_price('fooditem-update-details');
          }
        });
      }
    });
  // Add to Cart / Update Cart Button From Popup
  $(document).on('click', '.submit-fooditem-button', function (e) {
    e.preventDefault();
    var self = $(this);
    var cartAction = self.attr('data-cart-action');
    var text = self.find('span.cart-action-text').text();
    var validation = '';
    // Checking the Required & Max addon settings for Addons
    if (jQuery('.addons-wrapper').length > 0) {
      jQuery('.addons-wrapper').each(function (index, el) {
        var _self = jQuery(this);
        var addon = _self.attr('data-id');
        var is_required = _self.children('input.addon_is_required').val();
        var max_addons = _self.children('input.addon_max_limit').val();
        var min_addons = _self.children('input.addon_min_limit').val();
        var checked = _self.find('.food-item-list.active input:checked').length;

        var customValidation = {
          isValid: true,
          message: '',
          element: _self,
          minAddons: min_addons,
          maxAddons: max_addons,
          checkedAddons: checked
        };

        // Trigger custom validation hook
        $(document).trigger('rpress_addon_validation', customValidation);
        _self.find('.rp-addon-error')
          .removeClass('rp-addon-error');
        if (is_required == 'yes' && checked == 0) {
          _self.find('.rp-addon-required').addClass('rp-addon-error');
          validation = 1;
        } else if (max_addons != 0 && checked > max_addons) {
          _self.find('.rp-addon-required').addClass('rp-addon-error');
          _self.find('.rp-max-addon').addClass('rp-addon-error');
          _self.find(".rpress-addon-category").addClass('rp-addon-error');

          validation = 1;
        } else if (min_addons != 0 && checked < min_addons) {
          _self.find('.rp-addon-required').addClass('rp-addon-error');
          _self.find('.rp-min-addon').addClass('rp-addon-error');
          _self.find(".rpress-addon-category").addClass('rp-addon-error');

          validation = 1;
        } else if (!customValidation.isValid) {
          _self.find('.rp-addon-required').addClass('rp-addon-error');
          _self.find('.rp-min-addon').addClass('rp-addon-error');
          _self.find(".rpress-addon-category").addClass('rp-addon-error');
          validation = 1;
        }

        if (validation === 1) {
          var $error = $('#rpressModal .rp-addon-error').first();
          if ($error.length) {
            $error[0].scrollIntoView({ behavior: 'smooth', block: 'start' });
          }
        }

        if (validation != '') {
          self.removeClass('disable_click');
          self.find('.cart-action-text')
            .text(text);
          return false;
        }
      });
    }
    if (cartAction == 'add-cart' && validation == '') {
      self.addClass('disable_click');
      var this_form = self.parents('.modal')
        .find('form#fooditem-details .food-item-list.active input');
      var itemId = self.attr('data-item-id');
      var itemName = self.attr('data-title');
      var itemQty = self.attr('data-item-qty');
      var FormData = this_form.serializeArray();
      var SpecialInstruction = self.parents('.modal')
        .find('textarea.special-instructions')
        .val();
      var action = 'rpress_add_to_cart';
      var data = {
        action: action,
        fooditem_id: itemId,
        fooditem_qty: itemQty,
        special_instruction: SpecialInstruction,
        post_data: FormData,
        security: rp_scripts.add_to_cart_nonce
      };
      const float_menu = $(".container-actionmenu");

      if (itemId !== '') {
        $.ajax({
          type: "POST",
          data: data,
          dataType: "json",
          url: rp_scripts.ajaxurl,
          xhrFields: {
            withCredentials: true
          },
          beforeSend: (jqXHR, object) => {
            self.addClass('rp-loading');
            self.find('.rp-ajax-toggle-text')
              .addClass('rp-text-visibility')
            if (float_menu.length > 0) {
              float_menu.removeClass("cart-has-items");
            }
          },
          complete: (jqXHR, object) => {
            self.removeClass('rp-loading');
            self.find('.rp-ajax-toggle-text')
              .removeClass('rp-text-visibility')
          },
          success: function (response) {
            if (response) {
              $('.rpress-mobile-cart-icons')
                .css({
                  display: 'flex'
                });
              self.removeClass('disable_click');
              self.find('.cart-action-text')
                .text(text);
              var serviceType = rp_getCookie('service_type');
              var serviceTime = rp_getCookie('service_time');
              var serviceTimeText = rp_getCookie('service_time_text');
              var serviceDate = rp_getCookie('delivery_date');
              $('ul.rpress-cart')
                .find('li.cart_item.empty')
                .remove();
              $('ul.rpress-cart')
                .find('li.cart_item.rpress_subtotal')
                .remove();
              $('ul.rpress-cart')
                .find('li.cart_item.cart-sub-total')
                .remove();
              $('ul.rpress-cart')
                .find('li.cart_item.rpress_cart_tax')
                .remove();
              $('ul.rpress-cart')
                .find('li.cart_item.rpress-cart-meta.rpress-delivery-fee')
                .remove();
              $('ul.rpress-cart')
                .find('li.cart_item.rpress-cart-meta.rpress_subtotal')
                .remove();
              var $target = $('ul.rpress-cart div.rpress-cart-total-wrap');

              if ($target.length) {
                $(response.cart_item).insertBefore($target);
              } else {
                $(response.cart_item).insertBefore('ul.rpress-cart li.cart_item.rpress_total');
              }
              if (float_menu.length > 0) {
                float_menu.addClass("cart-has-items");
              }

              if ($('.rpress-cart')
                .find('.rpress-cart-meta.rpress_subtotal')
                .is(':first-child')) {
                $(this)
                  .hide();
              }
              rp_update_mobile_cart_summary(response.total, response.cart_quantity);
              $('.cart_item.rpress-cart-meta.rpress_total')
                .find('.cart-total')
                .text(response.total);
              $('.cart_item.rpress-cart-meta.rpress_subtotal')
                .find('.subtotal')
                .text(response.total);
              $('.cart_item.rpress-cart-meta.rpress_total')
                .css('display', 'block');
              $('.cart_item.rpress-cart-meta.rpress_subtotal')
                .css('display', 'block');
              $('.cart_item.rpress_checkout')
                .addClass(rp_scripts.button_color);
              $('.cart_item.rpress_checkout')
                .css('display', 'block');
              if (serviceType !== undefined) {
                serviceLabel = window.localStorage.getItem('serviceLabel');
                var orderInfo = '<span class="delMethod">' + serviceLabel + ', ' + serviceDate + '</span>';
                if (serviceTime !== undefined) {
                  // Check if the string contains 'ASAP'
                  if (serviceTime.includes('ASAP')) {
                    // Remove 'ASAP' from the string
                    serviceTimeText = serviceTime.replace('ASAP', '');
                    serviceTimeText = rp_scripts.asap_txt + ' ' + serviceTimeText;
                  }
                  orderInfo += '<span class="delTime">, ' + serviceTimeText + '</span>';
                }
                $('.delivery-items-options')
                  .find('.delivery-opts')
                  .html(orderInfo);
                if ($('.delivery-wrap .delivery-change')
                  .length == 0) {
                  $("<a href='#' class='delivery-change'>" + rp_scripts.change_txt + "</a>")
                    .insertAfter(".delivery-opts");
                }
              }
              $('.delivery-items-options')
                .css('display', 'block');
              var subTotal = '<li class="cart_item rpress-cart-meta rpress_subtotal">' + rp_scripts.total_text + '<span class="cart-subtotal">' + response.subtotal + '</span></li>';
              if (response.subtotal) {
                var cartLastChild = $('ul.rpress-cart>li.rpress-cart-item:last');
                $(subTotal).insertAfter(cartLastChild);
              }
              $('.cart_item.rpress-cart-meta.rpress_total')
                .find('.rpress-cart-quantity')
                .text(response.cart_quantity);
              if (response.taxes) {
                var taxHtml = '<li class="cart_item rpress-cart-meta rpress_cart_tax">' + rp_scripts.estimated_tax + '<span class="cart-tax">' + response.taxes + '</span></li>';
                $(taxHtml)
                  .insertBefore('ul.rpress-cart li.cart_item.rpress_total');
              }
              if (response.taxes === undefined) {
                $('ul.rpress-cart')
                  .find('.cart_item.rpress-cart-meta.rpress_subtotal')
                  .remove();
                var cartLastChild = $('ul.rpress-cart>li.rpress-cart-item:last');
                $(subTotal).insertAfter(cartLastChild);
              }
              if ($('div.rpress.item-order').length == 0) {
                var orderitems = $('<div class="rpress item-order"><h4>Ordered menu</h4><span>1 items</span></div>');
                $('div.rpress-sidebar-main-wrap div.rpress-sidebar-cart-wrap').removeClass('empty-cart');
                $('div.rpress-sidebar-main-wrap div.rpress-sidebar-cart-wrap').prepend(orderitems);
              }
              $(document.body)
                .trigger('rpress_added_to_cart', [response]);
              $('ul.rpress-cart')
                .find('.cart-total')
                .html(response.total);
              $('ul.rpress-cart')
                .find('.cart-subtotal')
                .html(response.subtotal);
              if ($('li.rpress-cart-item')
                .length > 0) {
                $('a.rpress-clear-cart')
                  .show();
              } else {
                $('a.rpress-clear-cart')
                  .hide();
              }
              // Target subtotal and total li elements
              var $subtotal = $('.rpress-cart .rpress_subtotal');
              var $tax = $('ul.rpress-cart li.rpress_cart_tax');
              var $total = $('.rpress-cart .rpress_total');

              // Remove any previously added wrapper
              $('div.rpress-sidebar-main-wrap div.rpress-sidebar-cart-wrap').find('.rpress-cart-total-wrap').children().unwrap();

              // Wrap them together only if they exist
              if ($subtotal.length && $total.length) {
                $subtotal.add($tax).add($total).wrapAll('<div class="rpress-cart-total-wrap"></div>');
              }
              $(document.body)
                .trigger('rpress_added_to_cart', [response]);
              MicroModal.close('rpressModal');
              tata.success(window.rp_scripts.success, self.attr('data-title') + window.rp_scripts.added_to_cart, {
                position: "tr"
              })
            }
          }
        })
      }
    }
    if (cartAction == 'update-cart' && validation == '') {

      self.addClass('disable_click');
      var this_form = self.parents('.modal')
        .find('form#fooditem-update-details .food-item-list.active input');
      var itemId = self.attr('data-item-id');
      var itemPrice = self.attr('data-item-price');
      var cartKey = self.attr('data-cart-key');
      var itemQty = self.attr('data-item-qty');
      var FormData = this_form.serializeArray();
      var SpecialInstruction = self.parents('.modal')
        .find('textarea.special-instructions')
        .val();
      var action = 'rpress_update_cart_items';
      var data = {
        action: action,
        fooditem_id: itemId,
        fooditem_qty: itemQty,
        fooditem_cartkey: cartKey,
        special_instruction: SpecialInstruction,
        post_data: FormData,
        security: rp_scripts.update_cart_item_nonce
      };

      if (itemId !== '') {
        $.ajax({
          type: "POST",
          data: data,
          dataType: "json",
          url: rp_scripts.ajaxurl,
          xhrFields: {
            withCredentials: true
          },
          success: function (response) {
            self.removeClass('disable_click');
            self.find('.cart-action-text')
              .text(text);
            if (response) {
              html = response.cart_item;
              $('ul.rpress-cart')
                .find('li.cart_item.empty')
                .remove();
              $('.rpress-cart >li.rpress-cart-item')
                .each(function (index, item) {
                  $(this)
                    .find("[data-cart-item]")
                    .attr('data-cart-item', index);
                  $(this)
                    .attr('data-cart-key', index);
                  $(this)
                    .attr('data-remove-item', index);
                });
              $('ul.rpress-cart')
                .find('li.edited')
                .replaceWith(function () {
                  let obj = $(html);
                  obj.attr('data-cart-key', response.cart_key);
                  obj.find("a.rpress-edit-from-cart")
                    .attr("data-cart-item", response.cart_key);
                  obj.find("a.rpress-edit-from-cart")
                    .attr("data-remove-item", response.cart_key);
                  obj.find("a.rpress_remove_from_cart")
                    .attr("data-cart-item", response.cart_key);
                  obj.find("a.rpress_remove_from_cart")
                    .attr("data-remove-item", response.cart_key);
                  return obj;
                });
              $('ul.rpress-cart')
                .find('.cart-total')
                .html(response.total);
              $('ul.rpress-cart')
                .find('.cart-subtotal')
                .html(response.subtotal);
              $('ul.rpress-cart')
                .find('.cart-tax')
                .html(response.tax);
              rp_update_mobile_cart_summary(response.total, response.cart_quantity);
              $(document.body)
                .trigger('rpress_items_updated', [response]);
              MicroModal.close('rpressModal');
            }
          }
        });
      }
    }
  });
  // Add Service Date and Time
  $('body')
    .on('click', '.rpress-delivery-opt-update', function (e) {
      e.preventDefault();
      var _self = $(this);
      var foodItemId = _self.attr('data-food-id');
      var $updateScope = _self.parents('.rpress-tabs-wrapper')
        .first();
      if (!$updateScope.length) {
        $updateScope = $('#rpressDateTime .rpress-tabs-wrapper')
          .first();
      }

      var serviceType = '';
      var serviceLabel = '';
      var $activeServiceTab = $updateScope.find('.nav-item.active a, .single-service-selected.active')
        .first();
      if (!$activeServiceTab.length) {
        $activeServiceTab = $('.rpress-tabs-wrapper')
          .find('.nav-item.active a, .single-service-selected.active')
          .first();
      }
      if ($activeServiceTab.length) {
        serviceType = ($activeServiceTab.attr('data-service-type') || '')
          .toString()
          .toLowerCase();
        serviceLabel = ($activeServiceTab.text() || '')
          .toString()
          .trim();
        window.localStorage.setItem('serviceLabel', serviceLabel);
      }

      var oldUiUxEnabled = rp_is_old_ui_ux_enabled();
      var hasMultipleServiceTabs = $updateScope.find('#rpressdeliveryTab .single-service-selected').length > 1;
      if (oldUiUxEnabled && hasMultipleServiceTabs && !serviceType) {
        tata.error('Error', 'Please select a service type', { position: "tr" });
        return false;
      }

      var normalizedSelection = rp_apply_service_defaults(
        $updateScope.length ? $updateScope : $(document),
        serviceType,
        true,
        oldUiUxEnabled,
        true
      );

      serviceType = normalizedSelection.serviceType || serviceType || rp_getCookie('service_type') || rp_scripts.default_service || 'delivery';
      var serviceTime = normalizedSelection.serviceTime;
      var serviceTimeText = normalizedSelection.serviceTimeText || serviceTime;
      var serviceDate = normalizedSelection.serviceDate;
      var hasServiceDateSelect = rp_get_active_service_date_select(
        $updateScope.length ? $updateScope : $(document),
        serviceType
      ).length > 0;
      var hasServiceTimeSelect = rp_get_active_service_time_select(
        $updateScope.length ? $updateScope : $(document),
        serviceType
      ).length > 0;
      if (oldUiUxEnabled && hasServiceDateSelect && !serviceDate) {
        tata.error('Error', 'Please select a date', { position: "tr" });
        return false;
      }
      if (oldUiUxEnabled && hasServiceTimeSelect && !rp_is_service_time_hidden(serviceType) && !serviceTime) {
        tata.error('Error', 'Please select a time', { position: "tr" });
        return false;
      }
      var sDate = serviceDate || rp_getCookie('service_date') || '';
      var action = 'rpress_check_service_slot';
      var data = {
        action: action,
        serviceType: serviceType,
        serviceTime: serviceTime,
        service_date: sDate,
        security: rp_scripts.service_type_nonce,
      };
      $.ajax({
        type: "POST",
        data: data,
        dataType: "json",
        url: rpress_scripts.ajaxurl,
        xhrFields: {
          withCredentials: true
        },
        beforeSend: (jqXHR, status) => {
          _self.addClass('rp-loading');
          _self.find('.rp-ajax-toggle-text')
            .addClass('rp-text-visibility');
        },
        complete: (jqXHR, oject) => {
          _self.removeClass('rp-loading');
          _self.find('.rp-ajax-toggle-text')
            .removeClass('rp-text-visibility');
        },
        success: function (response) {
          _self.removeClass('rp-loading');
          _self.find('.rp-ajax-toggle-text')
            .removeClass('rp-text-visibility');
          if (response.status == 'error') {
            _self.text(rpress_scripts.update);
            tata.error(rp_scripts.error, response.error_msg || response.msg || rp_scripts.closed_message);
            return false;
          } else {
            rp_setCookie('service_type', serviceType, rp_scripts.expire_cookie_time);
            if (serviceDate) {
              rp_setCookie('service_date', serviceDate, rp_scripts.expire_cookie_time);
              rp_setCookie('delivery_date', normalizedSelection.serviceDateText || serviceDate, rp_scripts.expire_cookie_time);
            }
            if (serviceTime) {
              rp_setCookie('service_time', serviceTime, rp_scripts.expire_cookie_time);
              rp_setCookie('service_time_text', serviceTimeText, rp_scripts.expire_cookie_time);
            } else {
              rp_setCookie('service_time', '', rp_scripts.expire_cookie_time);
              rp_setCookie('service_time_text', '', rp_scripts.expire_cookie_time);
            }
            $('#rpressModal')
              .removeClass('show-service-options');
            if (foodItemId) {
              $('#rpressModal')
                .addClass('loading');
              $('#rpress_fooditem_' + foodItemId)
                .find('.rpress-add-to-cart')
                .trigger('click');
              MicroModal.close('rpressModal');
            } else {
              if (jQuery('#rpressModal').length) {
                MicroModal.close('rpressModal');
              }
              var selectedDateLabel = normalizedSelection.serviceDateText || rp_getCookie('delivery_date') || serviceDate || '';
              if (serviceType && serviceTime) {
                $('.delivery-wrap .delivery-opts')
                  .html('<span class="delMethod">' + serviceLabel + ',</span> <span class="delTime"> ' + selectedDateLabel + ', ' + serviceTimeText + '</span>');
              } else if (serviceType) {
                $('.delivery-items-options')
                  .find('.delivery-opts')
                  .html('<span class="delMethod">' + serviceLabel + ',</span> <span class="delTime"> ' + selectedDateLabel + '</span>');
              }
            }

            //Trigger checked slot event so that it can be used by theme/plugins
            $(document.body)
              .trigger('rpress_checked_slots', [response]);
            // Refresh checkout fragments without forcing a full page reload loop.
            if (rpress_scripts.is_checkout == '1') {
              $(document.body).trigger('rp-refresh-checkout-service');
            }
          }
        }
      });
    });
  $('body')
    .on('click', '.rpress-editaddress-submit-btn', function (e) {
      e.preventDefault();
      var _self = $(this);
      var foodItemId = _self.attr('data-food-id');
      var $updateScope = _self.parents('.rpress-tabs-wrapper')
        .first();
      if (!$updateScope.length) {
        $updateScope = $('#rpressDateTime .rpress-tabs-wrapper')
          .first();
      }
      var serviceType = '';
      var serviceLabel = '';
      var $activeServiceTab = $updateScope.find('.nav-item.active a, .single-service-selected.active')
        .first();
      if (!$activeServiceTab.length) {
        $activeServiceTab = $('.rpress-tabs-wrapper')
          .find('.nav-item.active a, .single-service-selected.active')
          .first();
      }
      if ($activeServiceTab.length) {
        serviceType = ($activeServiceTab.attr('data-service-type') || '')
          .toString()
          .toLowerCase();
        serviceLabel = ($activeServiceTab.text() || '')
          .toString()
          .trim();
        window.localStorage.setItem('serviceLabel', serviceLabel);
      }

      var oldUiUxEnabled = rp_is_old_ui_ux_enabled();
      var hasMultipleServiceTabs = $updateScope.find('#rpressdeliveryTab .single-service-selected').length > 1;
      if (oldUiUxEnabled && hasMultipleServiceTabs && !serviceType) {
        tata.error('Error', 'Please select a service type', { position: "tr" });
        return false;
      }

      var normalizedSelection = rp_apply_service_defaults(
        $updateScope.length ? $updateScope : $(document),
        serviceType,
        true,
        oldUiUxEnabled,
        true
      );

      serviceType = normalizedSelection.serviceType || serviceType || rp_getCookie('service_type') || rp_scripts.default_service || 'delivery';
      var serviceTime = normalizedSelection.serviceTime;
      var serviceTimeText = normalizedSelection.serviceTimeText || serviceTime;
      var serviceDate = normalizedSelection.serviceDate;
      var hasServiceDateSelect = rp_get_active_service_date_select(
        $updateScope.length ? $updateScope : $(document),
        serviceType
      ).length > 0;
      var hasServiceTimeSelect = rp_get_active_service_time_select(
        $updateScope.length ? $updateScope : $(document),
        serviceType
      ).length > 0;
      if (oldUiUxEnabled && hasServiceDateSelect && !serviceDate) {
        tata.error('Error', 'Please select a date', { position: "tr" });
        return false;
      }
      if (oldUiUxEnabled && hasServiceTimeSelect && !rp_is_service_time_hidden(serviceType) && !serviceTime) {
        tata.error('Error', 'Please select a time', { position: "tr" });
        return false;
      }
      var sDate = serviceDate || rp_getCookie('service_date') || '';
      var action = 'rpress_check_service_slot';
      var data = {
        action: action,
        serviceType: serviceType,
        serviceTime: serviceTime,
        service_date: sDate,
        security: rp_scripts.service_type_nonce,
      };
      $.ajax({
        type: "POST",
        data: data,
        dataType: "json",
        url: rpress_scripts.ajaxurl,
        xhrFields: {
          withCredentials: true
        },
        beforeSend: (jqXHR, status) => {
          _self.addClass('rp-loading');
          _self.find('.rp-ajax-toggle-text')
            .addClass('rp-text-visibility');
        },
        complete: (jqXHR, oject) => {
          _self.removeClass('rp-loading');
          _self.find('.rp-ajax-toggle-text')
            .removeClass('rp-text-visibility');
        },
        success: function (response) {
          _self.removeClass('rp-loading');
          _self.find('.rp-ajax-toggle-text')
            .removeClass('rp-text-visibility');
          if (response.status == 'error') {
            _self.text(rpress_scripts.update);
            tata.error(rp_scripts.error, response.error_msg || response.msg || rp_scripts.closed_message);
            return false;
          } else {
            rp_setCookie('service_type', serviceType, rp_scripts.expire_cookie_time);
            if (serviceDate) {
              rp_setCookie('service_date', serviceDate, rp_scripts.expire_cookie_time);
              rp_setCookie('delivery_date', normalizedSelection.serviceDateText || serviceDate, rp_scripts.expire_cookie_time);
            }
            if (serviceTime) {
              rp_setCookie('service_time', serviceTime, rp_scripts.expire_cookie_time);
              rp_setCookie('service_time_text', serviceTimeText || serviceTime, rp_scripts.expire_cookie_time);
            } else {
              rp_setCookie('service_time', '', rp_scripts.expire_cookie_time);
              rp_setCookie('service_time_text', '', rp_scripts.expire_cookie_time);
            }
            $('#rpressModal')
              .removeClass('show-service-options');
            if (foodItemId) {
              $('#rpressModal')
                .addClass('loading');
              $('#rpress_fooditem_' + foodItemId)
                .find('.rpress-add-to-cart')
                .trigger('click');
              MicroModal.close('rpressModal');
            } else {
              MicroModal.close('rpressModal');
              var selectedDateLabel = normalizedSelection.serviceDateText || rp_getCookie('delivery_date') || serviceDate || '';
              if (serviceType && serviceTime) {
                $('.delivery-wrap .delivery-opts')
                  .html('<span class="delMethod">' + serviceLabel + ',</span> <span class="delTime"> ' + selectedDateLabel + ', ' + serviceTimeText + '</span>');
              } else if (serviceType) {
                $('.delivery-items-options')
                  .find('.delivery-opts')
                  .html('<span class="delMethod">' + serviceLabel + ',</span> <span class="delTime"> ' + selectedDateLabel + '</span>');
              }
            }

            //Trigger checked slot event so that it can be used by theme/plugins
            $(document.body)
              .trigger('rpress_checked_slots', [response]);
            // Refresh checkout fragments without forcing a full page reload loop.
            if (rpress_scripts.is_checkout == '1') {
              $(document.body).trigger('rp-refresh-checkout-service');
            }
          }

          // Close the modal
          MicroModal.close('rpressDateTime');
        }
      });
    });
  // Open modal when button is clicked
  $(document).on('click', '#editDateTime', function (e) {
    e.preventDefault();
    var self = $(this);

    var openLegacyServiceOptionsModal = function () {
      var $serviceChange = $('.delivery-change:visible').first();
      if (!$serviceChange.length) {
        $serviceChange = $('.delivery-change').first();
      }

      if ($serviceChange.length) {
        $serviceChange.trigger('click');
        return true;
      }

      if (!$('#rpressModal').length || !rp_scripts || !rp_scripts.ajaxurl || !rp_scripts.service_type_nonce) {
        return false;
      }

      $('#rpressModal').addClass('show-service-options');
      $.ajax({
        type: "POST",
        data: {
          action: 'rpress_show_delivery_options',
          security: rp_scripts.service_type_nonce
        },
        dataType: "json",
        url: rp_scripts.ajaxurl,
        success: function (response) {
          if (!response || !response.data) {
            return;
          }
          $('#rpressModal .modal-title').html(response.data.html_title || '');
          $('#rpressModal .modal-body').html(response.data.html || '');
          if (typeof window.rp_prepare_old_ui_modal_selection === 'function') {
            window.rp_prepare_old_ui_modal_selection($('#rpressModal .modal-body'));
          }
          MicroModal.show('rpressModal', {
            disableScroll: true
          });
          $(document.body).trigger('opened_service_options', [response.data]);
        }
      });

      return true;
    };

    // Old UI/UX uses the legacy popup flow.
    if (rp_is_old_ui_ux_enabled()) {
      if (openLegacyServiceOptionsModal()) {
        return;
      }
    }

    var $dateTimeModal = $('#rpressDateTime');
    var hasDateTimeMarkup = $dateTimeModal.length &&
      $dateTimeModal.find('.modal__overlay').length > 0 &&
      $dateTimeModal.find('.modal__container').length > 0;

    if (!hasDateTimeMarkup) {
      if (openLegacyServiceOptionsModal()) {
        return;
      }
    }

    var serviceType = rp_getCookie('service_type') || rp_scripts.default_service || 'delivery';
    var shouldPersistDefaults = !rp_is_old_ui_ux_enabled();
    if (shouldPersistDefaults) {
      rp_setCookie('service_type', serviceType, rp_scripts.expire_cookie_time);
    }
    rp_apply_service_defaults(
      $('#rpressDateTime-content'),
      serviceType,
      shouldPersistDefaults,
      rp_is_old_ui_ux_enabled()
    );
    if (typeof window.rp_prepare_old_ui_modal_selection === 'function') {
      window.rp_prepare_old_ui_modal_selection($('#rpressDateTime-content'));
    }

    $('.rpress-mobile-cart-icons').hide();

    MicroModal.show('rpressDateTime', {
      disableScroll: true
    });

  });
  $('body').on('click', '.rpress-editaddress-submit-btn', function (e) {
    e.preventDefault();

    var $modal = $('#rpressDateTime-content');
    if (!$modal.length) {
      $modal = $('#rpressDateTime');
    }
    var activeServiceType = rp_getCookie('service_type') || rp_scripts.default_service || 'delivery';
    var selection = rp_apply_service_defaults($modal.length ? $modal : $(document), activeServiceType, true, false, true);
    var selectedDateText = (selection.serviceDateText || rp_getCookie('delivery_date') || '')
      .toString()
      .trim();
    var selectedTimeText = (selection.serviceTimeText || selection.serviceTime || rp_getCookie('service_time_text') || '')
      .toString()
      .trim();

    if (selectedDateText) {
      $('#deliveryDate').text(selectedDateText);
    }

    if (selectedTimeText) {
      $('#deliveryTime').text(selectedTimeText);
    }

    $('.rpress-mobile-cart-icons').show();
  });
  // Update Service Date and Time
  $(document).on('click', '.delivery-change', function (e) {
    e.preventDefault();
    var self = $(this);
    var action = 'rpress_show_delivery_options';
    var ServiceType = rp_getCookie('service_type');
    var ServiceTime = rp_getCookie('service_time');
    var text = self.text();
    var data = {
      action: action,
      security: rp_scripts.service_type_nonce
    }
    $('#rpressModal').addClass('show-service-options');
    $.ajax({
      type: "POST",
      data: data,
      dataType: "json",
      url: rp_scripts.ajaxurl,
      beforeSend: (jqXHR, obj) => {
        self.addClass('rp-loading');
        self.find('.rp-ajax-toggle-text')
          .addClass('rp-text-visibility')
      },
      complete: (jqXHR, obj) => {
        self.removeClass('rp-loading');
        self.find('.rp-ajax-toggle-text')
          .removeClass('rp-text-visibility')
      },
      success: function (response) {
        // self.text(text);
        $('#rpressModal .modal-title')
          .html(response.data.html_title);
        $('#rpressModal .modal-body')
          .html(response.data.html);
        if (typeof window.rp_prepare_old_ui_modal_selection === 'function') {
          window.rp_prepare_old_ui_modal_selection($('#rpressModal .modal-body'));
        }
        MicroModal.show('rpressModal', {
          disableScroll: true
        });
        if ($('.rpress-tabs-wrapper')
          .length) {
          if (ServiceTime !== '') {
            $('.rpress-delivery-wrap')
              .find('select#rpress-' + ServiceType + '-hours')
              .val(ServiceTime);
          }
          $('.rpress-delivery-wrap')
            .find('a#nav-' + ServiceType + '-tab')
            .trigger('click');
        }
        // Trigger event so themes can refresh other areas.
        $(document.body).trigger('opened_service_options', [response.data]);
      }
    })
  });
  // Remove Item from Cart
  $('.rpress-cart')
    .on('click', '.rpress-remove-from-cart', function (event) {
      if ($('.rpress-remove-from-cart')
        .length == 1 && !confirm(rp_scripts.confirm_empty_cart)) {
        return false;
      }
      var $this = $(this),
        item = $this.data('cart-item'),
        action = $this.data('action'),
        id = $this.data('fooditem-id'),
        security = rp_scripts.edit_cart_fooditem_nonce,
        data = {
          action: action,
          cart_item: item,
          security: security
        };
      $.ajax({
        type: "POST",
        data: data,
        dataType: "json",
        url: rpress_scripts.ajaxurl,
        xhrFields: {
          withCredentials: true
        },
        success: function (response) {
          if (response.removed) {
            // Remove the $this cart item
            $('.rpress-cart .rpress-cart-item')
              .each(function () {
                $(this)
                  .find("[data-cart-item='" + item + "']")
                  .parents('.rpress-cart-item')
                  .remove();
              });
            // Check to see if the purchase form(s) for this fooditem is present on this page
            if ($('[id^=rpress_purchase_' + id + ']')
              .length) {
              $('[id^=rpress_purchase_' + id + '] .rpress_go_to_checkout')
                .hide();
              $('[id^=rpress_purchase_' + id + '] a.rpress-add-to-cart')
                .show()
                .removeAttr('data-rpress-loading');
              if (rpress_scripts.quantities_enabled == '1') {
                $('[id^=rpress_purchase_' + id + '] .rpress_fooditem_quantity_wrapper')
                  .show();
              }
            }
            rp_update_mobile_cart_summary(response.total, response.cart_quantity);
            $(document.body)
              .trigger('rpress_quantity_updated', [response.cart_quantity]);
            if (rpress_scripts.taxes_enabled) {
              $('.cart_item.rpress_subtotal span')
                .html(response.subtotal);
              $('.cart_item.rpress_cart_tax span')
                .html(response.tax);
            }
            $('.cart_item.rpress_total span.rpress-cart-quantity')
              .html(response.cart_quantity);
            $('.cart_item.rpress_total span.cart-total')
              .html(response.total);
            if (response.cart_quantity == 0) {
              $('li.rpress-cart-meta, .cart_item.rpress_subtotal, .rpress-cart-number-of-items, .cart_item.rpress_checkout, .cart_item.rpress_cart_tax, .cart_item.rpress_total')
                .hide();
              $('.rpress-cart')
                .each(function () {
                  var cart_wrapper = $(this)
                    .parent();
                  if (cart_wrapper) {
                    cart_wrapper.addClass('cart-empty')
                    cart_wrapper.removeClass('cart-not-empty');
                  }
                  $(this)
                    .append('<li class="cart_item empty">' + rpress_scripts.empty_cart_message + '</li>');
                });
            }
            $(document.body)
              .trigger('rpress_cart_item_removed', [response]);
            $('ul.rpress-cart > li.rpress-cart-item')
              .each(function (index, item) {
                $(this)
                  .find("[data-cart-item]")
                  .attr('data-cart-item', index);
                $(this)
                  .find("[data-remove-item]")
                  .attr('data-remove-item', index);
                $(this)
                  .attr('data-cart-key', index);
              });
            // check if no item in cart left
            if ($('li.rpress-cart-item')
              .length == 0) {
              $('div.rpress.item-order').hide();
              $('li.rpress-cart-meta')
                .hide();
              $('li.delivery-items-options')
                .hide();
              $('a.rpress-clear-cart')
                .hide();
            }
          }
        }
      });
      return false;
    });
  // Clear All Fooditems from Cart
  $(document)
    .on('click', 'a.rpress-clear-cart', function (e) {
      e.preventDefault();
      if (confirm(rp_scripts.confirm_empty_cart)) {
        var self = $(this);
        var old_text = self.html();
        var action = 'rpress_clear_cart';
        var data = {
          security: rp_scripts.clear_cart_nonce,
          action: action
        }
        $.ajax({
          type: "POST",
          data: data,
          dataType: "json",
          url: rp_scripts.ajaxurl,
          xhrFields: {
            withCredentials: true
          },
          beforeSend: (jqXHR, object) => {
            self.addClass('rp-loading')
            self.find('.rp-ajax-toggle-text')
              .addClass('rp-text-visibility')
          },
          complete: (jqXHR, object) => {
            self.removeClass('rp-loading')
            self.find('.rp-ajax-toggle-text')
              .removeClass('rp-text-visibility')
          },
          success: function (response) {
            if (response.status == 'success') {
              rp_update_mobile_cart_summary(`${rp_scripts.currency_sign}0.00`, 0);
              $(document.body)
                .trigger('rpress_quantity_updated', [0]);
              $(".rpress-sidebar-main-wrap")
                .css("left", "100%");
              $('ul.rpress-cart')
                .find('li.cart_item.rpress_total')
                .css('display', 'none');
              $('ul.rpress-cart')
                .find('li.cart_item.rpress_checkout')
                .css('display', 'none');
              $('ul.rpress-cart')
                .find('li.rpress-cart-item')
                .remove();
              $('ul.rpress-cart')
                .find('li.cart_item.empty')
                .remove();
              $('ul.rpress-cart')
                .find('li.rpress_subtotal')
                .remove();
              $('ul.rpress-cart')
                .find('li.rpress_cart_tax')
                .remove();
              $('ul.rpress-cart')
                .find('li.rpress-delivery-fee')
                .remove();
              $('ul.rpress-cart')
                .append(response.response);
              $('.rpress-cart-number-of-items')
                .css('display', 'none');
              $('.delivery-items-options')
                .css('display', 'none');
              self.hide();
              tata.success(window.rp_scripts.success, window.rp_scripts.success_empty_cart, {
                position: "tr"
              })
            }
          }
        });
      }
    });
  // Proceed to Checkout
  $(document)
    .on('click', '.cart_item.rpress_checkout a', function (e) {
      e.preventDefault();
      rp_sync_service_selection_cookies($('.rpress-delivery-wrap .rpress-tabs-wrapper:visible').first());
      var CheckoutUrl = rp_scripts.checkout_page;
      var _self = $(this);
      var OrderText = _self.text();
      var action = 'rpress_proceed_checkout';
      var data = {
        action: action,
        security: rp_scripts.proceed_checkout_nonce,
      }

      $.ajax({
        type: "POST",
        data: data,
        dataType: "json",
        url: rp_scripts.ajaxurl,
        beforeSend: function () {
          _self.addClass('rp-loading');
          _self.children('.rp-ajax-toggle-text')
            .addClass('rp-text-visibility');
        },
        success: function (response) {
          if (response.status == 'error') {
            if (response.error_msg) {
              errorString = response.error_msg;
            }
            tata.error(rp_scripts.error, errorString);
            _self.removeClass('rp-loading');
            _self.children('.rp-ajax-toggle-text')
              .removeClass('rp-text-visibility');
            if (response && response.error_type === "service_time_not_set") {
              $("#editDateTime").trigger('click');
              return;
            }
          } else {
            window.location.replace(rp_scripts.checkout_page)
            return;
          }
        }
      })
    });
  $(document)
    .on('click', 'span.special-instructions-link', function (e) {
      e.preventDefault();
      $(this)
        .parent('div')
        .find('.special-instructions')
        .toggleClass('hide');
    });
  $('body')
    .on('click', '.rpress-filter-toggle', function () {
      $('div.rpress-filter-wrapper')
        .toggleClass('active');
    });
  $(".rp-cart-left-wrap")
    .click(function () {
      $(".rpress-sidebar-main-wrap")
        .css("left", "0%");
    });
  //Triggering cart
  $(".rp-cart-right-wrap")
    .click(function () {
      $(".cart_item.rpress_checkout a")
        .trigger('click');
    });
  $(".close-cart-ic")
    .click(function () {
      $(".rpress-sidebar-main-wrap")
        .css("left", "100%");
    });
  // Show Image on Modal
  $(".rpress-thumbnail-popup")
    .fancybox({
      openEffect: 'elastic',
      closeEffect: 'elastic',
      helpers: {
        title: {
          type: 'inside'
        }
      }
    });
  if ($(window)
    .width() > 991) {
    var totalHeight = $('header:eq(0)')
      .length > 0 ? $('header:eq(0)')
        .height() + 30 : 120;
    if ($(".sticky-sidebar")
      .length != '') {
      $('.sticky-sidebar')
        .rpressStickySidebar({
          additionalMarginTop: totalHeight
        });
    }
  } else {
    var totalHeight = $('header:eq(0)')
      .length > 0 ? $('header:eq(0)')
        .height() + 30 : 70;
  }
});
/* Make Addons and Variables clickable for Live Price */
jQuery(document)
  .ajaxComplete(function () {
    jQuery('#fooditem-details .food-item-list input')
      .on('click', function (event) {
        update_modal_live_price('fooditem-details');
      });
    jQuery('#fooditem-update-details .food-item-list input')
      .on('click', function (event) {
        update_modal_live_price('fooditem-update-details');
      });
  });
/* RestroPress Sticky Sidebar - Imported from rp-sticky-sidebar.js */
function rp_get_dynamic_scroll_offset() {
  var isOrderOnlineView = jQuery('body').hasClass('order-online') || jQuery('.order-online .rpress-section').length > 0;
  var overlayBottom = 0;
  var selectors = ['#wpadminbar'];
  var basePadding = 12;
  var viewportWidth = window.innerWidth || jQuery(window).width() || 1024;
  var offsetCap = viewportWidth <= 1024 ? 96 : 180;

  if (!isOrderOnlineView) {
    selectors.push('header:eq(0)');
  }

  selectors = selectors.concat([
    '.order-online .rpress-section .make-me-sticky:visible',
    '.desktop-scroll-menu .make-me-sticky:visible',
    '.mobile-scroll-menu .make-me-sticky:visible',
    '.rpress-mobile-menu-wrap .make-me-sticky:visible'
  ]);

  selectors.forEach(function (selector) {
    jQuery(selector).each(function () {
      var $element = jQuery(this);
      if (!$element.is(':visible')) {
        return;
      }

      var position = ($element.css('position') || '').toLowerCase();
      if (position !== 'fixed' && position !== 'sticky') {
        return;
      }

      var rect = this.getBoundingClientRect ? this.getBoundingClientRect() : null;
      if (!rect || rect.height <= 0 || rect.bottom <= 0) {
        return;
      }

      // Count only bars occupying the top viewport band.
      if (rect.top > 140) {
        return;
      }

      overlayBottom = Math.max(overlayBottom, rect.bottom);
    });
  });

  return Math.max(0, Math.min(offsetCap, Math.round(overlayBottom + basePadding)));
}

function rp_resolve_category_target($trigger, preferredSelector) {
  if (!$trigger || !$trigger.length) {
    return jQuery();
  }

  var selector = '';
  var dataId = parseInt($trigger.data('id'), 10);
  if (!isNaN(dataId) && dataId > 0) {
    selector = '#menu-category-' + dataId;
  } else if (typeof preferredSelector === 'string' && preferredSelector.length > 0) {
    selector = preferredSelector;
  } else {
    selector = $trigger.attr('href') || '';
  }

  if (!selector) {
    return jQuery();
  }

  if (selector.charAt(0) !== '#') {
    selector = '#' + selector;
  }

  var $scope = $trigger.closest('.rpress-section');
  var $target = jQuery();

  if ($scope.length) {
    $target = $scope.find(selector + '.rpress-element-title').first();
    if (!$target.length) {
      $target = $scope.find(selector).first();
    }
  }

  if (!$target.length) {
    $target = jQuery(selector + '.rpress-element-title:visible').first();
  }
  if (!$target.length) {
    $target = jQuery(selector + '.rpress-element-title').first();
  }
  if (!$target.length) {
    $target = jQuery(selector + ':visible').first();
  }
  if (!$target.length) {
    $target = jQuery(selector).first();
  }

  // Fallback for theme overrides that still use slug anchors like "#beer".
  if (!$target.length && selector.charAt(0) === '#') {
    var slug = selector.substring(1);
    if (slug && slug.indexOf('menu-category-') !== 0) {
      if ($scope.length) {
        $target = $scope.find('.menu-category-wrap[data-cat-id="' + slug + '"]').first().closest('.rpress-element-title');
      }
      if (!$target.length) {
        $target = jQuery('.menu-category-wrap[data-cat-id="' + slug + '"]:visible').first().closest('.rpress-element-title');
      }
      if (!$target.length) {
        $target = jQuery('.menu-category-wrap[data-cat-id="' + slug + '"]').first().closest('.rpress-element-title');
      }
    }
  }

  var normalizeCategoryLabel = function (text) {
    return (text || '')
      .replace(/\(\s*\d+\s*\)/g, '')
      .replace(/\s+\d+\s*$/, '')
      .replace(/\s+/g, ' ')
      .trim()
      .toLowerCase();
  };

  var getLinkLabel = function () {
    if (!$trigger || !$trigger.length) {
      return '';
    }
    var $clone = $trigger.clone();
    $clone.find('span').remove();
    return normalizeCategoryLabel($clone.text());
  };

  var getHeadingLabel = function ($heading) {
    if (!$heading || !$heading.length) {
      return '';
    }
    var $title = $heading.find('h5.rpress-cat').first();
    return normalizeCategoryLabel($title.length ? $title.text() : $heading.text());
  };

  // Guard against mismatched link->href mappings by validating label vs heading.
  if ($target.length) {
    var linkLabel = getLinkLabel();
    var targetLabel = getHeadingLabel($target);
    var mismatch = (
      linkLabel &&
      targetLabel &&
      targetLabel.indexOf(linkLabel) === -1 &&
      linkLabel.indexOf(targetLabel) === -1
    );

    if (mismatch) {
      var $candidateHeadings = $scope.length
        ? $scope.find('.rpress-element-title')
        : jQuery('.rpress-element-title');

      var $matchingByLabel = $candidateHeadings.filter(function () {
        var label = getHeadingLabel(jQuery(this));
        return label === linkLabel || label.indexOf(linkLabel) !== -1 || linkLabel.indexOf(label) !== -1;
      }).first();

      if ($matchingByLabel.length) {
        $target = $matchingByLabel;
      } else {
        var $siblings = $trigger.closest('ul').find('a');
        var linkIndex = $siblings.index($trigger);
        if (linkIndex >= 0 && linkIndex < $candidateHeadings.length) {
          $target = $candidateHeadings.eq(linkIndex);
        }
      }
    }
  }

  return $target;
}

function rp_scroll_to_category_target($target) {
  if (!$target || !$target.length) {
    return;
  }

  var $page = jQuery('html, body');
  var initialOffset = rp_get_dynamic_scroll_offset();
  var initialDestination = Math.max(0, $target.offset().top - initialOffset);

  $page.stop(true).animate({
    scrollTop: initialDestination
  }, 420, function () {
    var raf = window.requestAnimationFrame || function (cb) {
      window.setTimeout(cb, 16);
    };

    raf(function () {
      if (!$target.length) {
        return;
      }

      var liveOffset = rp_get_dynamic_scroll_offset();
      var rect = $target[0].getBoundingClientRect();
      var delta = rect.top - liveOffset;

      if (Math.abs(delta) > 3) {
        var correctedDestination = Math.max(0, jQuery(window).scrollTop() + delta);
        $page.stop(true).animate({
          scrollTop: correctedDestination
        }, 160);
      }
    });
  });
}

function rp_close_action_menu_if_open() {
  var container = document.querySelector('.container-actionmenu');
  var burger = document.getElementById('actionburger');
  var menu = document.querySelector('.actionmenu');

  if (!container || !burger || !menu) {
    return;
  }

  if (!burger.classList.contains('is-expanded')) {
    return;
  }

  burger.classList.remove('is-expanded');
  menu.classList.remove('slides-up');
  menu.classList.add('slides-down');

  var icon = burger.querySelector('i');
  var textNode = burger.querySelector('.menu-text');
  var menuText = burger.getAttribute('data-text-menu') || 'Menu';
  var menuIcon = burger.getAttribute('data-icon-menu') || 'fa fa-cutlery';

  if (icon) {
    icon.className = menuIcon;
  }
  if (textNode) {
    textNode.textContent = menuText;
  }
}

jQuery(function ($) {
  if ($(window).width() > 991) {
    if ($(".sticky-sidebar").length > 0) {
      $('.sticky-sidebar').rpressStickySidebar({
        additionalMarginTop: rp_get_dynamic_scroll_offset()
      });
    }
  }
  // Category Navigation
  $('body')
    .on('click', '.rpress-category-link', function (e) {
      e.preventDefault();
      var $target = rp_resolve_category_target($(this));
      if (!$target.length) {
        return;
      }
      rp_scroll_to_category_target($target);
    });
  $('.rpress-category-item')
    .on('click', function () {
      $('.rpress-category-item')
        .removeClass('current');
      $(this)
        .addClass('current');
    });
});
jQuery(function ($) {
  // Dedicated handler for bottom mobile action-menu category links.
  // This ensures the action-menu path always scrolls via controlled offset logic.
  $('body')
    .off('click.rpActionMenuCategory', '.container-actionmenu .actionmenu a[href^="#menu-category-"]')
    .on('click.rpActionMenuCategory', '.container-actionmenu .actionmenu a[href^="#menu-category-"]', function (e) {
      e.preventDefault();
      e.stopPropagation();
      e.stopImmediatePropagation();

      var $link = $(this);
      var $target = rp_resolve_category_target($link, $link.attr('href') || '');
      var selectedHref = $link.attr('href') || '';
      var selectedTermId = selectedHref.replace('#menu-category-', '');

      // Keep all category nav UIs in sync immediately on click.
      $('.container-actionmenu .actionmenu .cd-dropdown-content a').removeClass('mnuactive');
      $link.addClass('mnuactive');

      if (selectedTermId) {
        $('.pn-ProductNav_Link').removeAttr('aria-selected');
        $('.pn-ProductNav_Link[href="#menu-category-' + selectedTermId + '"]')
          .attr('aria-selected', 'true')
          .addClass('mnuactive');

        $('.rpress-category-lists .rpress-category-link').removeClass('active');
        $('.rpress-category-lists .rpress-category-link').parent().removeClass('current');
        var $listMatch = $('.rpress-category-lists .rpress-category-link[data-id="' + selectedTermId + '"]').first();
        if ($listMatch.length) {
          $listMatch.addClass('active');
          $listMatch.parent().addClass('current');
        }
      }

      rp_close_action_menu_if_open();

      if ($target.length) {
        setTimeout(function () {
          rp_scroll_to_category_target($target);
        }, 60);
      }

      return false;
    });

  // Smooth scroll for category dropdown and horizontal nav
  $('body').on('click', '.cd-dropdown-content a, .pn-ProductNav_Link', function (e) {
    e.preventDefault();
    e.stopPropagation();

    const $link = $(this);
    const targetSelector = $link.attr('href') || '';
    const $target = rp_resolve_category_target($link, targetSelector);
    const isActionMenuLink = $link.closest('.container-actionmenu').length > 0;
    const isCdDropdownLink = $link.closest('.cd-dropdown').length > 0;
    const selectedTermId = targetSelector.replace('#menu-category-', '');

    if (isActionMenuLink) {
      rp_close_action_menu_if_open();
    }

    if (isCdDropdownLink) {
      $('.cd-dropdown').removeClass('dropdown-is-active');
      $('.cd-dropdown-trigger').removeClass('dropdown-is-active');
      $('body').removeClass('cd-overlay-open');
      $('.rpress-cat-overlay').remove();
      $('.rpress-mobile-cart-icons').show();
    }

    if ($target.length) {
      setTimeout(function () {
        rp_scroll_to_category_target($target);
      }, (isActionMenuLink || isCdDropdownLink) ? 80 : 0);
    }

    if (selectedTermId) {
      $('.rpress-category-lists .rpress-category-link').removeClass('active');
      $('.rpress-category-lists .rpress-category-link').parent().removeClass('current');
      var $listLink = $('.rpress-category-lists .rpress-category-link[data-id="' + selectedTermId + '"]').first();
      if ($listLink.length) {
        $listLink.addClass('active');
        $listLink.parent().addClass('current');
      }
    }

    // Set aria-selected on horizontal nav
    if ($link.hasClass('pn-ProductNav_Link')) {
      $('.pn-ProductNav_Link').removeAttr('aria-selected');
      $link.attr('aria-selected', 'true');
    }

    // Highlight dropdown item
    if ($link.closest('.cd-dropdown-content').length) {
      $('.cd-dropdown-content li a').removeClass('mnuactive');
      $link.addClass('mnuactive');
    }
  });

});

/* Cart Quantity Changer - Imported from cart-quantity-changer.js */
jQuery(function ($) {
  //quantity Minus
  var liveQtyVal;
  jQuery(document)
    .on('click', '.qtyminus', function (e) {
      // Stop acting like a button
      e.preventDefault();
      // Get the field name
      fieldName = 'quantity';
      // Get its current value
      var currentVal = parseInt(jQuery('input[name=' + fieldName + ']')
        .val());
      // If it isn't undefined or its greater than 0
      if (!isNaN(currentVal) && currentVal > 1) {
        // Decrement one only if value is > 1
        jQuery('input[name=' + fieldName + ']')
          .val(currentVal - 1);
        jQuery('.qtyplus')
          .removeAttr('style');
        liveQtyVal = currentVal - 1;
      } else {
        // Otherwise put a 0 there
        jQuery('input[name=' + fieldName + ']')
          .val(1);
        jQuery('.qtyminus')
          .css('color', '#aaa')
          .css('cursor', 'not-allowed');
        liveQtyVal = 1;
      }
      console.log(liveQtyVal);

      jQuery(this)
        .parents('footer.modal-footer')
        .find('a.submit-fooditem-button')
        .attr('data-item-qty', liveQtyVal);
      jQuery(this)
        .parents('footer.modal__footer')
        .find('a.submit-fooditem-button')
        .attr('data-item-qty', liveQtyVal);
      // Updating live price as per quantity
      var total_price = parseFloat(jQuery('#rpressModal .cart-item-price')
        .attr('data-current'));
      var new_price = parseFloat(total_price * liveQtyVal);
      if (rp_scripts.decimal_separator == ',') {
        new_price_v = new_price.toFixed(2)
          .split('.')
          .join(',');
      } else {
        new_price_v = new_price.toFixed(2);
      }
      jQuery('#rpressModal .cart-item-price')
        .html(rp_scripts.currency_sign + new_price_v);
    });
  jQuery(document)
    .on('click', '.qtyplus', function (e) {
      // Stop acting like a button
      e.preventDefault();
      // Get the field name
      fieldName = 'quantity';
      // Get its current value
      var currentVal = parseInt(jQuery('input[name=' + fieldName + ']').val());
      // If is not undefined
      if (!isNaN(currentVal)) {
        jQuery('input[name=' + fieldName + ']')
          .val(currentVal + 1);
        jQuery('.qtyminus')
          .removeAttr('style');
        liveQtyVal = currentVal + 1;
      } else {
        // Otherwise put a 0 there
        jQuery('input[name=' + fieldName + ']')
          .val(1);
        liveQtyVal = 1;
      }
      jQuery(this)
        .parents('footer.modal__footer')
        .find('a.submit-fooditem-button')
        .attr('data-item-qty', liveQtyVal);
      jQuery(this)
        .parents('footer.modal__footer')
        .find('a.submit-fooditem-button')
        .attr('data-item-qty', liveQtyVal);
      // Updating live price as per quantity
      var total_price = parseFloat(jQuery('#rpressModal .cart-item-price')
        .attr('data-current'));
      var new_price = parseFloat(total_price * liveQtyVal);
      if (rp_scripts.decimal_separator == ',') {
        new_price_v = new_price.toFixed(2)
          .split('.')
          .join(',');
      } else {
        new_price_v = new_price.toFixed(2);
      }
      jQuery('#rpressModal .cart-item-price')
        .html(rp_scripts.currency_sign + new_price_v);
    });
  jQuery(document)
    .on("input", ".qty", function () {
      this.value = this.value.replace(/\D/g, '');
    });
  jQuery(document)
    .on('keyup', '.qty', function (e) {
      // Updating live price as per quantity
      liveQtyVal = jQuery(this)
        .val();
      var total_price = parseFloat(jQuery('#rpressModal .cart-item-price')
        .attr('data-current'));
      var new_price = parseFloat(total_price * liveQtyVal);
      if (rp_scripts.decimal_separator == ',') {
        new_price_v = new_price.toFixed(2)
          .split('.')
          .join(',');
      } else {
        new_price_v = new_price.toFixed(2);
      }
      jQuery('#rpressModal .cart-item-price')
        .html(rp_scripts.currency_sign + new_price_v);
    });
});
jQuery(function ($) {
  // Detect whether list or grid is currently visible
  function getCurrentViewContainer() {
    if ($('.rpress_fooditems_list:visible').length) {
      return $('.rpress_fooditems_list');
    } else if ($('.rpress_fooditems_grid:visible').length) {
      return $('.rpress_fooditems_grid');
    } else {
      return $('.rpress_fooditems_list'); // default fallback
    }
  }

  // Step 1: Add searchable data attribute to all .rpress-title-holder elements (in both views)
  $('.rpress-title-holder').each(function () {
    $(this).attr('data-search-term', $(this).text().toLowerCase());
  });

  // Step 2: Live search
  $('#rpress-food-search').on('keyup', function () {
    var searchTerm = $(this).val().toLowerCase();
    var $viewContainer = getCurrentViewContainer();
    var visibleTermIds = [];

    // Reset states
    $viewContainer.find('.rpress-element-title').removeClass('matched not-matched');

    $viewContainer.find('.rpress_fooditem').each(function () {
      var $foodItem = $(this);
      var $titleHolder = $foodItem.find('.rpress-title-holder');
      var itemText = $titleHolder.data('search-term') || $titleHolder.text().toLowerCase();
      var termId = $foodItem.attr('data-term-id');

      if (searchTerm === '' || itemText.includes(searchTerm)) {
        $foodItem.show();
        visibleTermIds.push(termId);
      } else {
        $foodItem.hide();
      }
    });

    // Show/hide category headings
    $viewContainer.find('.rpress-element-title').each(function () {
      var termId = $(this).data('term-id');
      if (visibleTermIds.includes(termId.toString())) {
        $(this).show().addClass('matched');
      } else {
        $(this).hide().addClass('not-matched');
      }
    });

    // === CATEGORY NAVIGATION HIDE/SHOW ===
    $('.rpress-category-lists .rpress-category-link').each(function () {
      var termId = $(this).data('id');
      if (visibleTermIds.includes(termId.toString())) {
        $(this).parent().show();
      } else {
        $(this).parent().hide();
      }
    });

    // Dropdown menu in grid view
    $('.cd-dropdown-content a[href^="#menu-category-"]').each(function () {
      var termId = $(this).attr('href').replace('#menu-category-', '');
      if (visibleTermIds.includes(termId)) {
        $(this).closest('li').show();
      } else {
        $(this).closest('li').hide();
      }
    });

    // Horizontal nav in grid view
    $('.pn-ProductNav_Contents .pn-ProductNav_Link').each(function () {
      var termId = $(this).attr('href').replace('#menu-category-', '');
      if (visibleTermIds.includes(termId)) {
        $(this).show();
      } else {
        $(this).hide();
      }
    });

  });
});

/* RestroPress active category highlighter */
jQuery(function ($) {
  const rp_category_links = $('.rpress-category-lists .rpress-category-link');
  const rp_category_links_grid = $('#pnProductNavContents .pn-ProductNav_Link');
  if (rp_category_links.length > 0) {
    function rp_apply_list_active_term(termId) {
      if (typeof termId === 'undefined' || termId === null || termId === '') {
        return;
      }
      var normalizedId = String(termId);
      var $matchedLink = rp_category_links.filter(function () {
        return String($(this).data('id') || '') === normalizedId;
      }).first();

      if (!$matchedLink.length) {
        return;
      }

      rp_category_links.removeClass('active');
      $matchedLink.addClass('active');

      rp_category_links.parent().removeClass('current');
      $matchedLink.parent().addClass('current');
    }

    function rp_detect_active_term_from_scroll() {
      var anchorLine = rp_get_dynamic_scroll_offset() + 2;
      var activeTermId = '';
      var firstVisibleTermId = '';

      $('.rpress-element-title[id^="menu-category-"]:visible').each(function () {
        var $heading = $(this);
        var termId = String($heading.data('term-id') || '').trim();
        if (!termId) {
          var fallbackId = String($heading.attr('id') || '').replace('menu-category-', '');
          termId = fallbackId.trim();
        }
        if (!termId) {
          return;
        }

        var top = this.getBoundingClientRect().top;
        if (!firstVisibleTermId && top > -120) {
          firstVisibleTermId = termId;
        }
        if (top <= anchorLine) {
          activeTermId = termId;
        }
      });

      return activeTermId || firstVisibleTermId || '';
    }

    var rp_update_list_active_on_scroll = function () {
      rp_apply_list_active_term(rp_detect_active_term_from_scroll());
    };

    // Immediate visual selection for clicked list categories.
    $('body')
      .off('click.rpListActive', '.rpress-category-lists .rpress-category-link')
      .on('click.rpListActive', '.rpress-category-lists .rpress-category-link', function () {
        rp_apply_list_active_term($(this).data('id'));
      });

    rp_update_list_active_on_scroll();
    window.addEventListener('scroll', rp_update_list_active_on_scroll, { passive: true });
    window.addEventListener('resize', rp_update_list_active_on_scroll);
  }

  if (rp_category_links_grid.length > 0) {
    const header_height = $('header:eq(0)').height();
    const $nav = $('#pnProductNav');          // the actual scroller
    const $navContents = $('#pnProductNavContents');  // inner content
    const $indicator = $('#pnIndicator');
    let current_category = rp_category_links_grid.eq(0).attr('href').substr(1);

    // Make sure navContents is positioned so indicator can be positioned inside it
    if ($navContents.length && $navContents.css('position') === 'static') {
      $navContents.css('position', 'relative');
    }

    // ---- helper: move indicator visually under the link ----
    function moveIndicatorTo($link) {
      if (!$link || !$link.length) return;

      // Use bounding rects so calculation is robust even with transforms / scrolling
      const linkRect = $link[0].getBoundingClientRect();
      const contentsRect = $navContents[0].getBoundingClientRect();

      // left relative to contents' left (visual coordinate)
      const left = Math.round(linkRect.left - contentsRect.left + ($navContents.scrollLeft() || 0));
      const width = Math.round(linkRect.width);

      // Apply width and translateX in px (reliable)
      $indicator.css({
        width: width + 'px',
        transform: 'translateX(' + left + 'px)'
      });

      // Ensure the active link is visible / centered inside the scroller
      scrollActiveIntoView($link);
    }

    // ---- helper: scroll the scroller so the link is visible/centered ----
    function scrollActiveIntoView($link) {
      if (!$link || !$link.length) return;

      // Choose real scroller (outer nav) - fallback to contents if outer missing
      const $scroller = $nav.length ? $nav : $navContents;
      if (!$scroller.length) return;

      const scrollerEl = $scroller[0];
      const maxScroll = scrollerEl.scrollWidth - scrollerEl.clientWidth;

      const linkRect = $link[0].getBoundingClientRect();
      const scrollerRect = scrollerEl.getBoundingClientRect();

      // Current scrollLeft
      const currentScroll = $scroller.scrollLeft();

      // left of link relative to scrollable content coordinates:
      // (element left on screen - scroller left on screen) + currentScroll
      let leftRelativeToScroller = linkRect.left - scrollerRect.left + currentScroll;

      // center the link
      let desired = leftRelativeToScroller - (scrollerEl.clientWidth / 2) + ($link.outerWidth() / 2);

      // clamp
      desired = Math.max(0, Math.min(desired, maxScroll));

      // If the inner contents currently has a transform (arrow animation in progress),
      // animated scrollLeft may behave unexpectedly. In that case use scrollIntoView fallback:
      const contentsTransform = getComputedStyle($navContents[0]).transform;
      if (contentsTransform && contentsTransform !== 'none') {
        // fallback - ask the browser to scroll the nearest scrollable ancestor
        try {
          $link[0].scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' });
          return;
        } catch (e) {
          // if not supported, continue to jQuery animate fallback
        }
      }

      // animate scrollLeft (smooth)
      $scroller.stop().animate({ scrollLeft: desired }, 350);
    }

    // ---- main scanning function (updates current_category + classes) ----
    function RpScrollingCategoriesgrid() {
      // determine current category based on section positions
      rp_category_links_grid.each(function () {
        const section_id = $(this).attr('href').substr(1);
        const section = document.getElementById(section_id);
        if (section && section.getBoundingClientRect().top < header_height + 40) {
          current_category = section_id;
        }
      });

      // Update active link classes/aria
      const $activeLink = rp_category_links_grid
        .removeAttr('aria-selected').removeClass('mnuactive')
        .filter(`[href="#${current_category}"]`)
        .attr('aria-selected', 'true').addClass('mnuactive');

      // Move indicator + ensure visible
      if ($activeLink.length) {
        moveIndicatorTo($activeLink);
      }

      // Sync the dropdown menu
      $(".cd-dropdown-content a")
        .removeClass("mnuactive")
        .filter(`[href="#${current_category}"]`)
        .addClass("mnuactive");
    }

    // Run once on load
    RpScrollingCategoriesgrid();

    // Update on page scroll / resize (throttle-friendly native listeners)
    window.addEventListener('scroll', RpScrollingCategoriesgrid, { passive: true });
    window.addEventListener('resize', RpScrollingCategoriesgrid);

    // Utility to get current section in view (used elsewhere)
    function getCurrentCategoryInView() {
      let scrollTop = $(window).scrollTop();
      let current = null;

      $(".rpress-category-lists .rpress-category-wrap").each(function () {
        if ($(this).offset().top <= scrollTop + 100) {
          current = $(this).attr("id");
        }
      });

      return current;
    }

    // On window scroll (content scroll, not nav scroll) Ã¢â‚¬â€ keep dropdown and indicator in sync
    $(window).on("scroll", function () {
      let current = getCurrentCategoryInView();
      if (!current) return;

      const $active = rp_category_links_grid.filter(`[href="#${current}"]`);
      if ($active.length) {
        moveIndicatorTo($active);

        // Sync dropdown
        const activeHref = $active.attr("href");
        $(".cd-dropdown-content a").removeClass("mnuactive");
        $(`.cd-dropdown-content a[href="${activeHref}"]`).addClass("mnuactive");
      }
    });

    // Nav link click instant feedback
    $(document).on("click", ".pn-ProductNav_Link", function (e) {
      const $this = $(this);
      // Move indicator & scroll into view immediately
      moveIndicatorTo($this);

      // Sync dropdown
      const activeHref = $this.attr("href");
      $(".cd-dropdown-content a").removeClass("mnuactive");
      $(`.cd-dropdown-content a[href="${activeHref}"]`).addClass("mnuactive");
    });

  }

  $(document)
    .ready(function () {
      var getActiveServiceTimeSelect = (typeof window.rp_get_active_service_time_select === 'function')
        ? window.rp_get_active_service_time_select
        : function ($scope, preferredServiceType) {
          var $root = ($scope && $scope.length) ? $scope : $(document);
          var serviceType = (preferredServiceType || '').toLowerCase();
          var $select = $();

          if (serviceType) {
            $select = $root.find('.delivery-settings-wrapper#nav-' + serviceType + ' .rpress-hrs').first();
            if ($select.length) {
              return $select;
            }
          }

          $select = $root.find('.delivery-settings-wrapper.active .rpress-hrs').first();
          if ($select.length) {
            return $select;
          }

          return $root.find('#rpress-delivery-hours, .rpress-hrs').first();
        };

      var restoreServiceTimeSelect = (typeof window.rp_restore_service_time_select === 'function')
        ? window.rp_restore_service_time_select
        : function ($select, serviceTime) {
          if (!$select || !$select.length) {
            return '';
          }

          var requestedTime = (serviceTime || '').trim();
          var selectedValue = '';

          if (requestedTime && $select.find('option[value="' + requestedTime + '"]').length) {
            selectedValue = requestedTime;
          } else if (requestedTime) {
            var $matchingOption = $select.find('option').filter(function () {
              return $(this).text().trim() === requestedTime;
            }).first();
            if ($matchingOption.length) {
              selectedValue = $matchingOption.val();
            }
          }

          if (!selectedValue) {
            var $firstSelectableOption = $select.find('option').filter(function () {
              var optionValue = ($(this).val() || '').toString().trim();
              return optionValue !== '' && !$(this).prop('disabled');
            }).first();
            if (!$firstSelectableOption.length) {
              $firstSelectableOption = $select.find('option').first();
            }
            selectedValue = $firstSelectableOption.val() || '';
          }

          if (selectedValue) {
            $select.val(selectedValue);
          }

          return selectedValue;
        };
      var applyServiceDefaults = (typeof window.rp_apply_service_defaults === 'function')
        ? window.rp_apply_service_defaults
        : null;

      var checkoutUpdateInFlight = false;
      var lastCheckoutServiceType = '';
      var checkoutServiceTabSelector = '.rp-checkout-service-option .single-service-selected, #rpress_checkout_order_details .rpress-delivery-options .single-service-selected';
      var checkoutServiceTimeSelector = '.rp-checkout-service-option .rpress-hrs, #rpress_checkout_order_details .rpress-delivery-options .rpress-hrs';
      var getCheckoutServiceScope = function () {
        var $scope = $('.rp-checkout-service-option').first();
        if ($scope.length) {
          return $scope;
        }

        $scope = $('#rpress_checkout_order_details .rpress-delivery-options .rpress-tabs-wrapper').first();
        if ($scope.length) {
          return $scope;
        }

        return $('#rpress_checkout_order_details .rpress-tabs-wrapper').first();
      };
      var findCheckoutServiceTab = function (serviceType) {
        serviceType = (serviceType || '').toLowerCase();
        if (!serviceType) {
          return $();
        }

        var $scope = getCheckoutServiceScope();
        if (!$scope.length) {
          return $();
        }

        return $scope.find('#rpressdeliveryTab .single-service-selected[data-service-type="' + serviceType + '"]')
          .first();
      };
      var syncCheckoutServiceTabs = function (serviceType) {
        serviceType = (serviceType || '').toLowerCase();
        if (!serviceType) {
          return;
        }

        var $activeServiceTab = findCheckoutServiceTab(serviceType);
        if (!$activeServiceTab.length) {
          return;
        }

        var $wrapper = $activeServiceTab.closest('.rpress-tabs-wrapper');
        $wrapper.find('#rpressdeliveryTab .nav-item').removeClass('active');
        $wrapper.find('#rpressdeliveryTab .single-service-selected')
          .removeClass('active')
          .attr('aria-selected', 'false');

        $activeServiceTab
          .addClass('active')
          .attr('aria-selected', 'true');
        $activeServiceTab.closest('.nav-item').addClass('active');

        var targetTab = $activeServiceTab.attr('href');
        if (targetTab && targetTab.charAt(0) === '#') {
          $wrapper.find('.delivery-settings-wrapper').removeClass('active show');
          $wrapper.find(targetTab).addClass('active show');
        }
      };

      var refreshCheckoutServiceOption = async function () {
        if ($('#rpress_checkout_order_details').length === 0) {
          return;
        }

        if (!rp_scripts.update_service_nonce) {
          return;
        }

        if (checkoutUpdateInFlight) {
          return;
        }

        checkoutUpdateInFlight = true;
        $('#rpress_checkout_order_details')
          .addClass('rp-loading');

        try {
          const requestBody = new URLSearchParams();
          requestBody.set('action', 'rpress_checkout_update_service_option');
          requestBody.set('security', rp_scripts.update_service_nonce);

          const promiseData = await fetch(rp_scripts.ajaxurl, {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: requestBody.toString()
          });
          if (!promiseData.ok) {
            throw new Error('Checkout refresh request failed');
          }

          const html = await promiseData.json();
          if (!html || !html.success || !html.data) {
            throw new Error('Invalid checkout refresh payload');
          }

          $('#rpress_checkout_order_details')
            .replaceWith(html.data['order_html']);
          $('#rpress_checkout_cart_wrap')
            .html(html.data['cart_html']);
          $('.rpress_cart_amount')
            .replaceWith(html.data['total_amount']);
          var restoredServiceType = rp_getCookie('service_type') || lastCheckoutServiceType;
          syncCheckoutServiceTabs(restoredServiceType);
          var $checkoutScope = getCheckoutServiceScope();
          if (applyServiceDefaults) {
            applyServiceDefaults($checkoutScope.length ? $checkoutScope : $(document), restoredServiceType);
          } else {
            var $activeTimeSelect = getActiveServiceTimeSelect($checkoutScope, restoredServiceType);
            restoreServiceTimeSelect($activeTimeSelect, rp_getCookie('service_time'));
          }
          $(document.body)
            .trigger('rp-checkout-update-service-option', [html]);
        } catch (e) {
          // Skip transient checkout refresh failures.
        } finally {
          checkoutUpdateInFlight = false;
          $('#rpress_checkout_order_details')
            .removeClass('rp-loading');
        }
      };

      // Infinate scroll for order history page 
      createObserver();
      //Select service type on checkout page 
      let chkServiceType = (rp_getCookie('service_type') || '')
        .toLowerCase();
      if (!chkServiceType) {
        var $initialCheckoutScope = getCheckoutServiceScope();
        chkServiceType = ($initialCheckoutScope.find('#rpressdeliveryTab .single-service-selected.active')
          .first()
          .data('service-type') || '')
          .toLowerCase();
        if (chkServiceType) {
          rp_setCookie('service_type', chkServiceType, rp_scripts.expire_cookie_time);
        }
      }
      if (chkServiceType) {
        syncCheckoutServiceTabs(chkServiceType);
        const $serviceTab = findCheckoutServiceTab(chkServiceType);
        lastCheckoutServiceType = chkServiceType;
        if ($serviceTab.length) {
          var $checkoutScope = getCheckoutServiceScope();
          if (applyServiceDefaults) {
            applyServiceDefaults($checkoutScope.length ? $checkoutScope : $(document), chkServiceType);
          } else {
            var $activeTimeSelect = getActiveServiceTimeSelect($checkoutScope, chkServiceType);
            restoreServiceTimeSelect($activeTimeSelect, rp_getCookie('service_time'));
          }
        }
      }
      $(document)
        .off('click.rpressCheckoutService', checkoutServiceTabSelector)
        .on('click.rpressCheckoutService', checkoutServiceTabSelector, async function (event) {
          const $clickedTab = $(this);
          if (!$clickedTab.closest('.rp-checkout-service-option, #rpress_checkout_order_details').length) {
            return;
          }

          event.preventDefault();
          const serviceType_ = String($clickedTab
            .data('service-type') || '')
            .toLowerCase();

          if (!serviceType_) {
            return;
          }

          if (serviceType_ === lastCheckoutServiceType && $('#rpress_checkout_order_details').length > 0) {
            return;
          }

          lastCheckoutServiceType = serviceType_;
          syncCheckoutServiceTabs(serviceType_);
          rp_setCookie('service_type', serviceType_, rp_scripts.expire_cookie_time);
          var $checkoutScope = getCheckoutServiceScope();
          if (applyServiceDefaults) {
            applyServiceDefaults($checkoutScope.length ? $checkoutScope : $(document), serviceType_);
          } else {
            var $activeTimeSelect = getActiveServiceTimeSelect($checkoutScope, serviceType_);
            if ($activeTimeSelect.length) {
              var selectedTime = $activeTimeSelect.val() || '';
              var selectedTimeText = $activeTimeSelect.find('option:selected')
                .text()
                .trim();
              if (selectedTime) {
                rp_setCookie('service_time', selectedTime, rp_scripts.expire_cookie_time);
              }
              if (selectedTimeText) {
                rp_setCookie('service_time_text', selectedTimeText, rp_scripts.expire_cookie_time);
              }
            }
          }
          await refreshCheckoutServiceOption();
        });
      //set cookies on checkout page onchange service type
      $(document)
        .off('change.rpressCheckoutServiceTime', checkoutServiceTimeSelector)
        .on('change.rpressCheckoutServiceTime', checkoutServiceTimeSelector, function (event) {
          if (!$(this).closest('.rp-checkout-service-option, #rpress_checkout_order_details').length) {
            return;
          }

          if (!event.originalEvent) {
            return;
          }
          var $checkoutScope = getCheckoutServiceScope();
          $checkoutScope.find('.rpress-delivery-opt-update')
            .first()
            .trigger('click');
        });
      $(document.body)
        .off('rp-refresh-checkout-service.rpress')
        .on('rp-refresh-checkout-service.rpress', function () {
          refreshCheckoutServiceOption();
        });
      //Remove the additional service date dropdown
      if (typeof rp_st_vars !== 'undefined' && rp_st_vars.enabled_sevice_type == 'delivery_and_pickup') {
        $('.delivery-settings-wrapper#nav-pickup .delivery-time-wrapper:eq(0)')
          .remove();
      }
      var selectedServiceType = chkServiceType || rp_getCookie('service_type');
      var $checkoutScope = getCheckoutServiceScope();
      if (applyServiceDefaults) {
        applyServiceDefaults($checkoutScope.length ? $checkoutScope : $(document), selectedServiceType);
      } else {
        var serviceTime = rp_getCookie('service_time');
        if (serviceTime) {
          var $activeTimeSelect = getActiveServiceTimeSelect($checkoutScope, selectedServiceType);
          restoreServiceTimeSelect($activeTimeSelect, serviceTime);
        }
      }
    })

  $(document).on('click', 'a.rpress_cart_remove_item_btn', function (e) {
    var btnCount = $('.rpress_cart_remove_item_btn').length;

    // Check if there's only one element
    if (btnCount === 1) {
      var postData = {
        action: 'rpress_remove_fees_after_empty_cart',
        security: rp_scripts.clear_cart_nonce,
        gateway: rpress_gateway
      };

      $.ajax({
        type: "POST",
        data: postData,
        dataType: "json",
        url: rpress_global_vars.ajaxurl,
        success: function (response) {
          // Trigger a click event on the same button
          $('a.rpress_cart_remove_item_btn').click();
        }
      }).fail(function (data) {
        if (window.console && window.console.log) {
        }
      });
    }
  });
  // 
});
let page = 1;
const infinateCallback = async function (entries, observer) {
  for (var i = 0; i < entries.length; i++) {
    let cahnge = entries[i];
    if (cahnge.isIntersecting) {
      jQuery('#rp-order-history-infi-load-container')
        .html('<h2 class="rp-infi-load"><div class="rp-infi-loading">Loading...</div></h2>');
      page = page + 1;
      const data = await fetch(`${rp_scripts.ajaxurl}?action=rpress_more_order_history&security=${rp_scripts.order_details_nonce}&paged=${page}`);
      const html = await data.json();
      jQuery('#rpress_user_history .repress-history-inner')
        .append(html.data['html']);
      if (html.data['found_post'] == '0') {
        jQuery('#rp-order-history-infi-load-container')
          .hide();
      }
    }
  }
}
const createObserver = () => {
  const options = {
    threshold: 0,
  }
  const lastDiv = document.getElementById('rp-order-history-infi-load-container');
  if (!lastDiv) return;
  const observer = new IntersectionObserver(infinateCallback, options);
  observer.observe(lastDiv)
}
// Refresh page after coming from prev page
if (performance.navigation.type == 2) {
  var navReloadKey = 'rpress_nav_reloaded';
  if (!window.sessionStorage.getItem(navReloadKey)) {
    window.sessionStorage.setItem(navReloadKey, '1');
    location.reload(true);
  }
} else {
  window.sessionStorage.removeItem('rpress_nav_reloaded');
}
jQuery('.rpress_fooditems_list').find('.rpress_fooditem_inner').each(function (index, item) {
  if (0 === jQuery(this).find('.rpress-thumbnail-holder').length) {
    jQuery(this).addClass('no-thumbnail-img');
  }
});
jQuery(document).ready(function ($) {
  $(document).on('change', '.rp-variable-price-option', function () {
    rp_checked_default_subaddon();
  });
});

jQuery(document).ready(function ($) {
  const float_menu = $(".container-actionmenu");
  if ($('.rpress-mobile-cart-icons').is(':visible')) {
    float_menu.addClass("cart-has-items");
  }
  // Handle tab switching and cookie update on service tab click
  $(document)
    .off('click.rpressServiceTabs', '.rpress-tabs-wrapper .nav-link')
    .on('click.rpressServiceTabs', '.rpress-tabs-wrapper .nav-link', function (e) {
      var $this = $(this);
      var $wrapper = $this.closest('.rpress-tabs-wrapper');

      // Checkout has a dedicated service-switch flow; skip the generic tab updater here.
      if ($wrapper.closest('.rp-checkout-service-option, #rpress_checkout_order_details').length) {
        return;
      }

      e.preventDefault();

      // Remove active class from all nav-items and nav-links
      $wrapper.find('.nav-item').removeClass('active');
      $wrapper.find('.nav-link').removeClass('active');

      // Add active class to clicked tab
      $this.addClass('active');
      $this.closest('.nav-item').addClass('active');

      // Show the tab content if needed
      var targetTab = $this.attr('href');
      if (targetTab) {
        var $targetPane = $wrapper.closest('.rpress-time-preference-wrap, .rpress-delivery-wrap, .rp-checkout-service-option, #rpress_checkout_order_details')
          .find(targetTab)
          .first();

        if (!$targetPane.length) {
          $targetPane = $(targetTab).first();
        }

        if ($targetPane.length) {
          var $tabContent = $targetPane.closest('.tab-content');
          if ($tabContent.length) {
            $tabContent.find('.tab-pane').removeClass('active show');
          } else {
            $wrapper.find('.tab-pane').removeClass('active show');
          }
          $targetPane.addClass('active show');
        }
      }

      // Update cookies for service type and label
      var serviceType = String($this.data('service-type') || '')
        .toLowerCase();
      var serviceLabel = $this.text().trim();
      var oldUiUxEnabled = (typeof window.rp_is_old_ui_ux_enabled === 'function') && window.rp_is_old_ui_ux_enabled();
      if (serviceType) {
        rp_setCookie('service_type', serviceType, rp_scripts.expire_cookie_time);
        var $dateTimeModal = $('#rpressDateTime');
        var isDateTimeModalOpen = $dateTimeModal.length &&
          ($dateTimeModal.hasClass('is-open') || $dateTimeModal.attr('aria-hidden') === 'false');

        // Avoid replacing modal HTML while it is open; this causes the popup to flash and close.
        if (!isDateTimeModalOpen) {
          updataModalOnServiceTypeChange(serviceType);
        }
        if (oldUiUxEnabled) {
          if (typeof window.rp_prepare_old_ui_modal_selection === 'function') {
            window.rp_prepare_old_ui_modal_selection($wrapper.length ? $wrapper : $(document));
          }
        } else if (typeof window.rp_apply_service_defaults === 'function') {
          window.rp_apply_service_defaults($wrapper.length ? $wrapper : $(document), serviceType);
        }
      }
      if (typeof Cookies !== 'undefined') {
        Cookies.set('service_label', serviceLabel, { expires: 1 });
      }

      // Optionally update UI somewhere else if needed
      $('.delivery-opts').html('<span class="delMethod">' + serviceLabel + '</span>');
    });

  /**
 * Fire a ajax call to update the modal 
 * on change of service type
 * @author RestroPress
 * @param {string} service_type
 */
  var rpModalSwitchRequestSeq = 0;
  const updataModalOnServiceTypeChange = function (service_type) {
    var requestedServiceType = String(service_type || '')
      .toLowerCase();
    var requestSeq = ++rpModalSwitchRequestSeq;

    $.get(`${rp_scripts.ajaxurl}?action=rpress_update_modal_on_service_switch&service_type=${service_type}&security=${rp_scripts.service_type_nonce}`, function (res) {
      // Ignore stale out-of-order responses from earlier service switches.
      if (requestSeq !== rpModalSwitchRequestSeq) {
        return;
      }

      var currentServiceType = String(rp_getCookie('service_type') || '')
        .toLowerCase();
      if (requestedServiceType && currentServiceType && requestedServiceType !== currentServiceType) {
        return;
      }

      if (res && res.success && res.data.modal_html && res.data.time_option_html) {
        var $existingDateTimeModal = $("#rpressDateTime");
        var wasDateTimeModalOpen = $existingDateTimeModal.length &&
          ($existingDateTimeModal.hasClass('is-open') || $existingDateTimeModal.attr('aria-hidden') === 'false');

        // Do not replace DOM while popup is open; that causes instant close/flicker.
        if (wasDateTimeModalOpen) {
          var isOldUiUxEnabled = (typeof window.rp_is_old_ui_ux_enabled === 'function') && window.rp_is_old_ui_ux_enabled();
          if (isOldUiUxEnabled && typeof window.rp_prepare_old_ui_modal_selection === 'function') {
            window.rp_prepare_old_ui_modal_selection($('#rpressDateTime-content'));
          } else if (typeof window.rp_apply_service_defaults === 'function') {
            var openSelection = window.rp_apply_service_defaults($('#rpressDateTime-content'), requestedServiceType || currentServiceType);
            if (openSelection.serviceDateText) {
              $("#deliveryDate").text(openSelection.serviceDateText);
            }
            if (openSelection.serviceTimeText) {
              $("#deliveryTime").text(openSelection.serviceTimeText);
            }
          }
          return;
        }

        $("#rpressDateTime").replaceWith(res.data.modal_html);
        $(".rpress-option-col.rpress-edit-address-wrap").html(
          `<span class="left-brdr"></span>${res.data.time_option_html}`
        );
        if (typeof window.rp_prepare_old_ui_modal_selection === 'function') {
          window.rp_prepare_old_ui_modal_selection($('#rpressDateTime-content'));
        }
        if (typeof window.rp_apply_service_defaults === 'function') {
          var oldUiUxEnabled = (typeof window.rp_is_old_ui_ux_enabled === 'function') && window.rp_is_old_ui_ux_enabled();
          var selection = window.rp_apply_service_defaults(
            $('#rpressDateTime-content'),
            service_type,
            !oldUiUxEnabled,
            oldUiUxEnabled
          );
          if (selection.serviceDateText) {
            $("#deliveryDate").text(selection.serviceDateText);
          }
          if (selection.serviceTimeText) {
            $("#deliveryTime").text(selection.serviceTimeText);
          }
        }

      }
    })
  }
});

/* Global cross-page order status watcher for browser notifications */
(function (window) {
  "use strict";

  if (typeof window.rp_scripts === "undefined" || !window.fetch || !window.URLSearchParams) {
    return;
  }

  var STORAGE_KEY = "rpress_live_order_tracker_v1";
  var TERMINAL_STATUSES = {
    completed: true,
    cancelled: true,
    failed: true
  };

  var pollTimer = null;
  var pusherClient = null;
  var pollRequestInFlight = false;

  function parseJson(value) {
    if (!value) {
      return null;
    }

    try {
      return JSON.parse(value);
    } catch (e) {
      return null;
    }
  }

  function readTracker() {
    if (!window.localStorage) {
      return null;
    }

    return parseJson(window.localStorage.getItem(STORAGE_KEY));
  }

  function writeTracker(tracker) {
    if (!window.localStorage || !tracker) {
      return;
    }

    try {
      window.localStorage.setItem(STORAGE_KEY, JSON.stringify(tracker));
    } catch (e) {
      // Ignore storage failures.
    }
  }

  function clearTracker() {
    if (!window.localStorage) {
      return;
    }

    try {
      window.localStorage.removeItem(STORAGE_KEY);
    } catch (e) {
      // Ignore storage failures.
    }
  }

  function isValidTracker(tracker) {
    if (!tracker || !tracker.payment_id || !tracker.payment_key || !tracker.security) {
      return false;
    }

    if (tracker.expires_at && Date.now() > parseInt(tracker.expires_at, 10)) {
      return false;
    }

    return true;
  }

  function getNotifiedStorageKey(paymentId) {
    return "rpress_live_order_notified_" + String(paymentId);
  }

  function markNotified(paymentId, statusKey) {
    if (!window.localStorage || !paymentId || !statusKey) {
      return;
    }

    try {
      window.localStorage.setItem(getNotifiedStorageKey(paymentId), String(statusKey));
    } catch (e) {
      // Ignore storage failures.
    }
  }

  function shouldNotify(paymentId, statusKey) {
    if (!window.localStorage || !paymentId || !statusKey) {
      return true;
    }

    var storageKey = getNotifiedStorageKey(paymentId);
    var lastStatus = null;

    try {
      lastStatus = window.localStorage.getItem(storageKey);
      if (lastStatus === String(statusKey)) {
        return false;
      }
      window.localStorage.setItem(storageKey, String(statusKey));
      return true;
    } catch (e) {
      return true;
    }
  }

  function showBrowserNotification(orderNumber, statusLabel) {
    if (!("Notification" in window) || Notification.permission !== "granted") {
      return;
    }

    var title = "Order update #" + orderNumber;
    var body = "Status: " + statusLabel;

    if ("serviceWorker" in navigator) {
      navigator.serviceWorker.getRegistration().then(function (registration) {
        if (registration && typeof registration.showNotification === "function") {
          registration.showNotification(title, {
            body: body,
            tag: "rpress-order-" + orderNumber
          });
          return;
        }

        try {
          new Notification(title, { body: body });
        } catch (e) {
          // Ignore browser-level notification errors.
        }
      }).catch(function () {
        try {
          new Notification(title, { body: body });
        } catch (e) {
          // Ignore browser-level notification errors.
        }
      });
      return;
    }

    try {
      new Notification(title, { body: body });
    } catch (e) {
      // Ignore browser-level notification errors.
    }
  }

  function handleIncomingStatus(data, notifyOnChange) {
    if (!data || !data.payment_id || !data.status) {
      return;
    }

    var tracker = readTracker();
    if (!isValidTracker(tracker) || parseInt(tracker.payment_id, 10) !== parseInt(data.payment_id, 10)) {
      return;
    }

    var previousStatus = tracker.status || "";
    tracker.status = data.status;
    tracker.status_label = data.status_label || data.status;
    tracker.order_number = data.order_number || tracker.order_number;
    tracker.updated_at_unix = data.updated_at_unix || tracker.updated_at_unix || 0;
    var statusChanged = previousStatus !== tracker.status;

    if (notifyOnChange && statusChanged && shouldNotify(tracker.payment_id, tracker.status)) {
      showBrowserNotification(tracker.order_number || tracker.payment_id, tracker.status_label);
    }

    if (TERMINAL_STATUSES[tracker.status]) {
      clearTracker();
      stopWatchers();
      return;
    }

    if (!tracker.expires_at || Date.now() > parseInt(tracker.expires_at, 10)) {
      tracker.expires_at = Date.now() + (6 * 60 * 60 * 1000);
    }

    writeTracker(tracker);
  }

  function fetchLatestStatus() {
    if (pollRequestInFlight) {
      return;
    }

    var tracker = readTracker();
    if (!isValidTracker(tracker)) {
      stopWatchers();
      clearTracker();
      return;
    }

    var body = new URLSearchParams();
    body.set("action", "rpress_receipt_order_status");
    body.set("payment_id", String(tracker.payment_id));
    body.set("payment_key", String(tracker.payment_key));
    body.set("security", String(tracker.security));

    pollRequestInFlight = true;
    fetch(window.rp_scripts.ajaxurl, {
      method: "POST",
      credentials: "same-origin",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
      },
      body: body.toString()
    })
      .then(function (response) {
        return response.json();
      })
      .then(function (result) {
        if (!result || !result.success || !result.data) {
          return;
        }

        handleIncomingStatus(result.data, true);
      })
      .catch(function () {
        // Ignore transient errors.
      })
      .then(function () {
        pollRequestInFlight = false;
      });
  }

  function startPolling() {
    if (pollTimer) {
      return;
    }

    fetchLatestStatus();
    pollTimer = window.setInterval(fetchLatestStatus, 10000);
  }

  function stopPolling() {
    if (pollTimer) {
      window.clearInterval(pollTimer);
      pollTimer = null;
    }
  }

  function stopWatchers() {
    stopPolling();

    if (pusherClient && typeof pusherClient.disconnect === "function") {
      pusherClient.disconnect();
      pusherClient = null;
    }
  }

  function connectPusher(tracker) {
    var realtime = tracker.realtime || {};
    if (!realtime.enabled || !realtime.key || !realtime.channel || !realtime.event || typeof window.Pusher === "undefined") {
      return false;
    }

    var options = {
      forceTLS: !!realtime.forceTLS
    };

    if (realtime.cluster) {
      options.cluster = realtime.cluster;
    }

    if (realtime.wsHost) {
      options.wsHost = realtime.wsHost;
    }

    if (realtime.wsPort) {
      options.wsPort = parseInt(realtime.wsPort, 10);
    }

    if (realtime.wssPort) {
      options.wssPort = parseInt(realtime.wssPort, 10);
    }

    try {
      pusherClient = new window.Pusher(realtime.key, options);
    } catch (e) {
      return false;
    }

    var channel = pusherClient.subscribe(realtime.channel);

    channel.bind(realtime.event, function (payload) {
      handleIncomingStatus(payload || {}, true);
    });

    channel.bind("pusher:subscription_error", function () {
      startPolling();
    });

    if (pusherClient.connection && typeof pusherClient.connection.bind === "function") {
      pusherClient.connection.bind("error", function () {
        startPolling();
      });
    }

    return true;
  }

  function loadScript(url, callback) {
    if (!url) {
      callback(false);
      return;
    }

    var scripts = document.getElementsByTagName("script");
    for (var i = 0; i < scripts.length; i++) {
      if (scripts[i].src === url) {
        callback(true);
        return;
      }
    }

    var script = document.createElement("script");
    script.src = url;
    script.async = true;
    script.onload = function () {
      callback(true);
    };
    script.onerror = function () {
      callback(false);
    };
    document.head.appendChild(script);
  }

  function startWatcher() {
    var tracker = readTracker();
    if (!isValidTracker(tracker)) {
      clearTracker();
      return;
    }

    if (tracker.status && TERMINAL_STATUSES[tracker.status]) {
      clearTracker();
      return;
    }

    if (tracker.status) {
      markNotified(tracker.payment_id, tracker.status);
    }

    var realtime = tracker.realtime || {};
    if (!realtime.enabled) {
      startPolling();
      return;
    }

    if (typeof window.Pusher !== "undefined") {
      if (connectPusher(tracker)) {
        window.setTimeout(fetchLatestStatus, 1200);
      } else {
        startPolling();
      }
      return;
    }

    loadScript(realtime.script_url, function (loaded) {
      if (!loaded) {
        startPolling();
        return;
      }

      if (connectPusher(tracker)) {
        window.setTimeout(fetchLatestStatus, 1200);
      } else {
        startPolling();
      }
    });
  }

  startWatcher();
  window.addEventListener("beforeunload", stopWatchers);
})(window);



/*---foodmenutab---*/
var SETTINGS = {
  navBarTravelling: false,
  navBarTravelDirection: "",
  navBarTravelDistance: 150
};

var colours = {
  0: "#867100",
  1: "#7F4200",
  2: "#99813D",
  3: "#40FEFF",
  4: "#14CC99",
  5: "#00BAFF",
  6: "#0082B2",
  7: "#B25D7A",
  8: "#00FF17",
  9: "#006B49",
  10: "#00B27A",
  11: "#996B3D",
  12: "#CC7014",
  13: "#40FF8C",
  14: "#FF3400",
  15: "#ECBB5E",
  16: "#ECBB0C",
  17: "#B9D912",
  18: "#253A93",
  19: "#125FB9"
};

document.documentElement.classList.remove("no-js");
document.documentElement.classList.add("js");

function initProductNav(config) {
  const nav = document.getElementById(config.nav);
  const contents = document.getElementById(config.contents);
  const indicator = document.getElementById(config.indicator);
  const leftBtn = document.getElementById(config.leftBtn);
  const rightBtn = document.getElementById(config.rightBtn);

  if (!nav || !contents || !indicator || !leftBtn || !rightBtn) return;

  nav.setAttribute("data-overflowing", determineOverflow(contents, nav));
  moveIndicator(nav.querySelector('[aria-selected="true"]'), indicator, colours[0], contents);

  let ticking = false;
  nav.addEventListener("scroll", function () {
    if (!ticking) {
      window.requestAnimationFrame(function () {
        nav.setAttribute("data-overflowing", determineOverflow(contents, nav));
        ticking = false;
      });
    }
    ticking = true;
  });

  leftBtn.addEventListener("click", function () {
    if (SETTINGS.navBarTravelling) return;
    const overflow = determineOverflow(contents, nav);
    if (overflow === "left" || overflow === "both") {
      const availableScrollLeft = nav.scrollLeft;
      const distance = availableScrollLeft < SETTINGS.navBarTravelDistance * 2
        ? availableScrollLeft
        : SETTINGS.navBarTravelDistance;

      contents.style.transform = `translateX(${distance}px)`;
      contents.classList.remove("pn-ProductNav_Contents-no-transition");
      SETTINGS.navBarTravelDirection = "left";
      SETTINGS.navBarTravelling = true;
    }
    nav.setAttribute("data-overflowing", determineOverflow(contents, nav));
  });

  rightBtn.addEventListener("click", function () {
    if (SETTINGS.navBarTravelling) return;
    const overflow = determineOverflow(contents, nav);
    if (overflow === "right" || overflow === "both") {
      const navBarRightEdge = contents.getBoundingClientRect().right;
      const scrollerRightEdge = nav.getBoundingClientRect().right;
      const availableScrollRight = Math.floor(navBarRightEdge - scrollerRightEdge);
      const distance = availableScrollRight < SETTINGS.navBarTravelDistance * 2
        ? availableScrollRight
        : SETTINGS.navBarTravelDistance;

      contents.style.transform = `translateX(-${distance}px)`;
      contents.classList.remove("pn-ProductNav_Contents-no-transition");
      SETTINGS.navBarTravelDirection = "right";
      SETTINGS.navBarTravelling = true;
    }
    nav.setAttribute("data-overflowing", determineOverflow(contents, nav));
  });

  contents.addEventListener("transitionend", function () {
    const tr = getComputedStyle(contents).transform;
    const amount = Math.abs(parseInt(tr.split(",")[4]) || 0);
    contents.style.transform = "none";
    contents.classList.add("pn-ProductNav_Contents-no-transition");
    if (SETTINGS.navBarTravelDirection === "left") {
      nav.scrollLeft -= amount;
    } else {
      nav.scrollLeft += amount;
    }
    SETTINGS.navBarTravelling = false;
  });

  contents.addEventListener("click", function (e) {
    if (!e.target.classList.contains('pn-ProductNav_Link')) return;
    const links = Array.from(contents.querySelectorAll(".pn-ProductNav_Link"));
    links.forEach(link => link.setAttribute("aria-selected", "false"));
    e.target.setAttribute("aria-selected", "true");
    moveIndicator(e.target, indicator, colours[links.indexOf(e.target)], contents);
  });

  window.addEventListener("resize", function () {
    const selected = nav.querySelector('[aria-selected="true"]');
    if (selected) moveIndicator(selected, indicator, null, contents);
  });
}

function moveIndicator(item, indicator, color, container) {
  if (!item || !indicator) return;
  const textPosition = item.getBoundingClientRect();
  const containerLeft = container.getBoundingClientRect().left;
  const distance = textPosition.left - containerLeft;
  const scroll = container.scrollLeft;
  indicator.style.transform = `translateX(${distance + scroll}px) scaleX(${textPosition.width * 0.01})`;
  if (color) indicator.style.backgroundColor = color;
}

function determineOverflow(content, container) {
  const containerRect = container.getBoundingClientRect();
  const contentRect = content.getBoundingClientRect();
  if (
    containerRect.left > contentRect.left &&
    containerRect.right < contentRect.right
  ) {
    return "both";
  } else if (contentRect.left < containerRect.left) {
    return "left";
  } else if (contentRect.right > containerRect.right) {
    return "right";
  } else {
    return "none";
  }
}

// Initialize both desktop and mobile tab navigations
initProductNav({
  nav: 'pnProductNav',
  contents: 'pnProductNavContents',
  indicator: 'pnIndicator',
  leftBtn: 'pnAdvancerLeft',
  rightBtn: 'pnAdvancerRight'
});

initProductNav({
  nav: 'pnProductNavMobile',
  contents: 'pnProductNavContentsMobile',
  indicator: 'pnIndicatorMobile',
  leftBtn: 'pnAdvancerLeftMobile',
  rightBtn: 'pnAdvancerRightMobile'
});

jQuery(function ($) {
  if (window.location.pathname === '/order-online/') {
    $('body').addClass('order-online');
  }
  $('.rpress-category-lists .rpress-category-link:first').addClass('current');
  $('.rpress-category-lists li:first').addClass('current');

  $('.cd-dropdown-trigger').on('click', function () {
    $('body').toggleClass('cd-overlay-open');

    if ($('body').hasClass('cd-overlay-open')) {
      // Add overlay if opening
      if ($('.rpress-cat-overlay').length === 0) {
        var cdDropdown = $('.cd-dropdown-wrapper .cd-dropdown');
        $('<div class="rpress-cat-overlay"></div>').insertAfter(cdDropdown);
      }
    } else {
      // Remove overlay if closing
      $('.rpress-cat-overlay').remove();
    }
  });
  $('.cd-close').on('click', function () {
    $('body').removeClass('cd-overlay-open');
    $('.rpress-cat-overlay').remove();
  });
  $('.rpress-editaddress-cancel-btn').on('click', function () {
    $('.rpress-mobile-cart-icons').show();
    MicroModal.close('rpressDateTime');
  });
  $('.cd-dropdown-trigger').on('click', function (event) {
    event.preventDefault();
    $('.rpress-mobile-cart-icons').hide();
    toggleNav();
  });

  $('.cd-dropdown .cd-close').on('click', function (event) {
    event.preventDefault();
    $('.rpress-mobile-cart-icons').show();
    toggleNav();
  });

  function toggleNav() {
    var navIsVisible = (!$('.cd-dropdown').hasClass('dropdown-is-active'));
    $('.cd-dropdown').toggleClass('dropdown-is-active', navIsVisible);
    $('.cd-dropdown-trigger').toggleClass('dropdown-is-active', navIsVisible);

    if (!navIsVisible) {
      $('.cd-dropdown').one('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function () {
        $('.has-children ul').addClass('is-hidden');
        $('.move-out').removeClass('move-out');
        $('.is-active').removeClass('is-active');
      });
    }
  }

  var oldUiUxEnabled = rp_is_old_ui_ux_enabled();
  if (oldUiUxEnabled && String(rp_scripts.cart_quantity || '0') === '0') {
    rp_clear_old_ui_service_cookies();
  }

  var serviceType = rp_getCookie('service_type');
  if (serviceType) {
    var capitalized = serviceType.charAt(0).toUpperCase() + serviceType.slice(1);
    $('.rpress-service-label').text(capitalized);
  }
  var $initialOrderServiceScope = $('.rpress-delivery-wrap .rpress-tabs-wrapper:visible')
    .first();
  var initialServiceType = window.rp_get_active_service_type(
    $initialOrderServiceScope.length ? $initialOrderServiceScope : $(document),
    serviceType || rp_scripts.default_service || 'delivery'
  );
  window.rp_sync_service_ui_state(
    $initialOrderServiceScope.length ? $initialOrderServiceScope : $(document),
    initialServiceType,
    !oldUiUxEnabled
  );
  if (!oldUiUxEnabled) {
    window.rp_sync_service_selection_cookies(
      $initialOrderServiceScope.length ? $initialOrderServiceScope : $(document),
      initialServiceType
    );
  }
  $('#rpressdeliveryTab').on('click', '.single-service-selected', function (e) {
    var $serviceTab = $(this);
    var selectedServiceType = String($serviceTab.data('service-type') || '')
      .toLowerCase();

    if (selectedServiceType) {
      var capitalized = selectedServiceType.charAt(0).toUpperCase() + selectedServiceType.slice(1);
      $('.rpress-service-label').text(capitalized);
    }

    setTimeout(function () {
      var $serviceScope = $serviceTab.closest('.rpress-tabs-wrapper');
      window.rp_sync_service_ui_state(
        $serviceScope.length ? $serviceScope : $(document),
        selectedServiceType,
        !oldUiUxEnabled
      );
      if (!oldUiUxEnabled) {
        window.rp_sync_service_selection_cookies($serviceScope.length ? $serviceScope : $(document), selectedServiceType);
      }
    }, 0);
  });

  setTimeout(function () {
    // Do not force change events on checkout; this can retrigger slot checks.
    if (String(rpress_scripts.is_checkout) === '1') {
      return;
    }

    var $hours = $("#rpressDateTime #rpress-delivery-hours, #rpressModal #rpress-delivery-hours").first();
    if (!$hours.length) {
      return;
    }

    var selectedVal = $hours.find("option:selected").val();
    if (!selectedVal) {
      selectedVal = $hours.find("option:first").val();
    }

    if (selectedVal) {
      $hours.val(selectedVal);
    }
  }, 1000);

  $(document).on('click', '.rp-variable-price-wrapper .radio-container', function () {
    var $radio = $(this).find('input[type="radio"]');

    if ($radio.length) {
      var name = $radio.attr('name');

      // Uncheck all radios in this group
      $('input[name="' + name + '"]').prop('checked', false);

      // Check the clicked one
      $radio.prop('checked', true).trigger('change');

      // Optional: manage "checked" class on container
      $('.radio-container').removeClass('checked');
      $(this).addClass('checked');
    }
  });
});
jQuery(document).ready(function ($) {
  $('.menu-category-wrap').first().addClass('first-menu-category-wrap');


  var $nav = $('#pnProductNav');

  function checkOverflow() {
    if ($nav.attr('data-overflowing') !== 'right') {
      $nav.parent('.pn-ProductNav_Wrapper').addClass('background-hidden');
    } else {
      $nav.parent('.pn-ProductNav_Wrapper').removeClass('background-hidden');
    }
  }

  // Run once on page load
  checkOverflow();

  function updateTooManyAdds($span) {
    var textOnly = $span.text().trim();
    var $parent = $span.closest('.rpress-price-holder');

    if ($parent.length) {
      if (textOnly.length > 3) {
        $parent.addClass('too-many-adds');
      } else {
        $parent.removeClass('too-many-adds');
      }
    }
  }

  // Initial check on page load
  $('span.rpress-add-to-cart-label.rp-ajax-toggle-text').each(function () {
    updateTooManyAdds($(this));
  });

  // Observe only the spans
  $('span.rpress-add-to-cart-label.rp-ajax-toggle-text').each(function () {
    var targetNode = this;

    var observer = new MutationObserver(function () {
      updateTooManyAdds($(targetNode));
    });

    observer.observe(targetNode, {
      characterData: true,
      subtree: true,
      childList: true
    });
  });
});

jQuery(document).ready(function ($) {

  var oldUiUxEnabled = rp_is_old_ui_ux_enabled();
  var $selectionScope = $('#rpressDateTime-content');
  if (!$selectionScope.length) {
    $selectionScope = $('#rpressDateTime');
  }
  if (!$selectionScope.length) {
    $selectionScope = $('.rpress-delivery-wrap .rpress-tabs-wrapper:visible').first();
  }

  var selection = null;
  if (oldUiUxEnabled) {
    var shouldResetOldUiContext = String(rp_scripts.cart_quantity || '0') === '0';
    var resetOldUiServiceContext = function () {
      rp_clear_old_ui_service_cookies();
      $('#deliveryDate').text('');
      $('#deliveryTime').text('');
      if (typeof window.rp_prepare_old_ui_modal_selection === 'function') {
        window.rp_prepare_old_ui_modal_selection($selectionScope.length ? $selectionScope : $(document));
      }
    };

    if (shouldResetOldUiContext) {
      resetOldUiServiceContext();
      setTimeout(resetOldUiServiceContext, 0);
      setTimeout(resetOldUiServiceContext, 1200);
    } else if (typeof window.rp_prepare_old_ui_modal_selection === 'function') {
      window.rp_prepare_old_ui_modal_selection($selectionScope.length ? $selectionScope : $(document));
    }
  } else {
    var serviceType = rp_getCookie('service_type') || rp_scripts.default_service || 'delivery';
    rp_setCookie('service_type', serviceType, rp_scripts.expire_cookie_time);
    selection = (typeof window.rp_apply_service_defaults === 'function')
      ? window.rp_apply_service_defaults(
        $selectionScope.length ? $selectionScope : $(document),
        serviceType,
        true
      )
      : null;
  }

  if (selection && selection.serviceDateText && (!oldUiUxEnabled || rp_getCookie('service_date') || rp_getCookie('delivery_date'))) {
    $('#deliveryDate').text(selection.serviceDateText);
  }
  if (selection && selection.serviceTimeText && (!oldUiUxEnabled || rp_getCookie('service_time') || rp_getCookie('service_time_text'))) {
    $('#deliveryTime').text(selection.serviceTimeText);
  }

  function initStickyMenu() {
    var $menu = $('.desktop-scroll-menu .make-me-sticky');
    var $sidebar = $('.sticky-sidebar');

    if ($(window).width() > 991 && $menu.length > 0) {
      // Fixed offset from top
      var stickyTop = 0;

      var menuOffset = $menu.offset().top;

      $(window).off('.stickyMenu'); // Remove previous events

      $(window).on('scroll.stickyMenu', function () {
        var scrollTop = $(window).scrollTop();

        if (scrollTop + stickyTop >= menuOffset) {
          $menu.css({
            'position': 'fixed',
            'top': stickyTop + 'px',
            'left': $menu.offset().left + 'px',
            'width': $menu.outerWidth(),
            'z-index': 999
          });
        } else {
          $menu.css({
            'position': 'static',
            'width': '',
            'top': '',
            'left': '',
            'z-index': ''
          });
        }
      });

      // Recalculate left & width on resize
      $(window).on('resize.stickyMenu', function () {
        $menu.css({
          'position': 'static',
          'width': '',
          'top': '',
          'left': '',
          'height': $sidebar.length > 0 ? $sidebar.outerHeight() : 'auto'
        });
        menuOffset = $menu.offset().top;
      });

    } else {
      // Reset sticky behavior on mobile
      $menu.css({
        'position': 'static',
        'height': 'auto'
      });
    }
  }

  initStickyMenu();
  $(window).on('resize', initStickyMenu);
  /**
   * Action Menu Toggle for Mobile
   */
  var actionContainer = document.querySelector(".container-actionmenu");
  var burger = document.getElementById("actionburger");
  var menu = document.querySelector(".actionmenu");

  if (actionContainer && burger && menu) {
    var toggleActionMenu = function () {
      burger.classList.toggle("is-expanded");

      // Get the icon and text elements
      var icon = burger.querySelector('i');
      var textNode = burger.querySelector('.menu-text');
      var isExpanded = burger.classList.contains('is-expanded');

      // Get texts and icons from data attributes
      var menuText = burger.getAttribute('data-text-menu');
      var closeText = burger.getAttribute('data-text-close');
      var menuIcon = burger.getAttribute('data-icon-menu');
      var closeIcon = burger.getAttribute('data-icon-close');

      if (isExpanded) {
        menu.classList.replace("slides-down", "slides-up");
        if (icon) {
          icon.className = closeIcon;
        }
        if (textNode) {
          textNode.textContent = closeText;
        }
      } else {
        menu.classList.replace("slides-up", "slides-down");
        if (icon) {
          icon.className = menuIcon;
        }
        if (textNode) {
          textNode.textContent = menuText;
        }
      }
    };

    // Toggle only when the menu button itself is clicked.
    burger.addEventListener("click", function (event) {
      event.preventDefault();
      event.stopPropagation();
      toggleActionMenu();
    });

  }
});
