(function () {
  'use strict';

  const instances = [];
  const addressBarI18n = (window.foodord_location_vars && window.foodord_location_vars.address_bar) || {};

  function getAddressBarString(key, fallback) {
    const value = addressBarI18n && typeof addressBarI18n[key] === 'string' ? addressBarI18n[key] : '';
    return value ? value : fallback;
  }

  function getMode() {
    try {
      const m = (window.foodord_location_vars && window.foodord_location_vars.mode) ? String(window.foodord_location_vars.mode) : 'delivery';
      return (m === 'pickup') ? 'pickup' : 'delivery';
    } catch (e) { /* no-op */ void e; return 'delivery'; }
  }

  function isRadiusDeliveryMode() {
    try {
      return !!(window.foodord_location_vars && window.foodord_location_vars.delivery_mode === 'radius');
    } catch (e) { /* no-op */ void e; }
    return false;
  }

  function getDeliveryModeStatus() {
    try {
      if (!window.FoodordDeliveryPickup || !window.FoodordDeliveryPickup.modeStatus) {
        return null;
      }
      const raw = window.FoodordDeliveryPickup.modeStatus.delivery;
      if (!raw || typeof raw !== 'object') {
        return null;
      }
      return raw;
    } catch (e) { /* no-op */ void e; }
    return null;
  }

  function isDeliveryModeOpen() {
    const status = getDeliveryModeStatus();
    if (!status) {
      return true;
    }
    if (Object.prototype.hasOwnProperty.call(status, 'is_open')) {
      return !!status.is_open;
    }
    if (Object.prototype.hasOwnProperty.call(status, 'isOpen')) {
      return !!status.isOpen;
    }
    return true;
  }

  function shouldShowAddressBarForMode(mode) {
    if (mode !== 'delivery') {
      return false;
    }
    return isDeliveryModeOpen();
  }

  // Format city display.
  function formatCityDisplay(raw) {
    if (!raw) return '';
    try {
      const lower = String(raw).toLocaleLowerCase('tr-TR');
      // Split by spaces/hyphens/apostrophes but keep separators to preserve formatting
      return lower.split(/([\s\-']+)/).map(function (part) {
        if (/^[\s\-']+$/.test(part) || part.length === 0) return part;
        const first = part.charAt(0).toLocaleUpperCase('tr-TR');
        const rest = part.slice(1);
        return first + rest;
      }).join('');
    } catch (e) { /* no-op */ void e; }
    // Fallback: simple first-letter uppercase without locale
    const s = String(raw);
    return s.charAt(0).toUpperCase() + s.slice(1);
  }

  function extractStreetLine(raw) {
    if (!raw) return '';
    const cleaned = String(raw).split(/\n/)[0].trim();
    if (!cleaned) {
      return '';
    }
    const firstSegment = cleaned.split(',')[0].trim();
    return firstSegment || cleaned;
  }

  function getCurrentAddressText() {
    const cur = (window.foodord_location_vars && window.foodord_location_vars.current) || {};
    try {
      if (isRadiusDeliveryMode()) {
        const addressRaw = (cur.address || '').trim();
        const street = extractStreetLine(addressRaw);
        const city = formatCityDisplay((cur.city || '').trim());
        if (street && city) {
          return street + ' · ' + city;
        }
        if (street) {
          return street;
        }
        if (city) {
          return city;
        }
      }
      const cityRaw = (cur.city || '').trim();
      const city = formatCityDisplay(cityRaw);
      if (city) { return city; }
    } catch (e) { /* no-op */ void e; }
    return getAddressBarString('placeholder', 'Select address');
  }

  function getCurrentDeliveryFeeAmount() {
    const cur = (window.foodord_location_vars && window.foodord_location_vars.current) || {};
    if (!cur || !cur.allowed) {
      return null;
    }

    const fee = Number(cur.fee);
    if (!Number.isFinite(fee) || fee < 0) {
      return null;
    }

    return fee;
  }

  function addThousandsSeparator(value, separator) {
    const parts = String(value).split('.');
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, separator);
    return parts.join('.');
  }

  function formatDeliveryFeeAmount(amount) {
    if (Number(amount) === 0) {
      return getAddressBarString('free', 'Free');
    }

    const symbol = typeof addressBarI18n.currency_symbol === 'string' ? addressBarI18n.currency_symbol : '';
    const position = typeof addressBarI18n.currency_pos === 'string' ? addressBarI18n.currency_pos : 'left';
    const decimalsRaw = Number(addressBarI18n.price_decimals);
    const decimals = Number.isFinite(decimalsRaw) ? Math.max(0, decimalsRaw) : 2;
    const decimalSeparator = typeof addressBarI18n.decimal_separator === 'string' ? addressBarI18n.decimal_separator : '.';
    const thousandSeparator = typeof addressBarI18n.thousand_separator === 'string' ? addressBarI18n.thousand_separator : ',';
    const normalizedAmount = Number(amount);

    if (!Number.isFinite(normalizedAmount)) {
      return '';
    }

    const fixed = addThousandsSeparator(normalizedAmount.toFixed(decimals), thousandSeparator).replace('.', decimalSeparator);

    if (position === 'right') {
      return fixed + symbol;
    }
    if (position === 'right_space') {
      return fixed + ' ' + symbol;
    }
    if (position === 'left_space') {
      return symbol + ' ' + fixed;
    }

    return symbol + fixed;
  }

  function openLocationModal(e) {
    if (e && typeof e.preventDefault === 'function') e.preventDefault();
    try {
      if (typeof window.foodordOpenLocationModal === 'function') {
        window.foodordOpenLocationModal();
        return;
      }
      const m = document.getElementById('foodord-location-modal');
      if (m) {
        m.classList.add('is-open');
        m.setAttribute('aria-hidden', 'false');
        m.removeAttribute('inert');
        document.body.style.overflow = 'hidden';
      }
    } catch (e) { /* no-op */ void e; }
  }

  function buildAddressBar() {
    const bar = document.createElement('div');
    bar.className = 'wr-card__address-bar';
    bar.setAttribute('role', 'button');
    bar.setAttribute('tabindex', '0');
    bar.setAttribute('aria-label', getAddressBarString('change_aria', 'Change delivery address'));

    const left = document.createElement('div');
    left.className = 'wr-card__address-left';

    const iconWrap = document.createElement('span');
    iconWrap.className = 'wr-card__address-icon';
    iconWrap.innerHTML = '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"/><circle cx="12" cy="10" r="3"/></svg>';
    const icon = iconWrap.firstChild;

    const value = document.createElement('span');
    value.className = 'wr-card__address-value';
    value.textContent = getCurrentAddressText();

    const textWrap = document.createElement('span');
    textWrap.className = 'wr-card__address-text';

    const deliveryFee = document.createElement('span');
    deliveryFee.className = 'wr-card__address-delivery-fee';
    deliveryFee.setAttribute('aria-label', getAddressBarString('delivery_fee', 'Delivery Fee'));
    deliveryFee.hidden = true;

    const deliveryFeeIcon = document.createElement('span');
    deliveryFeeIcon.className = 'wr-card__address-delivery-fee-icon';
    deliveryFeeIcon.innerHTML = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="17" r="3"/><circle cx="18" cy="17" r="3"/><path d="M9 17h3.2l2.5-6H11"/><path d="M14.7 11l-2.2-4H9.8"/><path d="M16 7h2.7"/><path d="M5 14.1 7.2 10h3.1"/></svg>';

    const deliveryFeeValue = document.createElement('span');
    deliveryFeeValue.className = 'wr-card__address-delivery-fee-value';

    deliveryFee.appendChild(deliveryFeeIcon);
    deliveryFee.appendChild(deliveryFeeValue);
    textWrap.appendChild(value);
    textWrap.appendChild(deliveryFee);

    left.appendChild(icon);
    left.appendChild(textWrap);

    bar.appendChild(left);

    bar.addEventListener('click', openLocationModal);
    bar.addEventListener('keydown', function (e) {
      if (e.key === 'Enter' || e.key === ' ') openLocationModal(e);
    });

    if (!isRadiusDeliveryMode()) {
      const action = document.createElement('button');
      action.type = 'button';
      action.className = 'wr-card__address-change';
      action.textContent = getAddressBarString('change', 'Change');
      action.addEventListener('click', openLocationModal);
      bar.appendChild(action);
    }

    return { bar: bar, valueEl: value, feeEl: deliveryFee, feeValueEl: deliveryFeeValue };
  }

  function addAddressInstance(instance) {
    if (!instance || !instance.bar) {
      return;
    }

    if (!shouldShowAddressBarForMode(getMode())) {
      instance.bar.style.display = 'none';
    }

    instances.push(instance);
    applyLayout(instance);
  }

  function ensureOneAddressBar(card) {
    if (!card || card.dataset.addressBarInitialized === '1') return;

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

    const addr = buildAddressBar();

    // Prefer placing into the stable top container, below the toggle if present
    let topC = card.querySelector('.wr-card__top');
    if (!topC) {
      try {
        topC = document.createElement('div');
        topC.className = 'wr-card__top';
        card.insertBefore(topC, card.firstChild);
      } catch (e) { /* no-op */ void e; }
    }

    if (topC) {
      const toggle = card.querySelector('.wr-card__mode-toggle');
      if (toggle && toggle.parentNode === topC) {
        if (toggle.nextSibling) {
          topC.insertBefore(addr.bar, toggle.nextSibling);
        } else {
          topC.appendChild(addr.bar);
        }
      } else {
        topC.insertBefore(addr.bar, topC.firstChild);
      }
    } else {
      // Fallback: old behavior
      const toggle = card.querySelector('.wr-card__mode-toggle');
      if (toggle && toggle.parentNode) {
        if (toggle.nextSibling) {
          toggle.parentNode.insertBefore(addr.bar, toggle.nextSibling);
        } else {
          toggle.parentNode.appendChild(addr.bar);
        }
      } else {
        card.insertBefore(addr.bar, header);
        // Observe for a future toggle injection and move below it when it appears
        try {
          const mo = new MutationObserver(function (mutList) {
            for (let i = 0; i < mutList.length; i++) {
              const nodes = mutList[i].addedNodes || [];
              for (let j = 0; j < nodes.length; j++) {
                const n = nodes[j];
                if (n && n.nodeType === 1 && n.classList && n.classList.contains('wr-card__mode-toggle')) {
                  if (n.nextSibling) {
                    n.parentNode.insertBefore(addr.bar, n.nextSibling);
                  } else {
                    n.parentNode.appendChild(addr.bar);
                  }
                  try { mo.disconnect(); } catch (e) { /* no-op */ void e; }
                  return;
                }
              }
            }
          });
          mo.observe(card, { childList: true });
        } catch (e) { /* no-op */ void e; }
      }
    }

    card.classList.add('has-address-bar');
    card.dataset.addressBarInitialized = '1';

    // Initial visibility by mode
    addAddressInstance({
      card: card,
      bar: addr.bar,
      valueEl: addr.valueEl,
      feeEl: addr.feeEl,
      feeValueEl: addr.feeValueEl
    });
  }

  function ensureStandaloneAddressBar() {
    const slot = document.querySelector('[data-foodord-address-slot="products"]');
    if (!slot || slot.dataset.addressBarInitialized === '1') {
      return;
    }

    const addr = buildAddressBar();
    slot.appendChild(addr.bar);
    slot.dataset.addressBarInitialized = '1';

    addAddressInstance({
      card: slot,
      bar: addr.bar,
      valueEl: addr.valueEl,
      feeEl: addr.feeEl,
      feeValueEl: addr.feeValueEl,
      skipLayout: true
    });
  }

  function refreshAllValues() {
    const text = getCurrentAddressText();
    const feeAmount = getCurrentDeliveryFeeAmount();
    const feeText = null === feeAmount ? '' : formatDeliveryFeeAmount(feeAmount);
    instances.forEach(function (inst) {
      if (inst && inst.valueEl) {
        inst.valueEl.textContent = text;
      }
      if (inst && inst.feeEl && inst.feeValueEl) {
        if (feeText && getMode() === 'delivery') {
          inst.feeValueEl.textContent = feeText;
          inst.feeEl.hidden = false;
        } else {
          inst.feeValueEl.textContent = '';
          inst.feeEl.hidden = true;
        }
      }
    });
  }

  function setAllVisibility(mode) {
    const show = shouldShowAddressBarForMode(mode);
    instances.forEach(function (inst) {
      if (inst && inst.bar) {
        inst.bar.style.display = show ? 'flex' : 'none';
      }
      if (inst && inst.card) {
        applyLayout(inst);
      }
    });
  }

  // Helper functions for potential future use
  // function isDesktop() {
  //   return window.innerWidth >= 1025;
  // }
  // 
  // function isSticky() {
  //   return !!document.querySelector('.foodord-scroll-nav.is-sticky');
  // }


  function applyLayout(inst) {
    if (!inst || !inst.card || inst.skipLayout) return;
    const card = inst.card;
    const header = card.querySelector('.wr-card__header');
    const body = card.querySelector('.wr-card__body');
    const bar = inst.bar;

    // For stable variant, do not manipulate layout inline — CSS will manage it
    if (card.classList && card.classList.contains('wr-card--stable')) {
      try { if (header) { header.style.top = ''; header.style.marginBottom = ''; } } catch (_) { } // eslint-disable-line
      try { if (body) { body.style.marginTop = ''; body.style.paddingTop = ''; } } catch (_) { } // eslint-disable-line
      try { if (bar) { bar.style.marginTop = ''; } } catch (_) { } // eslint-disable-line
      return;
    }

    // Legacy behavior for non-stable variant
    if (header) {
      try { header.style.top = ''; header.style.marginBottom = ''; } catch (_) { } // eslint-disable-line
    }
    if (body) {
      try { body.style.marginTop = ''; body.style.paddingTop = ''; } catch (_) { } // eslint-disable-line
    }
    if (bar) {
      try { bar.style.marginTop = ''; } catch (_) { } // eslint-disable-line
    }
  }

  function refreshAllLayouts() {
    instances.forEach(function (inst) { applyLayout(inst); });
  }

  // Ensure the address bar sits below mobile delivery/pickup toggles on small screens
  function ensureMobileAddressBar() {
    try {
      const bars = Array.prototype.slice.call(document.querySelectorAll('.wr-card__address-bar'));
      if (!bars.length) {
        return;
      }
      const isMobile = window.innerWidth && window.innerWidth <= 1024;

      const primaryBar = bars[0];
      const secondaryBars = bars.slice(1);

      if (isMobile) {
        const mobileWrap = document.querySelector('.foodord-mode-toggle-mobile');
        if (!mobileWrap || !primaryBar) {
          return;
        }
        const toggle = mobileWrap.querySelector('.wr-card__mode-toggle--mobile') || null;
        const beforeNode = toggle ? toggle.nextSibling : null;
        moveAddressBar(primaryBar, mobileWrap, beforeNode);
        primaryBar.classList.add('wr-card__address-bar--mobile-slot');
        secondaryBars.forEach(function (bar) {
          bar.classList.add('wr-card__address-bar--hidden-mobile');
        });
      } else {
        bars.forEach(function (bar) {
          bar.classList.remove('wr-card__address-bar--mobile-slot');
          bar.classList.remove('wr-card__address-bar--hidden-mobile');
          restoreAddressBar(bar);
        });
      }
    } catch (e) { /* no-op */ void e; }
  }

  function moveAddressBar(bar, container, beforeNode) {
    if (!bar || !container) return;
    if (!bar.__foodordOriginalParent) {
      bar.__foodordOriginalParent = bar.parentNode;
      bar.__foodordOriginalNext = bar.nextSibling;
    }

    if (beforeNode && beforeNode.parentNode === container) {
      if (bar.parentNode === container && bar.nextSibling === beforeNode) {
        return;
      }
      container.insertBefore(bar, beforeNode);
    } else {
      // If beforeNode is not provided, keep the bar as the last node in the container.
      if (bar.parentNode !== container || bar.nextSibling) {
        container.appendChild(bar);
      }
    }
  }

  function restoreAddressBar(bar) {
    if (!bar || !bar.__foodordOriginalParent) {
      return;
    }
    const parent = bar.__foodordOriginalParent;
    const next = bar.__foodordOriginalNext;
    if (bar.parentNode === parent) {
      return;
    }
    if (next && next.parentNode === parent) {
      parent.insertBefore(bar, next);
    } else {
      parent.appendChild(bar);
    }
  }

  function init() {
    const cards = document.querySelectorAll('.wr-card');
    if (cards && cards.length) {
      cards.forEach(ensureOneAddressBar);
      // If toggle script injects later, try a short delayed second pass
      try {
        setTimeout(function () {
          document.querySelectorAll('.wr-card').forEach(ensureOneAddressBar);
        }, 120);
      } catch (e) { /* no-op */ void e; }
    }

    ensureStandaloneAddressBar();

    // Always try to ensure mobile address bar once DOM is ready
    ensureMobileAddressBar();
    // If the mobile toggle is injected after this script, re-run shortly to correct ordering.
    try { setTimeout(ensureMobileAddressBar, 180); } catch (e) { /* no-op */ void e; }

    // Fill values initially
    refreshAllValues();

    // Sync with current mode
    setAllVisibility(getMode());
  }

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

  // Update value when location is selected
  document.addEventListener('foodord:locationSelected', function () {
    try { refreshAllValues(); refreshAllLayouts(); } catch (e) { /* no-op */ void e; }
  });

  // React to delivery/pickup mode changes
  document.addEventListener('wrc:deliveryModeChange', function (evt) {
    try {
      const mode = evt && evt.detail && evt.detail.mode ? String(evt.detail.mode) : '';
      if (mode === 'delivery' || mode === 'pickup') {
        setAllVisibility(mode);
        refreshAllLayouts();
      }
    } catch (e) { /* no-op */ void e; }
  });

  // Update on scroll/resize for sticky state and breakpoints
  window.addEventListener('scroll', function () { try { refreshAllLayouts(); } catch (e) { /* no-op */ void e; } }, { passive: true });
  window.addEventListener('resize', function () {
    try { ensureMobileAddressBar(); ensureStandaloneAddressBar(); refreshAllLayouts(); } catch (e) { /* no-op */ void e; }
  });
})();
