(function (window, document) {
  if (!window || !document) {
    return;
  }

  const status = window.FoodordStoreStatus || {};
  const selectors = status.selectors || {};
  const cardSelector = selectors.productCard || '.foodord-product-card';
  const buttonSelectors = [selectors.addToCartButton, selectors.directAddButton]
    .filter(Boolean);

  const hostSelector = typeof status.containerSelector === 'string' && status.containerSelector
    ? status.containerSelector
    : 'body';

  let toastElement = null;
  let hideTimer = null;
  let activeMode = initialiseActiveMode();

  window.FoodordStoreStatusToast = {
    show: function (mode) {
      const resolvedMode = mode ? normalizeMode(mode) : determineFallbackMode();
      showToast(resolvedMode);
    },
    showUnavailableProduct: function (source) {
      showToast('', resolveUnavailableProductMessage(source));
    },
    hide: hideToast,
  };

  if (!hasClosedModes()) {
    return;
  }

  document.addEventListener('wrc:deliveryModeChange', function (event) {
    if (event && event.detail && event.detail.mode) {
      setActiveMode(event.detail.mode);
    }
  });

  document.addEventListener('click', interceptClick, true);

  function getModeEntries() {
    if (status && status.modes && typeof status.modes === 'object') {
      return Object.keys(status.modes);
    }
    return ['delivery', 'pickup'];
  }

  function getModeData(mode) {
    if (!status || !status.modes || typeof status.modes !== 'object') {
      return null;
    }
    if (Object.prototype.hasOwnProperty.call(status.modes, mode)) {
      return status.modes[mode];
    }
    return null;
  }

  function normalizeMode(mode) {
    return mode === 'pickup' ? 'pickup' : 'delivery';
  }

  function isModeOpen(mode) {
    const normalized = normalizeMode(mode);
    const data = getModeData(normalized);
    if (data && Object.prototype.hasOwnProperty.call(data, 'is_open')) {
      if (data.manual_locked || data.locked || data.custom_closed) {
        return false;
      }
      if (data.is_open) {
        return true;
      }
      if (data.preorder_enabled && data.preorder_open) {
        return true;
      }
      return false;
    }
    if (typeof status.isOpen === 'boolean') {
      return status.isOpen;
    }
    return true;
  }

  function getClosedModes() {
    if (status && status.modes && typeof status.modes === 'object') {
      const entries = Object.keys(status.modes);
      const closed = [];
      for (let i = 0; i < entries.length; i += 1) {
        const key = entries[i];
        if (!isModeOpen(key)) {
          closed.push(key);
        }
      }
      return closed;
    }
    if (typeof status.isOpen === 'boolean') {
      return status.isOpen ? [] : ['delivery', 'pickup'];
    }
    return [];
  }

  function hasClosedModes() {
    return getClosedModes().length > 0;
  }

  function getMobileToggleMode() {
    const toggle = document.querySelector('.foodord-mode-toggle-mobile[data-active-mode]');
    if (!toggle) {
      return null;
    }

    const attr = toggle.getAttribute('data-active-mode');
    if (attr === 'pickup' || attr === 'delivery') {
      return attr;
    }

    return null;
  }

  function detectModeFromDOM() {
    const pickupCard = document.querySelector('.wr-card.is-pickup');
    if (pickupCard) {
      return 'pickup';
    }
    const deliveryCard = document.querySelector('.wr-card.is-delivery');
    if (deliveryCard) {
      return 'delivery';
    }
    return null;
  }

  function getStoredMode() {
    if (window.FoodordDeliveryPickup && (window.FoodordDeliveryPickup.currentMode === 'delivery' || window.FoodordDeliveryPickup.currentMode === 'pickup')) {
      return window.FoodordDeliveryPickup.currentMode;
    }
    if (window.foodord_location_vars && (window.foodord_location_vars.mode === 'delivery' || window.foodord_location_vars.mode === 'pickup')) {
      return window.foodord_location_vars.mode;
    }
    return null;
  }

  function initialiseActiveMode() {
    const mobileToggleMode = getMobileToggleMode();
    if (mobileToggleMode) {
      return mobileToggleMode;
    }

    const domMode = detectModeFromDOM();
    if (domMode) {
      return domMode;
    }
    const storedMode = getStoredMode();
    if (storedMode) {
      return storedMode;
    }
    const modes = getModeEntries();
    if (modes.indexOf('delivery') !== -1) {
      return 'delivery';
    }
    return modes[0] || 'delivery';
  }

  function setActiveMode(mode) {
    const normalized = normalizeMode(mode);
    if (normalized) {
      activeMode = normalized;
    }
  }

  function determineFallbackMode() {
    if (isModeOpen(activeMode)) {
      return activeMode;
    }
    const entries = getModeEntries();
    for (let i = 0; i < entries.length; i += 1) {
      if (isModeOpen(entries[i])) {
        return entries[i];
      }
    }
    return activeMode;
  }

  function getModeMessage(mode) {
    const normalized = normalizeMode(mode);
    if (status && status.modeMessages && Object.prototype.hasOwnProperty.call(status.modeMessages, normalized)) {
      return status.modeMessages[normalized];
    }
    const data = getModeData(normalized);
    if (data && data.preorder_enabled && !data.preorder_open) {
      return status && typeof status.message === 'string' ? status.message : '';
    }
    return status && typeof status.message === 'string' ? status.message : '';
  }

  function resolveUnavailableProductMessage(source) {
    if (typeof source === 'string' && source.trim()) {
      return source;
    }

    if (source && typeof source.getAttribute === 'function') {
      const message = source.getAttribute('data-foodord-availability-message');
      if (typeof message === 'string' && message.trim()) {
        return message;
      }
    }

    return status && typeof status.unavailableProductMessage === 'string'
      ? status.unavailableProductMessage
      : 'This product is not available right now.';
  }

  function resolveModeFromEvent(event) {
    if (event && event.target && typeof event.target.closest === 'function') {
      const card = event.target.closest('.wr-card');
      if (card) {
        if (card.classList.contains('is-pickup')) {
          return 'pickup';
        }
        if (card.classList.contains('is-delivery')) {
          return 'delivery';
        }
      }

      const productCard = event.target.closest(cardSelector);
      if (productCard) {
        const mobileMode = getMobileToggleMode();
        if (mobileMode) {
          return mobileMode;
        }
      }
    }

    const fallbackMobileMode = getMobileToggleMode();
    if (fallbackMobileMode) {
      return fallbackMobileMode;
    }

    return activeMode;
  }

  function resolveHost() {
    const host = document.querySelector(hostSelector);
    return host || document.body;
  }

  function hideToast() {
    if (hideTimer) {
      window.clearTimeout(hideTimer);
      hideTimer = null;
    }

    if (!toastElement) {
      return;
    }
    toastElement.classList.remove('is-visible');
    toastElement.setAttribute('aria-hidden', 'true');
  }

  function ensureToast() {
    if (toastElement && toastElement.isConnected) {
      return toastElement;
    }

    toastElement = document.createElement('div');
    toastElement.className = 'foodord-store-toast';
    toastElement.setAttribute('role', 'alert');
    toastElement.setAttribute('aria-live', 'assertive');
    toastElement.setAttribute('aria-hidden', 'true');

    const iconEl = document.createElement('span');
    iconEl.className = 'foodord-store-toast__icon';
    iconEl.setAttribute('aria-hidden', 'true');
    iconEl.innerHTML = '<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="9" stroke="currentColor" stroke-width="2"/><path d="M12 8V8.01M12 12V16" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>';
    toastElement.appendChild(iconEl);

    const messageEl = document.createElement('span');
    messageEl.className = 'foodord-store-toast__message';
    toastElement.appendChild(messageEl);

    const closeBtn = document.createElement('button');
    closeBtn.type = 'button';
    closeBtn.className = 'foodord-store-toast__close';
    closeBtn.setAttribute('aria-label', status.closeLabel || 'Close');
    closeBtn.innerHTML = '<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M7 7L17 17M17 7L7 17" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"/></svg>';
    closeBtn.addEventListener('click', function (evt) {
      if (evt) {
        evt.preventDefault();
        evt.stopPropagation();
      }
      hideToast();
    });

    toastElement.appendChild(closeBtn);

    const host = resolveHost();
    host.appendChild(toastElement);

    return toastElement;
  }

  function showToast(mode, customMessage) {
    const toast = ensureToast();
    const messageEl = toast.querySelector('.foodord-store-toast__message');
    const message = typeof customMessage === 'string' && customMessage.trim()
      ? customMessage
      : getModeMessage(mode);
    if (messageEl) {
      messageEl.textContent = message;
    }
    toast.dataset.mode = mode || '';

    toast.classList.add('is-visible');
    toast.setAttribute('aria-hidden', 'false');

    if (hideTimer) {
      window.clearTimeout(hideTimer);
    }

    const rawDuration = typeof status.duration === 'number' ? status.duration : parseInt(status.duration, 10);
    const duration = Number.isFinite(rawDuration) && rawDuration > 0 ? rawDuration : 5000;

    hideTimer = window.setTimeout(function () {
      hideTimer = null;
      hideToast();
    }, duration);
  }

  function shouldHandleClick(event) {
    if (!event) {
      return false;
    }

    if (event.target && typeof event.target.closest === 'function') {
      const card = event.target.closest(cardSelector);
      if (card) {
        return true;
      }
    }

    if (buttonSelectors.length) {
      for (let i = 0; i < buttonSelectors.length; i += 1) {
        const selector = buttonSelectors[i];
        if (selector && event.target && typeof event.target.closest === 'function' && event.target.closest(selector)) {
          return true;
        }
      }
    }

    return false;
  }

  function interceptClick(event) {
    if (!shouldHandleClick(event)) {
      return;
    }

    const mode = resolveModeFromEvent(event);
    if (isModeOpen(mode)) {
      return;
    }

    if (typeof event.preventDefault === 'function') {
      event.preventDefault();
    }
    if (typeof event.stopPropagation === 'function') {
      event.stopPropagation();
    }
    if (typeof event.stopImmediatePropagation === 'function') {
      event.stopImmediatePropagation();
    }

    showToast(mode);
  }
})(window, document);
