(function () {
  'use strict';

  const DESKTOP_MIN_WIDTH = 1025;
  const config = window.FoodordDeliveryPickup || {};
  const themeActive = !!config.themeActive;
  const CLOSED_LABEL = typeof config.closedLabel === 'string' && config.closedLabel ? config.closedLabel : 'Closed';
  const CLOSED_MESSAGE = typeof config.closedMessage === 'string' && config.closedMessage ? config.closedMessage : CLOSED_LABEL;
  const GROUP_LABEL = typeof config.groupLabel === 'string' && config.groupLabel ? config.groupLabel : 'Order mode';

  function syncModeState(mode) {
    if (mode !== 'delivery' && mode !== 'pickup') {
      return;
    }

    try {
      if (config && typeof config === 'object') {
        config.currentMode = mode;
      }
    } catch (error) { void error; }

    try {
      const hiddenField = document.querySelector('input[name="foodord_order_mode"]');
      if (hiddenField) {
        hiddenField.value = mode;
      }
    } catch (error) { void error; }

    try {
      if (window.foodord_location_vars && typeof window.foodord_location_vars === 'object') {
        window.foodord_location_vars.mode = mode;
      }
    } catch (error) { void error; }
  }

  let toggleInstances = [];
  let activeMode = selectInitialMode();
  syncModeState(activeMode);
  let initialSyncSent = false;
  function selectInitialMode() {
    let candidate = 'delivery';
    try {
      if (config && typeof config.currentMode === 'string' && (config.currentMode === 'delivery' || config.currentMode === 'pickup')) {
        candidate = config.currentMode;
      } else if (window.foodord_location_vars && (foodord_location_vars.mode === 'delivery' || foodord_location_vars.mode === 'pickup')) {
        candidate = foodord_location_vars.mode;
      }
    } catch (error) { void error; }

    // Auto-switch to available mode if candidate is unavailable.
    try {
      const delAvailable = isModeAvailable('delivery');
      const pickAvailable = isModeAvailable('pickup');

      // If candidate mode is not available, switch to the available one
      if (candidate === 'delivery' && !delAvailable && pickAvailable) {
        return 'pickup';
      }
      if (candidate === 'pickup' && !pickAvailable && delAvailable) {
        return 'delivery';
      }

      // If both available or both unavailable, keep candidate
      // If only one is available (regardless of candidate), prefer the available one
      if (delAvailable && !pickAvailable) {
        return 'delivery';
      }
      if (pickAvailable && !delAvailable) {
        return 'pickup';
      }
    } catch (error) { void error; }

    return candidate;
  }

  function modeStatusFor(mode) {
    if (!mode || !config.modeStatus || typeof config.modeStatus !== 'object') {
      return null;
    }
    const status = config.modeStatus[mode];
    if (!status || typeof status !== 'object') {
      return null;
    }
    return {
      isOpen: Boolean(status.is_open),
      preorderEnabled: Boolean(status.preorder_enabled),
      preorderOpen: Boolean(status.preorder_open),
      regularOpen: Boolean(status.regular_open),
      hasSlotsToday: Boolean(status.has_slots_today),
      customClosed: Boolean(status.custom_closed),
      manualLocked: Boolean(status.manual_locked || status.locked)
    };
  }

  function isModeAvailable(mode) {
    const status = modeStatusFor(mode);
    if (!status) {
      return true;
    }

    if (status.manualLocked || status.customClosed) {
      return false;
    }

    // Toggle should only be active when restaurant is actually open right now.
    // - regularOpen: within normal service hours
    // - preorderOpen: inside the configured preorder window (if enabled)
    // Note: status.isOpen can include future slot availability; we intentionally avoid that for UI state.
    return Boolean(status.regularOpen || (status.preorderEnabled && status.preorderOpen));
  }

  function createModeIcon(mode) {
    const iconWrap = document.createElement('span');
    iconWrap.className = mode === 'pickup' ? 'pickup-icon-wrap' : 'delivery-icon-wrap';

    if (mode === 'pickup') {
      iconWrap.innerHTML = `
        <svg viewBox="0 0 16 16" width="16" height="16" fill="currentColor" role="presentation" aria-hidden="true" class="pickup-icon">
          <path d="M2 15h12" stroke="currentColor" stroke-width="0.8" stroke-linecap="round" stroke-dasharray="1 3" class="motion-ground" />
          <path d="M6.496 10.383l-.19-.187-.12.424a3.25 3.25 0 0 1-.658 1.222l-1.43 1.67a.75.75 0 1 0 1.138.976l1.431-1.67c.343-.4.617-.854.81-1.342a8 8 0 0 0-.753-.867l-.223-.221z" class="pickup-leg pickup-leg-1" />
          <path d="M8.934 6.265c.071-.598-.096-1.276-.587-1.603a.9.9 0 0 0-.358-.106 1 1 0 0 0-.128-.018c-1.482-.077-2.49.626-3.1 1.51-.586.849-.813 1.863-.844 2.555a.75.75 0 0 0 1.499.067c.021-.483.19-1.206.579-1.77.169-.244.376-.458.638-.612l-.31 2.714a.75.75 0 0 0 .277.68c1.426 1.136 2.512 3.232 3.073 4.602a.75.75 0 0 0 1.388-.569c-.476-1.163-1.378-3.001-2.657-4.39l.043-.202c.07-.351.152-.764.206-1.023.12-.574.221-1.335.281-1.835" class="pickup-leg pickup-leg-2" />
          <path d="M9.595 6.38a2.7 2.7 0 0 0-.037-.883l.525.525c.36.36.847.561 1.355.561h.562a.75.75 0 0 1 0 1.5h-.562c-.717 0-1.41-.225-1.987-.637.06-.39.11-.775.144-1.065" class="pickup-body" />
          <path d="M9.667 2.667a1.333 1.333 0 1 1-2.667 0 1.333 1.333 0 0 1 2.667 0" class="pickup-head" />
        </svg>`;
    } else {
      iconWrap.innerHTML = `
        <svg viewBox="0 0 16 16" width="16" height="16" fill="currentColor" role="presentation" aria-hidden="true" class="delivery-icon">
          <path d="M1 14.5h14" stroke="currentColor" stroke-width="0.8" stroke-dasharray="2 4" class="motion-ground" />
          <g class="delivery-wheel delivery-wheel-1">
            <path d="M12 10.083a1.25 1.25 0 1 0 0 2.5 1.25 1.25 0 0 0 0-2.5m-2.75 1.25a2.75 2.75 0 1 1 5.5 0 2.75 2.75 0 0 1-5.5 0" />
            <path d="M12 9.133v1.2" stroke="white" stroke-width="0.6" stroke-linecap="round" class="delivery-wheel-spoke" />
          </g>
          <g class="delivery-wheel delivery-wheel-2">
            <path d="M4 10.083a1.25 1.25 0 1 0 0 2.5 1.25 1.25 0 0 0 0-2.5m-2.75 1.25a2.75 2.75 0 1 1 5.5 0 2.75 2.75 0 0 1-5.5 0" />
            <path d="M4 9.133v1.2" stroke="white" stroke-width="0.6" stroke-linecap="round" class="delivery-wheel-spoke" />
          </g>
          <path d="M7.47 5.136a.75.75 0 0 1 .946-.093l.227.152c.391.263.607.409.905.517.337.122.817.205 1.785.205a.75.75 0 0 1 0 1.5c-1.032 0-1.718-.085-2.298-.295a4 4 0 0 1-.41-.179c-.279.388-.668.798-1.069 1.086a5.27 5.27 0 0 1 1.194 3.304v.666a.75.75 0 0 1-1.5.001v-.667c0-1.105-.547-2.218-1.346-2.83-.481-.369-.648-1.153-.127-1.674zM10.667 3.333a1.333 1.333 0 1 1-2.667 0 1.333 1.333 0 0 1 2.667 0M6.256 2.98a.833.833 0 0 0-1.179 0l-1.93 1.93a.833.833 0 0 0 0 1.18l.597.597a.833.833 0 0 0 1.179 0l1.93-1.931a.833.833 0 0 0 0-1.179z" class="delivery-frame" />
        </svg>`;
    }

    return iconWrap.firstElementChild;
  }

  function createModeButton(mode) {
    const button = document.createElement('button');
    button.type = 'button';
    button.className = 'wr-card__mode-btn';
    button.dataset.mode = mode;
    button.appendChild(createModeIcon(mode));
    button.appendChild(document.createTextNode(mode === 'pickup' ? (config.pickupLabel || 'Pickup') : (config.deliveryLabel || 'Delivery')));
    return button;
  }

  function buildToggleBar() {
    const bar = document.createElement('div');
    bar.className = 'wr-card__mode-toggle';
    bar.setAttribute('role', 'group');
    bar.setAttribute('aria-label', GROUP_LABEL);

    const group = document.createElement('div');
    group.className = 'wr-card__mode-group';

    // Add slider element
    const slider = document.createElement('div');
    slider.className = 'wr-card__mode-slider';
    group.appendChild(slider);

    const deliveryBtn = createModeButton('delivery');
    const pickupBtn = createModeButton('pickup');

    group.appendChild(deliveryBtn);
    group.appendChild(pickupBtn);
    bar.appendChild(group);

    return { bar, deliveryBtn, pickupBtn, slider };
  }

  function updateButtonAvailability(button) {
    if (!button) {
      return;
    }
    const mode = button.dataset.mode;
    const available = isModeAvailable(mode);
    button.disabled = false;
    button.setAttribute('aria-disabled', available ? 'false' : 'true');
    button.classList.toggle('is-closed', !available);
    if (!available) {
      button.title = CLOSED_MESSAGE;
      button.classList.remove('is-active');
    } else if (button.title === CLOSED_MESSAGE) {
      button.removeAttribute('title');
    }
  }

  function isButtonUnavailable(button) {
    if (!button) {
      return true;
    }
    const mode = button.dataset.mode;
    return !isModeAvailable(mode) || button.classList.contains('is-closed') || button.getAttribute('aria-disabled') === 'true';
  }

  function showClosedModeToast(mode, event) {
    if (event) {
      if (typeof event.preventDefault === 'function') {
        event.preventDefault();
      }
      if (typeof event.stopPropagation === 'function') {
        event.stopPropagation();
      }
    }

    if (window.FoodordStoreStatusToast && typeof window.FoodordStoreStatusToast.show === 'function') {
      window.FoodordStoreStatusToast.show(mode);
      return;
    }

    if (typeof window.alert === 'function') {
      window.alert(CLOSED_MESSAGE);
    }
  }

  function handleModeButtonClick(button, mode, event) {
    if (isButtonUnavailable(button)) {
      showClosedModeToast(mode, event);
      return;
    }

    triggerIconAnimation(button);
    setMode(mode, 'user');
  }

  function updateAvailabilityForInstance(instance) {
    if (!instance) {
      return;
    }
    updateButtonAvailability(instance.deliveryBtn);
    updateButtonAvailability(instance.pickupBtn);
  }

  function updateInstanceUI(instance, mode) {
    if (!instance || !mode) {
      return;
    }

    const activeModeClosed = !isModeAvailable(mode);

    const buttons = [instance.deliveryBtn, instance.pickupBtn];
    buttons.forEach(function (btn) {
      if (!btn) {
        return;
      }

      const isSelected = btn.dataset.mode === mode;
      const canBeActive = isSelected && !isButtonUnavailable(btn);
      btn.classList.toggle('is-active', canBeActive);
    });

    // Slider is controlled purely via CSS classes (no inline style).
    if (instance.bar) {
      instance.bar.classList.toggle('is-delivery-active', mode === 'delivery');
      instance.bar.classList.toggle('is-pickup-active', mode === 'pickup');
      instance.bar.classList.toggle('is-store-closed', activeModeClosed);
    }

    if (instance.type === 'card' && instance.card) {
      instance.card.classList.toggle('is-delivery', mode === 'delivery');
      instance.card.classList.toggle('is-pickup', mode === 'pickup');
    }

    if (instance.container && (instance.type === 'mobile' || instance.type === 'products')) {
      instance.container.setAttribute('data-active-mode', mode);
    }
  }

  function updateAllUI(mode) {
    toggleInstances.forEach(function (instance) {
      updateInstanceUI(instance, mode);
    });
  }

  function triggerIconAnimation(btn) {
    if (!btn) return;

    // Find the parent group to stop other animations in the same toggle instance
    const group = btn.closest('.wr-card__mode-group');
    if (group) {
      const allIcons = group.querySelectorAll('.delivery-icon, .pickup-icon');
      allIcons.forEach(function (icon) {
        icon.classList.remove('is-animating');
      });
    }

    const icon = btn.querySelector('.delivery-icon, .pickup-icon');
    if (!icon) return;

    // Small delay to ensure the browser registers the class removal/re-addition for restart
    requestAnimationFrame(function () {
      icon.classList.add('is-animating');
    });

    setTimeout(function () {
      icon.classList.remove('is-animating');
    }, 3000);
  }

  function registerInstance(instance) {
    updateAvailabilityForInstance(instance);
    toggleInstances.push(instance);
    updateInstanceUI(instance, activeMode);

    // Broadcast initial active mode so other scripts (e.g., store-status) can align.
    if (!initialSyncSent && activeMode) {
      initialSyncSent = true;
      try {
        document.dispatchEvent(new CustomEvent('wrc:deliveryModeChange', { detail: { mode: activeMode, source: 'init', userInitiated: false }, bubbles: true }));
      } catch (error) { void error; }
      syncServerMode(activeMode);
    }
  }

  function syncServerMode(mode) {
    if (!mode || !config.ajaxUrl || !config.nonce) {
      return;
    }

    try {
      const form = new FormData();
      form.append('action', 'foodord_set_order_mode');
      form.append('mode', mode);
      form.append('nonce', config.nonce);

      fetch(config.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: form })
        .then(function (response) {
          if (!response.ok) {
            return null;
          }

          return response.json().catch(function () {
            return null;
          });
        })
        .then(function (payload) {
          if (!payload || payload.success !== true) {
            return;
          }

          try {
            document.dispatchEvent(new CustomEvent('wrc:deliveryModeSynced', { detail: { mode: mode }, bubbles: true }));
          } catch (error) {
            void error;
          }

          if (typeof jQuery !== 'undefined' && typeof window.foodord_modal_vars !== 'undefined') {
            jQuery.post(window.foodord_modal_vars.ajax_url, {
              action: 'foodord_get_cart_items',
              nonce: window.foodord_modal_vars.nonce
            }, function (resp) {
              if (resp && resp.success && resp.data) {
                try {
                  if (window.FoodordCard && window.FoodordCard.updateCTAState) {
                    window.FoodordCard.updateCTAState(resp.data);
                  }
                } catch (error) {
                  void error;
                }
                try {
                  document.dispatchEvent(new CustomEvent('foodord_cart_updated', { detail: resp.data }));
                } catch (error) {
                  void error;
                }
              }
            });
          }
        })
        .catch(function () { /* ignore */ });
    } catch (error) {
      void error;
    }
  }

  function setMode(mode, source) {
    const changeSource = source || 'system';
    if (!mode || !isModeAvailable(mode)) {
      return;
    }
    if (mode === activeMode) {
      return;
    }

    activeMode = mode;
    syncModeState(mode);
    updateAllUI(mode);

    // Update hidden checkout field if present
    try {
      if (typeof jQuery !== 'undefined') {
        jQuery('input[name="foodord_order_mode"]').val(mode);
      }
    } catch (error) { void error; }

    syncServerMode(mode);

    try {
      document.dispatchEvent(new CustomEvent('wrc:deliveryModeChange', { detail: { mode: mode, source: changeSource, userInitiated: changeSource === 'user' }, bubbles: true }));
    } catch (error) {
      void error;
    }
  }

  function createCardToggle(card) {
    if (!card || card.classList.contains('has-mode-toggle')) {
      return;
    }

    const header = card.querySelector('.wr-card__header');
    if (!header) {
      return;
    }

    // Ensure stable top container to hold toggle and address bar
    let topC = card.querySelector('.wr-card__top');
    if (!topC) {
      topC = document.createElement('div');
      topC.className = 'wr-card__top';
      card.insertBefore(topC, card.firstChild);
    }

    const toggle = buildToggleBar();
    // Always place toggle as the first element in the top container
    topC.insertBefore(toggle.bar, topC.firstChild);
    card.classList.add('has-mode-toggle', 'wr-card--stable');

    const instance = {
      type: 'card',
      card: card,
      bar: toggle.bar,
      deliveryBtn: toggle.deliveryBtn,
      pickupBtn: toggle.pickupBtn,
      slider: toggle.slider
    };

    toggle.deliveryBtn.addEventListener('click', function (event) {
      handleModeButtonClick(toggle.deliveryBtn, 'delivery', event);
    });

    toggle.pickupBtn.addEventListener('click', function (event) {
      handleModeButtonClick(toggle.pickupBtn, 'pickup', event);
    });

    registerInstance(instance);
  }

  function attachDesktopToggles() {
    const cards = document.querySelectorAll('.wr-card');
    cards.forEach(createCardToggle);
  }

  function detachDesktopToggles() {
    const remaining = [];

    toggleInstances.forEach(function (instance) {
      if (instance.type === 'card') {
        if (instance.bar && instance.bar.parentNode) {
          instance.bar.parentNode.removeChild(instance.bar);
        }
        if (instance.card) {
          instance.card.classList.remove('has-mode-toggle', 'is-delivery', 'is-pickup');
        }
      } else {
        remaining.push(instance);
      }
    });

    toggleInstances = remaining;
  }

  function createMobileToggle(container) {
    if (!container || container.dataset.modeToggleInitialized === '1') {
      return;
    }

    const toggle = buildToggleBar();
    toggle.bar.classList.add('wr-card__mode-toggle--mobile');
    container.appendChild(toggle.bar);

    const instance = {
      type: 'mobile',
      container: container,
      bar: toggle.bar,
      deliveryBtn: toggle.deliveryBtn,
      pickupBtn: toggle.pickupBtn,
      slider: toggle.slider
    };

    toggle.deliveryBtn.addEventListener('click', function (event) {
      handleModeButtonClick(toggle.deliveryBtn, 'delivery', event);
    });

    toggle.pickupBtn.addEventListener('click', function (event) {
      handleModeButtonClick(toggle.pickupBtn, 'pickup', event);
    });

    container.dataset.modeToggleInitialized = '1';

    registerInstance(instance);
  }

  function ensureMobileToggle() {
    const containers = document.querySelectorAll('.foodord-mode-toggle-mobile');
    if (!containers.length) {
      return;
    }
    containers.forEach(createMobileToggle);
  }

  function createProductsToggle(slot) {
    if (!slot || slot.dataset.modeToggleInitialized === '1') {
      return;
    }

    const toggle = buildToggleBar();
    toggle.bar.classList.add('wr-card__mode-toggle--products');
    slot.appendChild(toggle.bar);

    const instance = {
      type: 'products',
      container: slot,
      bar: toggle.bar,
      deliveryBtn: toggle.deliveryBtn,
      pickupBtn: toggle.pickupBtn,
      slider: toggle.slider
    };

    toggle.deliveryBtn.addEventListener('click', function (event) {
      handleModeButtonClick(toggle.deliveryBtn, 'delivery', event);
    });

    toggle.pickupBtn.addEventListener('click', function (event) {
      handleModeButtonClick(toggle.pickupBtn, 'pickup', event);
    });

    slot.dataset.modeToggleInitialized = '1';

    registerInstance(instance);
  }

  function ensureProductsToggle() {
    if (themeActive) {
      return;
    }
    const slots = document.querySelectorAll('[data-foodord-mode-toggle="products"]');
    if (!slots.length) {
      return;
    }
    slots.forEach(createProductsToggle);
  }

  function handleResize() {
    if (window.innerWidth >= DESKTOP_MIN_WIDTH) {
      attachDesktopToggles();
    } else {
      detachDesktopToggles();
    }
    updateAllUI(activeMode);
  }

  document.addEventListener('DOMContentLoaded', function () {
    ensureMobileToggle();
    ensureProductsToggle();
    if (window.innerWidth >= DESKTOP_MIN_WIDTH) {
      attachDesktopToggles();
    }
    updateAllUI(activeMode);
  });

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

  if (typeof MutationObserver !== 'undefined') {
    const observer = new MutationObserver(function () {
      ensureMobileToggle();
      ensureProductsToggle();
      if (window.innerWidth >= DESKTOP_MIN_WIDTH) {
        attachDesktopToggles();
      }
    });

    observer.observe(document.documentElement || document.body, {
      childList: true,
      subtree: true
    });
  }
})();
