(function ($) {
  'use strict';

  const locationVars = window.foodord_location_vars || {};

	function getAjaxBaseUrl() {
		if (locationVars && typeof locationVars.ajax_url === 'string' && locationVars.ajax_url) {
			return locationVars.ajax_url;
		}
		if (typeof window !== 'undefined' && typeof window.ajaxurl === 'string' && window.ajaxurl) {
			return window.ajaxurl;
		}
		return '';
	}

	function buildAjaxUrl(action) {
		const baseUrl = getAjaxBaseUrl();
		if (!baseUrl) {
			return '';
		}
		const encoded = encodeURIComponent(String(action || ''));
		return baseUrl.includes('?') ? (baseUrl + '&action=' + encoded) : (baseUrl + '?action=' + encoded);
	}
  const dropdownChevron = '<svg viewBox="0 0 20 20" aria-hidden="true" focusable="false"><path d="M6 8l4 4 4-4" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path></svg>';
  const deliveryMode = locationVars.delivery_mode || 'postal';
  const isRadiusMode = deliveryMode === 'radius';
	const radiusConfig = locationVars.radius || {};
	const radiusCenter = radiusConfig.center || {};
	const rawRadiusZones = Array.isArray(radiusConfig.zones) ? radiusConfig.zones : [];
	const radiusZones = isRadiusMode ? rawRadiusZones.map(function(zone) {
		const radiusVal = Number(zone && (zone.radius ?? zone.radius_km ?? zone.distance ?? 0));
		if (!Number.isFinite(radiusVal) || radiusVal <= 0) {
			return null;
		}
		return {
			radius: radiusVal,
			minimum: Number(zone && zone.minimum ? zone.minimum : 0) || 0,
			fee: Number(zone && zone.fee ? zone.fee : 0) || 0,
			label: zone && typeof zone.label === 'string' ? zone.label : ''
		};
	}).filter(Boolean).sort(function(a, b) {
		if (a.radius !== b.radius) {
			return a.radius - b.radius;
		}
		return a.minimum - b.minimum;
	}) : [];
	const maxRadiusKm = isRadiusMode ? (radiusZones.length ? radiusZones[radiusZones.length - 1].radius : Number(radiusConfig.distance_km || radiusConfig.distance || 0)) : 0;
	const storeLat = isRadiusMode ? Number(radiusCenter.lat) : null;
	const storeLng = isRadiusMode ? Number(radiusCenter.lng) : null;
	let radiusAutocomplete = null;
	let radiusInitialised = false;
	let radiusSelection = null;
	let radiusCurrentLocation = null;
	let radiusPacContainer = null;
	let radiusDropdownEventsBound = false;
	let radiusDropdownObserver = null;
	let radiusFormatDebounce = null;
	let radiusDropdownHasItems = false;
	let radiusDropdownEmptyTimer = null;
	let radiusDropdownSyncTimer = null;
	let radiusAutofillInProgress = false;
	let radiusAutofillRequestId = 0;
	let radiusModalIsClosing = false;
	let pendingProductModalRequest = null;

	function scheduleFormatUpdate() {
		if (radiusFormatDebounce) {
			clearTimeout(radiusFormatDebounce);
		}
		radiusFormatDebounce = setTimeout(function () {
			try {
				formatRadiusDropdownItems();
			} catch (err) {
				console.error('[foodord] formatRadiusDropdownItems error', err);
			}
		}, 16);
	}

	function updateRadiusClearState() {
		const input = document.querySelector(modal.selectors.radiusAddress);
		const clearBtn = document.getElementById('foodord-radius-clear');
		if (!clearBtn || !input) {
			return;
		}
		if (input.value && input.value.trim() !== '') {
			clearBtn.classList.remove('is-hidden');
		} else {
			clearBtn.classList.add('is-hidden');
		}
		updateRadiusCurrentVisibility();
	}

	function initRadiusClearControl(input) {
		const clearBtn = document.getElementById('foodord-radius-clear');
		if (!input || !clearBtn || clearBtn.dataset.wrcBound === '1') {
			updateRadiusClearState();
			return;
		}
		clearBtn.dataset.wrcBound = '1';

		clearBtn.addEventListener('click', function (event) {
			event.preventDefault();
			try {
				input.value = '';
				$(modal.selectors.radiusLat).val('');
				$(modal.selectors.radiusLng).val('');
				$(modal.selectors.radiusCity).val('');
				$(modal.selectors.radiusPostal).val('');
				clearRadiusHouseNumber();
			} catch { /* ignored */ }
			radiusSelection = null;
			modal.setFeedback('', null);
			updateRadiusClearState();
			try {
				const evt = new Event('input', { bubbles: true });
				input.dispatchEvent(evt);
			} catch { /* ignored */ }
			input.focus();
		});

		input.addEventListener('input', updateRadiusClearState);
		updateRadiusClearState();
	}

	function getRadiusLabel(key, fallback) {
		return locationVars.labels && locationVars.labels[key] ? locationVars.labels[key] : fallback;
	}

	function clearRadiusHouseNumber() {
		const row = document.querySelector(modal.selectors.radiusHouseNumberRow);
		const input = document.querySelector(modal.selectors.radiusHouseNumber);
		if (row) {
			row.classList.add('is-hidden');
		}
		if (input) {
			input.value = '';
		}
		updateRadiusSaveButtonState();
	}

	function setRadiusHouseNumberRequired(required) {
		const row = document.querySelector(modal.selectors.radiusHouseNumberRow);
		if (!row) {
			return;
		}
		row.classList.toggle('is-hidden', !required);
		if (!required) {
			clearRadiusHouseNumber();
		}
		updateRadiusSaveButtonState();
	}

	function getRadiusHouseNumber() {
		const input = document.querySelector(modal.selectors.radiusHouseNumber);
		return input ? input.value.trim() : '';
	}

	function hasRadiusAddressSelection() {
		const address = getRadiusSelectedAddress();
		const latVal = $(modal.selectors.radiusLat).val();
		const lngVal = $(modal.selectors.radiusLng).val();
		return !!(
			address &&
			latVal &&
			lngVal &&
			!isNaN(parseFloat(latVal)) &&
			!isNaN(parseFloat(lngVal))
		);
	}

	function getRadiusSelectedAddress() {
		const inputAddress = $(modal.selectors.radiusAddress).val().trim();
		if (inputAddress) {
			return inputAddress;
		}
		return radiusSelection && radiusSelection.address ? String(radiusSelection.address).trim() : '';
	}

	function hasRadiusAddressInputValue() {
		const input = document.querySelector(modal.selectors.radiusAddress);
		return !!(input && input.value.trim());
	}

	function updateRadiusSaveButtonState() {
		if (!isRadiusMode) {
			return;
		}
		const saveButton = document.querySelector(modal.selectors.save);
		if (!saveButton || saveButton.classList.contains('is-loading')) {
			return;
		}
		const needsHouseNumber = !!(radiusSelection && radiusSelection.requiresHouseNumber);
		const canSave = hasRadiusAddressSelection() && (!needsHouseNumber || !!getRadiusHouseNumber());
		saveButton.disabled = !canSave;
		saveButton.classList.toggle('is-disabled', !canSave);
	}

	function composeRadiusAddress(address, houseNumber) {
		const cleanAddress = String(address || '').trim();
		const cleanHouseNumber = String(houseNumber || '').trim();
		if (!cleanHouseNumber) {
			return cleanAddress;
		}
		if (!cleanAddress) {
			return cleanHouseNumber;
		}
		if (cleanAddress.indexOf(cleanHouseNumber) !== -1) {
			return cleanAddress;
		}
		const commaIndex = cleanAddress.indexOf(',');
		if (commaIndex > 0) {
			return cleanAddress.slice(0, commaIndex).trim() + ' ' + cleanHouseNumber + cleanAddress.slice(commaIndex);
		}
		return cleanAddress + ' ' + cleanHouseNumber;
	}

	function isRadiusSelectionInServiceArea(selection) {
		if (!selection) {
			return false;
		}
		if (Number.isFinite(storeLat) && Number.isFinite(storeLng)) {
			const distance = haversineDistance(storeLat, storeLng, selection.lat, selection.lng);
			let matchedZone = null;
			if (radiusZones.length) {
				matchedZone = findMatchingRadiusZone(distance);
			} else if (maxRadiusKm > 0) {
				matchedZone = distance <= maxRadiusKm ? { radius: maxRadiusKm } : null;
			}
			return !!matchedZone;
		}
		return true;
	}

	function updateRadiusSelectionPrompt(selection) {
		if (!selection) {
			return;
		}
		if (!isRadiusSelectionInServiceArea(selection)) {
			const failText = locationVars.labels && locationVars.labels.fail ? locationVars.labels.fail : 'We do not deliver to this address.';
			modal.setFeedback(failText, 'error');
			return;
		}
		if (selection.requiresHouseNumber) {
			modal.setFeedback(getRadiusLabel('house_number_required', 'Please enter your house number.'), 'error');
			return;
		}
		modal.setFeedback('', null);
	}

	function hasSavedRadiusLocation() {
		const current = getCurrentRadiusLocation();
		return !!(
			current &&
			(current.allowed === true || current.allowed === '1' || current.allowed === 1) &&
			typeof current.lat === 'number' &&
			!Number.isNaN(current.lat) &&
			typeof current.lng === 'number' &&
			!Number.isNaN(current.lng) &&
			current.address
		);
	}

	function getCurrentRadiusLocation() {
		if (
			typeof window.foodord_location_vars === 'object' &&
			window.foodord_location_vars &&
			typeof window.foodord_location_vars.current === 'object' &&
			window.foodord_location_vars.current
		) {
			return window.foodord_location_vars.current;
		}
		return locationVars.current || {};
	}

	function updateRadiusCurrentLocation(location) {
		const row = document.querySelector(modal.selectors.radiusCurrent);
		const addressEl = document.querySelector(modal.selectors.radiusCurrentAddress);
		if (!row || !addressEl) {
			return;
		}

		const address = location && location.address ? String(location.address).trim() : '';
		const lat = location && Number.isFinite(location.lat) ? location.lat : NaN;
		const lng = location && Number.isFinite(location.lng) ? location.lng : NaN;
		radiusCurrentLocation = address && Number.isFinite(lat) && Number.isFinite(lng) ? {
			address: address,
			city: location.city || '',
			postal: location.postal || '',
			lat: lat,
			lng: lng,
			requiresHouseNumber: !!location.requiresHouseNumber
		} : null;
		addressEl.textContent = address;
		updateRadiusCurrentVisibility();
		row.disabled = !radiusCurrentLocation;
	}

	function updateRadiusCurrentVisibility() {
		const row = document.querySelector(modal.selectors.radiusCurrent);
		if (!row) {
			return;
		}
		row.classList.toggle('is-hidden', radiusModalIsClosing || !radiusCurrentLocation || hasRadiusAddressInputValue());
	}

	function initRadiusCurrentLocationControl() {
		const row = document.querySelector(modal.selectors.radiusCurrent);
		if (!row || row.dataset.wrcBound === '1') {
			return;
		}
		row.dataset.wrcBound = '1';
		row.addEventListener('click', function (event) {
			event.preventDefault();
			if (!radiusCurrentLocation) {
				return;
			}
			hideRadiusDropdown();
			modal.setFeedback('', null);
			applyRadiusSelection(radiusCurrentLocation, { fillInput: true });
			updateRadiusSaveButtonState();
			validateRadiusAndSave();
		});
	}

	function resetRadiusFieldsToSavedLocation() {
		if (!isRadiusMode) {
			return;
		}

		const current = getCurrentRadiusLocation();
		if (hasSavedRadiusLocation()) {
			radiusSelection = {
				address: current.address || '',
				city: current.city || '',
				postal: current.postal || '',
				lat: current.lat,
				lng: current.lng
			};
			populateRadiusFieldsFromSelection(radiusSelection, { fillInput: false });
			updateRadiusCurrentLocation(radiusSelection);
		} else {
			radiusSelection = null;
			$(modal.selectors.radiusAddress).val('');
			$(modal.selectors.radiusLat).val('');
			$(modal.selectors.radiusLng).val('');
			$(modal.selectors.radiusCity).val('');
			$(modal.selectors.radiusPostal).val('');
			updateRadiusCurrentLocation(null);
			updateRadiusClearState();
		}

		clearRadiusHouseNumber();
		hideRadiusDropdown();
		updateRadiusSaveButtonState();
	}

	function isLocationModalOpen() {
		const modalEl = document.querySelector(modal.selectors.modal);
		return !!(modalEl && modalEl.classList.contains('is-open'));
	}

	function buildRadiusSelectionFromGeocode(result, lat, lng) {
		const parts = extractAddressParts(result && result.address_components ? result.address_components : []);
		return {
			address: result && result.formatted_address ? result.formatted_address : '',
			lat: lat,
			lng: lng,
			city: parts.city || '',
			postal: parts.postal || '',
			houseNumber: parts.houseNumber || '',
			requiresHouseNumber: !parts.houseNumber
		};
	}

	function applyRadiusSelection(selection, options) {
		radiusSelection = selection;
		populateRadiusFieldsFromSelection(radiusSelection, options);
		if (options && options.syncCurrent === true) {
			updateRadiusCurrentLocation(radiusSelection);
		}
		setRadiusHouseNumberRequired(!!(radiusSelection && radiusSelection.requiresHouseNumber && isRadiusSelectionInServiceArea(radiusSelection)));
		updateRadiusSelectionPrompt(radiusSelection);
	}

	function geocodeRadiusAddress(address, onComplete) {
		if (!window.google || !window.google.maps || !window.google.maps.Geocoder) {
			onComplete(null);
			return;
		}

		const geocoder = new window.google.maps.Geocoder();
		geocoder.geocode({ address: address }, function (results, status) {
			const result = Array.isArray(results) && results.length ? results[0] : null;
			if (status !== 'OK' || !result || !result.geometry || !result.geometry.location) {
				onComplete(null);
				return;
			}

			onComplete(buildRadiusSelectionFromGeocode(result, result.geometry.location.lat(), result.geometry.location.lng()));
		});
	}

	function requestRadiusAutofillOnOpen() {
		if (radiusAutofillInProgress || !isLocationModalOpen()) {
			return;
		}
		if (!navigator.geolocation || !window.google || !window.google.maps || !window.google.maps.Geocoder) {
			return;
		}

		radiusAutofillInProgress = true;
		radiusAutofillRequestId += 1;
		const requestId = radiusAutofillRequestId;

		const completeAutofill = function () {
			if (requestId === radiusAutofillRequestId) {
				radiusAutofillInProgress = false;
			}
		};

		navigator.geolocation.getCurrentPosition(
			function (position) {
				const lat = position && position.coords ? Number(position.coords.latitude) : NaN;
				const lng = position && position.coords ? Number(position.coords.longitude) : NaN;
				if (!Number.isFinite(lat) || !Number.isFinite(lng)) {
					completeAutofill();
					return;
				}

				const geocoder = new window.google.maps.Geocoder();
				geocoder.geocode({ location: { lat: lat, lng: lng } }, function (results, status) {
					completeAutofill();
					if (requestId !== radiusAutofillRequestId || !isLocationModalOpen()) {
						return;
					}
					const result = Array.isArray(results) && results.length ? results[0] : null;
					if (status !== 'OK' || !result) {
						modal.setFeedback(getRadiusLabel('location_no_address', 'Unable to find an address for your current location.'), 'error');
						return;
					}
					const input = document.querySelector(modal.selectors.radiusAddress);
					if (input && input.value.trim()) {
						return;
					}

					applyRadiusSelection(buildRadiusSelectionFromGeocode(result, lat, lng), {
						fillInput: false,
						syncCurrent: true
					});
				});
			},
			function () {
				completeAutofill();
			},
			{
				enableHighAccuracy: false,
				timeout: 10000,
				maximumAge: 300000
			}
		);
	}

  const modal = {
    el: null,
    lastFocus: null,
    closeTimer: null,
    selectors: {
      modal: '#foodord-location-modal',
      close: '#foodord-location-close',
      cancel: '#foodord-location-cancel',
      save: '#foodord-location-save',
		locationSelect: '#foodord-location-choice',
      feedback: '#foodord-location-feedback',
      radiusAddress: '#foodord-radius-address',
      radiusCurrent: '#foodord-radius-current',
      radiusCurrentAddress: '#foodord-radius-current-address',
      radiusHouseNumber: '#foodord-radius-house-number',
      radiusHouseNumberRow: '#foodord-radius-house-number-row',
      radiusLat: '#foodord-radius-lat',
      radiusLng: '#foodord-radius-lng',
      radiusCity: '#foodord-radius-city',
      radiusPostal: '#foodord-radius-postal',
      radiusFeedback: '#foodord-radius-feedback'
    },
    open() {
      const $m = $(this.selectors.modal);
      if ($m.length) {
        if (this.closeTimer) {
          window.clearTimeout(this.closeTimer);
          this.closeTimer = null;
        }
        // Remember previously focused element to restore on close
        this.lastFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
        $m.removeClass('is-closing').addClass('is-open').attr('aria-hidden', 'false').removeAttr('inert');
        $('body').css('overflow', 'hidden');
        if (isRadiusMode) {
          initRadiusCurrentLocationControl();
          resetRadiusFieldsToSavedLocation();
          initialiseRadiusFeaturesWhenReady();
          updateRadiusSaveButtonState();
          requestRadiusAutofillOnOpen();
        }
        // Focus first field for a11y without opening Places suggestions on radius mode.
        const $field = isRadiusMode ? $(this.selectors.save) : $('#foodord-location-modal .foodord-ttd__trigger');
        if ($field.length) {
try { $field.trigger('focus'); } catch { }
        }
        if (isRadiusMode) {
			updateRadiusClearState();
        }
		}
    },
    close() {
      const $m = $(this.selectors.modal);
      if ($m.length) {
        const shouldAnimate = $m.hasClass('is-open') || $m.hasClass('is-closing');
        if (this.closeTimer) {
          window.clearTimeout(this.closeTimer);
          this.closeTimer = null;
        }
        const modalEl = $m[0];
        const active = document.activeElement;

        // Blur current active element if it is inside the modal
        if (active && modalEl.contains(active) && typeof active.blur === 'function') {
try { active.blur(); } catch { }
        }

        // Try restoring focus outside the modal
        let movedFocus = false;
        if (this.lastFocus && document.contains(this.lastFocus) && !modalEl.contains(this.lastFocus) && typeof this.lastFocus.focus === 'function') {
try { this.lastFocus.focus(); movedFocus = true; } catch { }
        }
        if (!movedFocus) {
          const fallback = document.querySelector('main, [role="main"], header, footer, a,button,input,select,textarea,[tabindex]:not([tabindex="-1"])');
          if (fallback && !modalEl.contains(fallback) && typeof fallback.focus === 'function') {
try { fallback.focus(); movedFocus = true; } catch { }
          }
        }
        if (!movedFocus) {
          // Last resort: focus body temporarily
          try {
            document.body.setAttribute('tabindex', '-1');
            document.body.focus();
            document.body.removeAttribute('tabindex');
} catch (e) { /* no-op */ void e; }
        }

        if (isRadiusMode) {
          radiusModalIsClosing = true;
          updateRadiusCurrentVisibility();
        }

        $m.removeClass('is-open');

        const hide = () => {
          $m.removeClass('is-closing').attr('aria-hidden', 'true').attr('inert', '');
          $('body').css('overflow', '');
          radiusAutofillRequestId += 1;
          radiusAutofillInProgress = false;
          $(this.selectors.feedback).text('');
          $(this.selectors.radiusFeedback).text('');
          resetRadiusFieldsToSavedLocation();
          if (isRadiusMode) {
            setSaveButtonLoadingState(false);
            radiusModalIsClosing = false;
          }
          if (radiusPacContainer) {
            radiusPacContainer.style.display = 'none';
          }
			if (radiusDropdownObserver) {
				radiusDropdownObserver.disconnect();
				radiusDropdownObserver = null;
			}
			radiusPacContainer = null;
			this.closeTimer = null;
        };

        if (shouldAnimate) {
          $m.addClass('is-closing');
          this.closeTimer = window.setTimeout(hide, 320);
        } else {
          hide();
        }
      }
    },
	    setFeedback(msg, type) {
      const targetSelector = isRadiusMode ? this.selectors.radiusFeedback : this.selectors.feedback;
      const $fb = $(targetSelector);
      if (!$fb.length) {
        return;
      }
      if (isRadiusMode && msg && (type === 'error' || type === 'success')) {
        hideRadiusDropdown();
      }
      $fb.removeClass('is-success is-error');
      if (type === 'success') $fb.addClass('is-success');
      if (type === 'error') $fb.addClass('is-error');
      $fb.text(msg || '');
	    }
	  };

  function closeLocationDropdowns(exceptSelect) {
    document.querySelectorAll('#foodord-location-modal .foodord-ttd__dropdown.is-open').forEach(function (dropdown) {
      const ownerSelect = dropdown.parentNode ? dropdown.parentNode.querySelector('.foodord-ttd__native-select') : null;

      if (exceptSelect && ownerSelect === exceptSelect) {
        return;
      }

      dropdown.classList.remove('is-open');

      const trigger = dropdown.querySelector('.foodord-ttd__trigger');
      if (trigger) {
        trigger.setAttribute('aria-expanded', 'false');
      }
    });
  }

  function syncLocationCustomDropdown(select) {
    if (!select || !select.parentNode) {
      return;
    }

    let dropdown = select.parentNode.querySelector('.foodord-ttd__dropdown');

    if (!dropdown) {
      dropdown = document.createElement('div');
      dropdown.className = 'foodord-ttd__dropdown';

      const trigger = document.createElement('button');
      trigger.type = 'button';
      trigger.className = 'foodord-ttd__trigger';
      trigger.setAttribute('aria-haspopup', 'listbox');
      trigger.setAttribute('aria-expanded', 'false');

      const triggerLabel = document.createElement('span');
      triggerLabel.className = 'foodord-ttd__trigger-label';

      const triggerIcon = document.createElement('span');
      triggerIcon.className = 'foodord-ttd__trigger-icon';
      triggerIcon.innerHTML = dropdownChevron;

      const menu = document.createElement('div');
      menu.className = 'foodord-ttd__menu';
      menu.setAttribute('role', 'listbox');

      trigger.appendChild(triggerLabel);
      trigger.appendChild(triggerIcon);
      dropdown.appendChild(trigger);
      dropdown.appendChild(menu);
      select.parentNode.appendChild(dropdown);
      select.classList.add('foodord-ttd__native-select');

      trigger.addEventListener('click', function () {
        if (trigger.disabled) {
          return;
        }

        const isOpen = dropdown.classList.contains('is-open');
        closeLocationDropdowns(select);
        dropdown.classList.toggle('is-open', !isOpen);
        trigger.setAttribute('aria-expanded', !isOpen ? 'true' : 'false');
      });
    }

    const trigger = dropdown.querySelector('.foodord-ttd__trigger');
    const triggerLabel = dropdown.querySelector('.foodord-ttd__trigger-label');
    const menu = dropdown.querySelector('.foodord-ttd__menu');
    const options = Array.from(select.options || []);
    const selectedOption = select.selectedIndex >= 0 ? select.options[select.selectedIndex] : options[0];
    let interactiveOptionCount = 0;

    if (triggerLabel) {
      triggerLabel.textContent = selectedOption ? selectedOption.textContent : '';
    }

    if (menu) {
      menu.innerHTML = '';

      options.forEach(function (option, index) {
        const item = document.createElement('button');
        item.type = 'button';
        item.className = 'foodord-ttd__option';
        item.setAttribute('role', 'option');
        item.textContent = option.textContent || '';

        if (option.selected) {
          item.classList.add('is-selected');
          item.setAttribute('aria-selected', 'true');
        } else {
          item.setAttribute('aria-selected', 'false');
        }

        if (option.disabled) {
          item.disabled = true;
        } else {
          interactiveOptionCount += 1;
        }

        item.addEventListener('click', function () {
          if (option.disabled) {
            return;
          }

          select.selectedIndex = index;
          select.value = option.value;
          select.dispatchEvent(new Event('change', { bubbles: true }));
          syncLocationCustomDropdown(select);
          closeLocationDropdowns();
        });

        menu.appendChild(item);
      });
    }

    if (trigger) {
      const shouldDisableTrigger = select.disabled || interactiveOptionCount <= 1;
      trigger.disabled = shouldDisableTrigger;
      dropdown.classList.toggle('is-disabled', shouldDisableTrigger);

      if (shouldDisableTrigger) {
        dropdown.classList.remove('is-open');
        trigger.setAttribute('aria-expanded', 'false');
      }
    }
  }

  function initLocationCustomDropdown() {
    const select = document.querySelector(modal.selectors.locationSelect);
    if (!select) {
      return;
    }

    syncLocationCustomDropdown(select);

    select.addEventListener('change', function () {
      modal.setFeedback('', null);
      syncLocationCustomDropdown(select);
    });
  }

  function setSaveButtonLoadingState(isLoading) {
    const $saveBtn = $(modal.selectors.save);
    if (!$saveBtn.length) {
      return;
    }

    if (isLoading) {
      $saveBtn.addClass('is-loading').prop('disabled', true).attr('aria-busy', 'true');
      return;
    }

    $saveBtn.removeClass('is-loading').removeAttr('aria-busy');
    if (isRadiusMode) {
      updateRadiusSaveButtonState();
      return;
    }
    $saveBtn.prop('disabled', false);
  }

	function getSelectedDropdownLocation() {
		const select = document.querySelector(modal.selectors.locationSelect);
		if (!select) {
			return null;
		}
		const selectedOption = select.options[select.selectedIndex];
		if (!selectedOption || !selectedOption.value) {
			return null;
		}
		const cityAttr = selectedOption.getAttribute('data-city') || selectedOption.textContent || '';
		const postalAttr = selectedOption.getAttribute('data-postal') || '';
		return {
			id: selectedOption.value,
			city: String(cityAttr || '').trim(),
			postal: String(postalAttr || '').trim()
		};
	}

	  function validatePostalAndSave() {
		const selectedLocation = getSelectedDropdownLocation();
		const city = selectedLocation && selectedLocation.city ? selectedLocation.city : '';
		const postal = selectedLocation && selectedLocation.postal ? selectedLocation.postal : '';

		if (!city) {
			modal.setFeedback(foodord_location_vars.labels.select_area, 'error');
			return;
		}

		const payload = {
      action: 'foodord_validate_location',
      nonce: foodord_location_vars.nonce,
      city: city,
      postal_code: postal
    };

	    modal.setFeedback('', null);
      setSaveButtonLoadingState(true);

	    // Build ajax URL from localized admin_url (do not assume /wp-admin path)
	    const ajaxUrlPrimary = buildAjaxUrl('foodord_validate_location');
	    if (!ajaxUrlPrimary) {
				setSaveButtonLoadingState(false);
				modal.setFeedback(foodord_location_vars.labels.fail, 'error');
				return;
			}

    // Also send a duplicate 'security' field for plugins expecting that key
    payload.security = foodord_location_vars.nonce;

    const tryPost = (url, triedFallback) => {
      $.post(url, payload)
	        .done(function (resp) {
            setSaveButtonLoadingState(false);
	          if (!resp || resp.success !== true) {
	            modal.setFeedback(foodord_location_vars.labels.fail, 'error');
	            return;
          }
          const data = resp.data || {};
        if (data.allowed) {
          modal.setFeedback(foodord_location_vars.labels.success, 'success');
          try {
            if (typeof window.foodord_location_vars === 'undefined') { window.foodord_location_vars = {}; }
            if (typeof window.foodord_location_vars.current !== 'object' || window.foodord_location_vars.current === null) {
              window.foodord_location_vars.current = {};
            }
            window.foodord_location_vars.current.city = data.city || '';
            window.foodord_location_vars.current.postal = data.postal || '';
            window.foodord_location_vars.current.allowed = true;
            window.foodord_location_vars.current.fee = typeof data.fee === 'number' ? data.fee : 0;
            window.foodord_location_vars.current.minimum = typeof data.minimum === 'number' ? data.minimum : 0;
            window.foodord_location_vars.open_on_load = false;
            // Mark globally and via cookie to prevent reopening and allow quick gates
            window.FOODORD_LOCATION_OK = 1;
            try { document.cookie = 'foodord_location_ok=1; path=/; max-age=' + (7*24*60*60); } catch{ /* ignored */ }
            try { document.cookie = 'foodord_location=' + encodeURIComponent(JSON.stringify({city:data.city,postal:data.postal,allowed:true,fee:data.fee,minimum:data.minimum})) + '; path=/; max-age=' + (7*24*60*60); } catch{ /* ignored */ }
          } catch { /* no-op */ }

          // Close modal and refresh WooCommerce fragments/checkout without full reload
          try { modal.close(); } catch { /* ignored */ }
          setTimeout(function () {
            try {
              if (foodord_location_vars.is_checkout && typeof jQuery !== 'undefined') {
                jQuery(document.body).trigger('update_checkout');
              } else if (typeof jQuery !== 'undefined') {
              jQuery(document.body).trigger('wc_fragment_refresh');
              }
              // Emit a custom event for other scripts
              document.dispatchEvent(new CustomEvent('foodord:locationSelected', { detail: { city: data.city, postal: data.postal, fee: data.fee, minimum: data.minimum } }));
              if (typeof window.foodord_block_checkout_params !== 'undefined') {
                if (typeof data.minimum === 'number' && data.minimum > 0) {
                  window.foodord_block_checkout_params.minimum_order_amount = data.minimum;
                } else {
                  window.foodord_block_checkout_params.minimum_order_amount = 0;
                }
              }
} catch (e) { /* no-op */ void e; }
          }, 100);
        } else {
          // Disallowed: ensure cookies are cleared and global gate remains active
          try {
            if (typeof window !== 'undefined') {
              try { document.cookie = 'foodord_location_ok=; path=/; max-age=0'; } catch{ /* ignored */ }
              try { document.cookie = 'foodord_location=; path=/; max-age=0'; } catch{ /* ignored */ }
              window.FOODORD_LOCATION_OK = 0;
              if (typeof window.foodord_location_vars === 'undefined') { window.foodord_location_vars = {}; }
              if (typeof window.foodord_location_vars.current !== 'object' || window.foodord_location_vars.current === null) {
                window.foodord_location_vars.current = {};
              }
              window.foodord_location_vars.current.allowed = false;
              window.foodord_location_vars.current.minimum = 0;
            }
          } catch{ /* ignored */ }
          modal.setFeedback(foodord_location_vars.labels.fail, 'error');
        }
        })
	        .fail(function (xhr) {
            setSaveButtonLoadingState(false);
	          if (!triedFallback) {
						const ajaxUrlFallback = buildAjaxUrl('foodord_validate_location');
						if (ajaxUrlFallback) {
              setSaveButtonLoadingState(true);
							tryPost(ajaxUrlFallback, true);
						}
						return;
          }
          // Log details for debugging
          try { console.error('Location AJAX failed', xhr && xhr.status, xhr && xhr.responseText); } catch { /* ignored */ }
          let msg = foodord_location_vars.labels.fail;
          if (xhr && (xhr.status === 403)) { msg = 'Security check failed. Please refresh the page and try again.'; }
          modal.setFeedback(msg, 'error');
        });
    };

    tryPost(ajaxUrlPrimary, false);
  }

	  function validateRadiusAndSave() {
    let address = getRadiusSelectedAddress();
    const latVal = $(modal.selectors.radiusLat).val();
    const lngVal = $(modal.selectors.radiusLng).val();
    const city = $(modal.selectors.radiusCity).val().trim();
    const postal = $(modal.selectors.radiusPostal).val().trim();

    if (!address) {
      const prompt = locationVars.labels && locationVars.labels.radius_select_address ? locationVars.labels.radius_select_address : 'Please choose an address from the suggestions.';
      modal.setFeedback(prompt, 'error');
      return;
    }

    if (!latVal || !lngVal || isNaN(parseFloat(latVal)) || isNaN(parseFloat(lngVal))) {
      const prompt = locationVars.labels && locationVars.labels.radius_select_address ? locationVars.labels.radius_select_address : 'Please choose an address from the suggestions.';
      modal.setFeedback(prompt, 'error');
      return;
    }

    let shouldResolveHouseNumber = false;
    let requiredHouseNumber = '';
    if (radiusSelection && radiusSelection.requiresHouseNumber) {
      requiredHouseNumber = getRadiusHouseNumber();
      if (!requiredHouseNumber) {
        modal.setFeedback(getRadiusLabel('house_number_required', 'Please enter your house number.'), 'error');
        const houseNumberInput = document.querySelector(modal.selectors.radiusHouseNumber);
        if (houseNumberInput && typeof houseNumberInput.focus === 'function') {
          houseNumberInput.focus();
        }
        return;
      }
      address = composeRadiusAddress(address, requiredHouseNumber);
      shouldResolveHouseNumber = true;
    }

    const lat = parseFloat(latVal);
    const lng = parseFloat(lngVal);

    if (shouldResolveHouseNumber) {
      modal.setFeedback('', null);
      setSaveButtonLoadingState(true);
      geocodeRadiusAddress(address, function (selection) {
        if (!selection) {
          setSaveButtonLoadingState(false);
          const coordsError = locationVars.labels && locationVars.labels.radius_coords_error ? locationVars.labels.radius_coords_error : 'Unable to determine coordinates for this address.';
          modal.setFeedback(coordsError, 'error');
          return;
        }

        if (requiredHouseNumber && selection.address.indexOf(requiredHouseNumber) === -1) {
          selection.address = address;
        }
        selection.requiresHouseNumber = false;
        applyRadiusSelection(selection);
        validateRadiusAndSave();
      });
      return;
    }

    const payload = {
      action: 'foodord_validate_location',
      nonce: locationVars.nonce,
      address: address,
      lat: lat,
      lng: lng,
      city: city,
      postal_code: postal
    };

    modal.setFeedback('', null);

	    const ajaxUrlPrimary = buildAjaxUrl('foodord_validate_location');
	    if (!ajaxUrlPrimary) {
				setSaveButtonLoadingState(false);
				modal.setFeedback((locationVars.labels && locationVars.labels.fail) || 'We do not deliver to this address.', 'error');
				return;
			}
	    payload.security = locationVars.nonce;
      setSaveButtonLoadingState(true);

	    const tryPost = (url, triedFallback) => {
	      $.post(url, payload)
	        .done(function (resp) {
	          if (!resp || resp.success !== true) {
	            setSaveButtonLoadingState(false);
	            modal.setFeedback((locationVars.labels && locationVars.labels.fail) || 'Address not in delivery area.', 'error');
	            return;
          }
          const data = resp.data || {};
          if (data.allowed) {
            radiusSelection = {
              address: data.address || address,
              city: data.city || city,
              postal: data.postal || postal,
              lat: typeof data.lat === 'number' ? data.lat : lat,
              lng: typeof data.lng === 'number' ? data.lng : lng
            };
            populateRadiusFieldsFromSelection(radiusSelection, { preserveInput: true });
            try {
              if (typeof window.foodord_location_vars === 'undefined') { window.foodord_location_vars = {}; }
              if (typeof window.foodord_location_vars.current !== 'object' || window.foodord_location_vars.current === null) {
                window.foodord_location_vars.current = {};
              }
              window.foodord_location_vars.current.address = data.address || address;
              window.foodord_location_vars.current.city = data.city || city;
              window.foodord_location_vars.current.postal = data.postal || postal;
              window.foodord_location_vars.current.lat = typeof data.lat === 'number' ? data.lat : lat;
              window.foodord_location_vars.current.lng = typeof data.lng === 'number' ? data.lng : lng;
              window.foodord_location_vars.current.allowed = true;
              window.foodord_location_vars.current.fee = typeof data.fee === 'number' ? data.fee : 0;
              window.foodord_location_vars.current.minimum = typeof data.minimum === 'number' ? data.minimum : 0;
				window.foodord_location_vars.current.zone_radius = typeof data.zone_radius === 'number' ? data.zone_radius : 0;
              updateRadiusCurrentLocation(window.foodord_location_vars.current);
              window.foodord_location_vars.open_on_load = false;
              window.FOODORD_LOCATION_OK = 1;
              try { document.cookie = 'foodord_location_ok=1; path=/; max-age=' + (7 * 24 * 60 * 60); } catch { }
              const cookiePayload = {
                allowed: true,
                fee: window.foodord_location_vars.current.fee || 0,
                minimum: window.foodord_location_vars.current.minimum || 0,
                address: window.foodord_location_vars.current.address || '',
                city: window.foodord_location_vars.current.city || '',
                postal: window.foodord_location_vars.current.postal || '',
                lat: window.foodord_location_vars.current.lat,
					lng: window.foodord_location_vars.current.lng,
					zone_radius: window.foodord_location_vars.current.zone_radius || 0
              };
              try { document.cookie = 'foodord_location=' + encodeURIComponent(JSON.stringify(cookiePayload)) + '; path=/; max-age=' + (7 * 24 * 60 * 60); } catch { }
            } catch { }

            try { modal.close(); } catch { }
            setTimeout(function () {
              try {
                if (locationVars.is_checkout && typeof jQuery !== 'undefined') {
                  jQuery(document.body).trigger('update_checkout');
                } else if (typeof jQuery !== 'undefined') {
                  jQuery(document.body).trigger('wc_fragment_refresh');
                }
                document.dispatchEvent(new CustomEvent('foodord:locationSelected', { detail: {
                  address: data.address || address,
                  city: data.city || city,
                  postal: data.postal || postal,
                  lat: data.lat || lat,
                  lng: data.lng || lng,
                  fee: data.fee || 0,
                  minimum: data.minimum || 0,
						distance: data.distance || null,
						zone_radius: typeof data.zone_radius === 'number' ? data.zone_radius : null
                } }));
                if (typeof window.foodord_block_checkout_params !== 'undefined') {
                  if (typeof data.minimum === 'number' && data.minimum > 0) {
                    window.foodord_block_checkout_params.minimum_order_amount = data.minimum;
                  } else {
                    window.foodord_block_checkout_params.minimum_order_amount = 0;
                  }
                }
              } catch (e) { void e; }
            }, 100);
          } else {
            setSaveButtonLoadingState(false);
            try {
              document.cookie = 'foodord_location_ok=; path=/; max-age=0';
              document.cookie = 'foodord_location=; path=/; max-age=0';
            } catch { }
            window.FOODORD_LOCATION_OK = 0;
            const failMsg = (data && data.message) ? data.message : ((locationVars.labels && locationVars.labels.fail) || 'We do not deliver to this address.');
            modal.setFeedback(failMsg, 'error');
          }
        })
	        .fail(function (xhr) {
            setSaveButtonLoadingState(false);
	          if (!triedFallback) {
						const ajaxUrlFallback = buildAjaxUrl('foodord_validate_location');
						if (ajaxUrlFallback) {
              setSaveButtonLoadingState(true);
							tryPost(ajaxUrlFallback, true);
						}
						return;
          }
          try { console.error('Location AJAX failed', xhr && xhr.status, xhr && xhr.responseText); } catch { }
          let msg = (locationVars.labels && locationVars.labels.fail) || 'We do not deliver to this address.';
          if (xhr && xhr.status === 403) {
            msg = 'Security check failed. Please refresh the page and try again.';
          }
          modal.setFeedback(msg, 'error');
        });
    };

    tryPost(ajaxUrlPrimary, false);
  }

  function handleSave() {
    if (isRadiusMode) {
      validateRadiusAndSave();
    } else {
      validatePostalAndSave();
    }
  }

  function extractAddressParts(components) {
    const result = { city: '', postal: '', houseNumber: '' };
    if (!Array.isArray(components)) {
      return result;
    }
    components.forEach(function (component) {
      if (!component || !component.types) {
        return;
      }
      if (!result.postal && component.types.indexOf('postal_code') !== -1) {
        result.postal = component.long_name || component.short_name || '';
      }
      if (!result.houseNumber && component.types.indexOf('street_number') !== -1) {
        result.houseNumber = component.long_name || component.short_name || '';
      }
      if (!result.city && component.types.indexOf('locality') !== -1) {
        result.city = component.long_name || component.short_name || '';
      }
      if (!result.city && component.types.indexOf('postal_town') !== -1) {
        result.city = component.long_name || component.short_name || '';
      }
      if (!result.city && component.types.indexOf('administrative_area_level_2') !== -1) {
        result.city = component.long_name || component.short_name || '';
      }
      if (!result.city && component.types.indexOf('administrative_area_level_1') !== -1) {
        result.city = component.long_name || component.short_name || '';
      }
    });
    return result;
  }

  function haversineDistance(lat1, lng1, lat2, lng2) {
    const toRad = function (deg) { return deg * (Math.PI / 180); };
    const earthRadius = 6371.0;
    const dLat = toRad(lat2 - lat1);
    const dLng = toRad(lng2 - lng1);
    const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLng / 2) * Math.sin(dLng / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return earthRadius * c;
  }

	function findMatchingRadiusZone(distanceKm) {
		if (!isRadiusMode || !radiusZones.length || !Number.isFinite(distanceKm)) {
			return null;
		}
		for (let i = 0; i < radiusZones.length; i += 1) {
			if (distanceKm <= radiusZones[i].radius) {
				return radiusZones[i];
			}
		}
		return null;
	}

	function populateRadiusFieldsFromSelection(selection, options) {
    if (!selection) {
      return;
    }
    if (!options || options.preserveInput !== true) {
      const fillInput = !options || options.fillInput !== false;
      $(modal.selectors.radiusAddress).val(fillInput ? (selection.address || '') : '');
    }
    $(modal.selectors.radiusLat).val(Number.isFinite(selection.lat) ? selection.lat : '');
    $(modal.selectors.radiusLng).val(Number.isFinite(selection.lng) ? selection.lng : '');
    $(modal.selectors.radiusCity).val(selection.city || '');
    $(modal.selectors.radiusPostal).val(selection.postal || '');
	updateRadiusClearState();
  }

	function ensureRadiusDropdownAttached() {
    if (!isRadiusMode) {
      return;
    }

    const input = document.querySelector(modal.selectors.radiusAddress);
    if (!input) {
      return;
    }
    if (!input.value.trim()) {
      hideRadiusDropdown();
      return;
    }

	setTimeout(function () {
		if (!input.value.trim()) {
			hideRadiusDropdown();
			return;
		}
		const containers = document.querySelectorAll('.pac-container');
		if (!containers.length) {
			return;
		}
		const candidate = containers[containers.length - 1];

		if (candidate !== radiusPacContainer) {
			if (radiusDropdownObserver) {
				radiusDropdownObserver.disconnect();
				radiusDropdownObserver = null;
			}
			radiusPacContainer = candidate;
			if (radiusPacContainer) {
				radiusPacContainer.dataset.foodordRadius = '1';
				radiusPacContainer.classList.add('foodord-pac-container');
				radiusPacContainer.style.boxSizing = 'border-box';
				radiusDropdownObserver = new MutationObserver(function () {
					scheduleRadiusDropdownSync(input);
					updateRadiusDropdownDimensions();
					scheduleFormatUpdate();
				});
				radiusDropdownObserver.observe(radiusPacContainer, { childList: true, subtree: true });
			}
		}

		if (radiusPacContainer) {
			const inputWrap = input.parentElement;
			if (radiusPacContainer.parentNode !== inputWrap) {
				inputWrap.style.position = 'relative';
				inputWrap.appendChild(radiusPacContainer);
			}

			radiusPacContainer.style.position = 'absolute';
			radiusPacContainer.style.visibility = 'visible';
			radiusPacContainer.style.pointerEvents = 'auto';
			radiusPacContainer.style.zIndex = '100000';
			applyRadiusDropdownBranding();
			syncRadiusDropdownVisibility(input);
			updateRadiusDropdownDimensions();
			scheduleFormatUpdate();
			setTimeout(function () {
				syncRadiusDropdownVisibility(input);
				updateRadiusDropdownDimensions();
				scheduleFormatUpdate();
			}, 50);
			setTimeout(function () {
				syncRadiusDropdownVisibility(input);
				updateRadiusDropdownDimensions();
				scheduleFormatUpdate();
			}, 120);
		}
	}, 0);
	}

	function hideRadiusDropdown() {
		setRadiusDropdownOpenState(false);
		radiusDropdownHasItems = false;
		clearRadiusDropdownEmptyTimer();
		clearRadiusDropdownSyncTimer();
		if ( ! radiusPacContainer ) {
			return;
		}

		radiusPacContainer.style.display = 'none';
	}

	function hideRadiusDropdownIfInputEmpty(input) {
		if (input && input.value.trim()) {
			return;
		}

		hideRadiusDropdown();
		setTimeout(function () {
			hideRadiusDropdown();
		}, 40);
	}

	function syncRadiusDropdownVisibility(input) {
		if ( ! radiusPacContainer ) {
			return;
		}

		if ( ! input || ! input.value.trim() ) {
			radiusPacContainer.style.display = 'none';
			radiusDropdownHasItems = false;
			clearRadiusDropdownEmptyTimer();
			setRadiusDropdownOpenState(false);
			return;
		}

		if ( ! radiusPacContainer.querySelector('.pac-item') && ! radiusDropdownHasItems ) {
			radiusPacContainer.style.display = 'none';
			clearRadiusDropdownEmptyTimer();
			setRadiusDropdownOpenState(false);
			return;
		}

		if (radiusPacContainer.querySelector('.pac-item')) {
			radiusDropdownHasItems = true;
			clearRadiusDropdownEmptyTimer();
		} else {
			scheduleRadiusDropdownEmptyHide(input);
		}

		radiusPacContainer.style.display = '';
		setRadiusDropdownOpenState(true);
	}

	function scheduleRadiusDropdownSync(input) {
		if (radiusDropdownSyncTimer) {
			clearRadiusDropdownSyncTimer();
		}
		radiusDropdownSyncTimer = setTimeout(function () {
			radiusDropdownSyncTimer = null;
			syncRadiusDropdownVisibility(input);
		}, 60);
	}

	function clearRadiusDropdownSyncTimer() {
		if (!radiusDropdownSyncTimer) {
			return;
		}
		clearTimeout(radiusDropdownSyncTimer);
		radiusDropdownSyncTimer = null;
	}

	function scheduleRadiusDropdownEmptyHide(input) {
		clearRadiusDropdownEmptyTimer();
		radiusDropdownEmptyTimer = setTimeout(function () {
			if (!input || !input.value.trim() || !radiusPacContainer || radiusPacContainer.querySelector('.pac-item')) {
				return;
			}
			radiusDropdownHasItems = false;
			hideRadiusDropdown();
		}, 180);
	}

	function clearRadiusDropdownEmptyTimer() {
		if (!radiusDropdownEmptyTimer) {
			return;
		}
		clearTimeout(radiusDropdownEmptyTimer);
		radiusDropdownEmptyTimer = null;
	}

	function handleRadiusOutsidePointerDown(event) {
		if (!isRadiusMode || !radiusPacContainer) {
			return;
		}

		const input = document.querySelector(modal.selectors.radiusAddress);
		const target = event.target;
		if (!target || target === input || radiusPacContainer.contains(target)) {
			return;
		}

		hideRadiusDropdown();
	}

	function setRadiusDropdownOpenState(isOpen) {
		const modalElement = document.querySelector(modal.selectors.modal);
		if (!modalElement) {
			return;
		}

		modalElement.classList.toggle('is-radius-dropdown-open', !!isOpen);
	}

	function repositionRadiusDropdown() {
		if ( ! isRadiusMode || ! radiusPacContainer ) {
			return;
		}

		updateRadiusDropdownDimensions();
	}

	function updateRadiusDropdownDimensions() {
		if ( ! isRadiusMode || ! radiusPacContainer ) {
			return;
		}

		const input = document.querySelector(modal.selectors.radiusAddress);
		if (!input) {
			return;
		}

		const isMobile = window.innerWidth <= 1024;

		radiusPacContainer.classList.remove('foodord-pac-container--upward');
		
		if (isMobile) {
			radiusPacContainer.style.removeProperty('position');
			radiusPacContainer.style.removeProperty('top');
			radiusPacContainer.style.removeProperty('left');
			radiusPacContainer.style.removeProperty('width');
			radiusPacContainer.style.removeProperty('max-width');
			radiusPacContainer.style.removeProperty('min-width');
			radiusPacContainer.style.removeProperty('max-height');
			radiusPacContainer.style.removeProperty('overflow-y');
			radiusPacContainer.style.removeProperty('transform-origin');
			radiusPacContainer.style.removeProperty('margin-top');
		} else {
			radiusPacContainer.style.position = 'absolute';
			radiusPacContainer.style.top = (input.offsetHeight + 4) + 'px';
			radiusPacContainer.style.left = '0px';
			radiusPacContainer.style.width = '100%';
			radiusPacContainer.style.maxWidth = '100%';
			radiusPacContainer.style.minWidth = '100%';
			radiusPacContainer.style.maxHeight = '240px';
			radiusPacContainer.style.overflowY = 'auto';
			radiusPacContainer.style.transformOrigin = 'top center';
			radiusPacContainer.style.marginTop = '0';
		}

		scheduleFormatUpdate();
	}

	function applyRadiusDropdownBranding() {
		if ( ! radiusPacContainer ) {
			return;
		}
		radiusPacContainer.classList.add('foodord-pac-container');
		const logo = radiusPacContainer.querySelector('.pac-logo');
		if (logo && !logo.dataset.foodordStyled) {
			logo.dataset.foodordStyled = '1';
			logo.style.textAlign = 'left';
		}
	scheduleFormatUpdate();
	}

	function normalizeSuggestionFragment(text) {
		if (!text) {
			return '';
		}
		return text.replace(/\s*,\s*/g, ', ').replace(/\s+/g, ' ').trim();
	}

	function formatRadiusDropdownItems() {
		if ( ! radiusPacContainer ) {
			return;
		}
		const items = radiusPacContainer.querySelectorAll('.pac-item');
		if (!items.length) {
			return;
		}
		items.forEach(function (item) {
			formatRadiusDropdownItem(item);
		});
	}

	function formatRadiusDropdownItem(item) {
		if (!item) {
			return;
		}
	const childNodes = Array.from(item.childNodes).filter(function (node) {
		if (node.nodeType === 1 && node.classList.contains('pac-icon')) {
			return false;
		}
		return true;
	});

	let primary = null;
	const detailNodes = [];
	childNodes.forEach(function (node) {
		if (!primary && node.nodeType === 1 && node.classList.contains('pac-item-query')) {
			primary = node;
			return;
		}
		detailNodes.push(node);
	});

	if (!primary && detailNodes.length) {
		primary = detailNodes.shift();
	}

	const segments = [];
	const primaryTextRaw = primary ? primary.textContent || '' : '';
	const normalizedPrimary = normalizeSuggestionFragment(primaryTextRaw).replace(/,\s*$/, '');
	if (normalizedPrimary) {
		segments.push(normalizedPrimary);
	}
	const detailTexts = detailNodes.map(function (node) {
		const text = node.textContent || '';
		return normalizeSuggestionFragment(text).replace(/^,\s*/, '').replace(/,\s*$/, '');
	}).filter(Boolean);
	segments.push.apply(segments, detailTexts);

	const formatted = segments.join(', ');
	if (!formatted) {
		return;
	}
	if (item.dataset.foodordFormatHash === formatted) {
		return;
	}
	item.dataset.foodordFormatHash = formatted;
	item.textContent = formatted;

	if (typeof item.normalize === 'function') {
		item.normalize();
	}
	}



  function initialiseRadiusFeaturesWhenReady(retryCount) {
    if (!isRadiusMode) {
      return;
    }
    const input = document.querySelector(modal.selectors.radiusAddress);
    if (!input) {
      return;
    }
    if (typeof retryCount === 'undefined') {
      retryCount = 0;
    }
    if (!window.google || !window.google.maps || !window.google.maps.places) {
      if (retryCount > 20) {
        return;
      }
      setTimeout(function () { initialiseRadiusFeaturesWhenReady(retryCount + 1); }, 400);
      return;
    }
    if (radiusInitialised) {
      requestRadiusAutofillOnOpen();
      return;
    }
    radiusInitialised = true;

    radiusAutocomplete = new google.maps.places.Autocomplete(input, {
      types: ['address'],
      fields: ['geometry', 'formatted_address', 'address_components']
    });

	initRadiusClearControl(input);
	initRadiusCurrentLocationControl();

	    if (!radiusDropdownEventsBound) {
	      radiusDropdownEventsBound = true;
	      document.addEventListener('scroll', repositionRadiusDropdown, true);
	      document.addEventListener('pointerdown', handleRadiusOutsidePointerDown, true);
	      window.addEventListener('resize', repositionRadiusDropdown);
	      window.addEventListener('orientationchange', repositionRadiusDropdown);
	      if (window.visualViewport) {
	        window.visualViewport.addEventListener('resize', repositionRadiusDropdown);
	        window.visualViewport.addEventListener('scroll', repositionRadiusDropdown);
	      }
	    }

    input.addEventListener('focus', function () {
      if (!input.value.trim()) {
        hideRadiusDropdownIfInputEmpty(input);
        return;
      }
      ensureRadiusDropdownAttached();
      repositionRadiusDropdown();
    });

    input.addEventListener('click', function () {
      if (!input.value.trim()) {
        hideRadiusDropdownIfInputEmpty(input);
        return;
      }
      ensureRadiusDropdownAttached();
      repositionRadiusDropdown();
    });

    radiusAutocomplete.addListener('place_changed', function () {
      const place = radiusAutocomplete.getPlace();
      if (!place || !place.geometry || !place.geometry.location) {
        const coordsError = locationVars.labels && locationVars.labels.radius_coords_error ? locationVars.labels.radius_coords_error : 'Unable to determine coordinates for this address.';
        modal.setFeedback(coordsError, 'error');
        updateRadiusSaveButtonState();
        return;
      }

      const lat = place.geometry.location.lat();
      const lng = place.geometry.location.lng();

      applyRadiusSelection(buildRadiusSelectionFromGeocode(place, lat, lng));
      hideRadiusDropdown();
      updateRadiusSaveButtonState();
    });

    if (!input.dataset.wrcRadiusInputBound) {
      input.addEventListener('input', function () {
        $(modal.selectors.radiusLat).val('');
        $(modal.selectors.radiusLng).val('');
        $(modal.selectors.radiusCity).val('');
        $(modal.selectors.radiusPostal).val('');
        clearRadiusHouseNumber();
        radiusSelection = null;
        modal.setFeedback('', null);
        updateRadiusSaveButtonState();
        if (!input.value.trim()) {
          hideRadiusDropdownIfInputEmpty(input);
          return;
        }
        ensureRadiusDropdownAttached();
        repositionRadiusDropdown();
      });
      input.dataset.wrcRadiusInputBound = '1';
    }

    const houseNumberInput = document.querySelector(modal.selectors.radiusHouseNumber);
    if (houseNumberInput && !houseNumberInput.dataset.wrcRadiusStateBound) {
      houseNumberInput.addEventListener('input', updateRadiusSaveButtonState);
      houseNumberInput.dataset.wrcRadiusStateBound = '1';
    }

    const modalBody = document.querySelector('#foodord-location-modal .foodord-modal__body');
    if (modalBody && !modalBody.dataset.wrcRadiusScrollBound) {
      modalBody.addEventListener('scroll', function () {
        repositionRadiusDropdown();
      });
      modalBody.dataset.wrcRadiusScrollBound = '1';
    }

    const current = getCurrentRadiusLocation();
    if (current && current.allowed && Number.isFinite(current.lat) && Number.isFinite(current.lng)) {
      radiusSelection = {
        address: current.address || '',
        lat: current.lat,
        lng: current.lng,
        city: current.city || '',
        postal: current.postal || ''
      };
      populateRadiusFieldsFromSelection(radiusSelection, { fillInput: false });
      updateRadiusCurrentLocation(radiusSelection);
    }

    updateRadiusSaveButtonState();
    requestRadiusAutofillOnOpen();
  }

  // Helper functions defined outside document ready
  function getCookie(name){
    try {
      const v = document.cookie.split(';').map(s=>s.trim()).find(s=>s.startsWith(name+'='));
      return v ? decodeURIComponent(v.split('=')[1]) : null;
    } catch { return null; }
  }
  function clearLocationCookies(){
    try { document.cookie = 'foodord_location_ok=; path=/; max-age=0'; } catch{ /* ignored */ }
    try { document.cookie = 'foodord_location=; path=/; max-age=0'; } catch{ /* ignored */ }
    try { window.FOODORD_LOCATION_OK = 0; } catch{ /* ignored */ }
  }
  
  // Global current mode (updated immediately on toggle)
  let currentOrderMode = 'delivery';
  if (window.foodord_location_vars && window.foodord_location_vars.mode) {
    currentOrderMode = window.foodord_location_vars.mode;
  } else if (window.FoodordDeliveryPickup && window.FoodordDeliveryPickup.currentMode) {
    currentOrderMode = window.FoodordDeliveryPickup.currentMode;
  }
  
  // Listen for mode changes immediately
  document.addEventListener('wrc:deliveryModeChange', function (evt) {
    if (evt && evt.detail && evt.detail.mode) {
      currentOrderMode = evt.detail.mode;
    }
  });
  
  // Also check mode from active toggle button
  function checkModeFromToggle() {
    try {
      const activeBtn = document.querySelector('.wr-card__mode-btn.is-active');
      if (activeBtn && activeBtn.dataset.mode) {
        const btnMode = activeBtn.dataset.mode;
        if ((btnMode === 'delivery' || btnMode === 'pickup') && currentOrderMode !== btnMode) {
          currentOrderMode = btnMode;
        }
      }
    } catch { /* ignore */ }
  }
  
  // Check toggle state periodically
  setInterval(checkModeFromToggle, 100);
  
  // Listen to click events on toggle buttons directly
  document.addEventListener('click', function(e) {
    if (e.target && e.target.closest) {
      const btn = e.target.closest('.wr-card__mode-btn');
      if (btn && btn.dataset.mode) {
        if (btn.disabled || btn.classList.contains('is-closed') || btn.getAttribute('aria-disabled') === 'true') {
          return;
        }
        const mode = btn.dataset.mode;
        if (mode === 'delivery' || mode === 'pickup') {
          currentOrderMode = mode;
        }
      }
    }
  }, true);

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

  function resolveModeForTrigger(trigger) {
    try {
      const candidate = trigger && trigger.element ? trigger.element : null;
      if (candidate && typeof candidate.closest === 'function') {
        const card = candidate.closest('.wr-card');
        if (card) {
          if (card.classList.contains('is-pickup')) {
            return 'pickup';
          }
          if (card.classList.contains('is-delivery')) {
            return 'delivery';
          }
        }
      }
      return normalizeModeValue(currentOrderMode);
    } catch {
      return normalizeModeValue(currentOrderMode);
    }
  }

  function isStoreOpenForMode(mode) {
    try {
      const normalized = normalizeModeValue(mode);
      const status = window.FoodordStoreStatus || null;
      if (status && status.modes && typeof status.modes === 'object') {
        const data = status.modes[normalized];
        if (data) {
          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 (status && typeof status.isOpen === 'boolean') {
        return status.isOpen;
      }
      return true;
    } catch {
      return true;
    }
  }

  function handleStoreClosedEvent(event, mode) {
    try {
      if (event) {
        if (typeof event.preventDefault === 'function') { event.preventDefault(); }
        if (typeof event.stopPropagation === 'function') { event.stopPropagation(); }
        if (typeof event.stopImmediatePropagation === 'function') { event.stopImmediatePropagation(); }
      }
      if (window.FoodordStoreStatusToast && typeof window.FoodordStoreStatusToast.show === 'function') {
        window.FoodordStoreStatusToast.show(normalizeModeValue(mode));
        return;
      }
      const fallbackMessage = (window.FoodordStoreStatus && window.FoodordStoreStatus.message) ? window.FoodordStoreStatus.message : 'We are currently closed.';
      if (typeof window.alert === 'function') {
        window.alert(fallbackMessage);
      }
    } catch { /* ignored */ }
  }
  
  // Define foodordHasLocation function early
  window.foodordHasLocation = function () {
    try {
      const mode = (window.foodord_location_vars && window.foodord_location_vars.mode) || 'delivery';
      if (mode === 'pickup') {
        return true; // no address required for pickup
      }
      const configuredDeliveryMode = (window.foodord_location_vars && window.foodord_location_vars.delivery_mode) || deliveryMode || 'postal';
      const curWrap = (window.foodord_location_vars && window.foodord_location_vars.current) || {};
      const hasCur = !!(curWrap && typeof curWrap === 'object');
      const curAllowed = hasCur && (curWrap.allowed === true || curWrap.allowed === '1' || curWrap.allowed === 1);
      // If server explicitly says not allowed, prefer that over cookies and clear any stale cookies
      if (hasCur && !curAllowed) {
        clearLocationCookies();
        return false;
      }
		if (hasCur && curAllowed) {
			if ('radius' === configuredDeliveryMode) {
          const hasCoords = typeof curWrap.lat === 'number' && !Number.isNaN(curWrap.lat) && typeof curWrap.lng === 'number' && !Number.isNaN(curWrap.lng);
          if (hasCoords && curWrap.address) {
            return true;
          }
			} else if (curWrap.city) {
          return true;
        }
      }
      const ok = getCookie('foodord_location_ok');
      if (ok === '1') {
        return true;
      }
      // Optionally parse full cookie if exists
      const locRaw = getCookie('foodord_location');
      if (locRaw) {
        try {
          const obj = JSON.parse(locRaw);
          if (obj && obj.allowed === true) {
			if ('radius' === configuredDeliveryMode) {
              const hasCoords = typeof obj.lat === 'number' && !Number.isNaN(obj.lat) && typeof obj.lng === 'number' && !Number.isNaN(obj.lng);
              if (hasCoords && obj.address) {
                return true;
              }
			} else if (obj.city) {
              return true;
            }
          }
        } catch {}
      }
      return false;
    } catch { 
      return false; 
    }
  };

  // Helper: should we gate this event due to missing location in delivery mode?
  function shouldGateForLocation(modeArg) {
    try {
      const mode = normalizeModeValue(modeArg || currentOrderMode);
      if (mode === 'pickup') {
        return false;
      }
      if (!isStoreOpenForMode(mode)) {
        return false;
      }
      const hasLocation = window.foodordHasLocation && window.foodordHasLocation();
      return !hasLocation;
    } catch { 
      return false; 
    }
  }

  function findLocationTrigger(target) {
    try {
      if (!target || typeof target.closest !== 'function') {
        return null;
      }

      const addressTrigger = target.closest('[data-foodord-location-trigger], .wr-card__address-bar, .wr-card__address-change');
      if (addressTrigger) {
        return { element: addressTrigger, type: 'address' };
      }

      if (target.closest('.wr-card')) {
        return null;
      }

      const productSelectors = [
        '.foodord-product-card',
        '.foodord-product-card .product-actions .button',
        '.foodord-product-card .product-actions .add_to_cart_button',
        '.foodord-product-card .foodord-direct-add-button',
        '.foodord-products-shortcode .product',
        '.foodord-products-shortcode .add_to_cart_button',
        '.wc-block-grid__product',
        '.wc-block-components-product-add-to-cart-button',
        '.woocommerce ul.products li.product',
        '.woocommerce ul.products li.product a.button',
        '.woocommerce ul.products li.product button',
        '.add_to_cart_button',
        '.ajax_add_to_cart',
        '.single_add_to_cart_button',
        'button[name="add-to-cart"]',
        'input[name="add-to-cart"]',
        'a[href*="add-to-cart="]',
        '[data-foodord-product-trigger]'
      ];

      for (let i = 0; i < productSelectors.length; i++) {
        const match = target.closest(productSelectors[i]);
        if (match) {
          return { element: match, type: 'product' };
        }
      }

      if (target.matches && target.matches('form.cart')) {
        return { element: target, type: 'product' };
      }

      const formCart = target.closest('form.cart');
      if (formCart) {
        return { element: formCart, type: 'product' };
      }

      return null;
    } catch {
      return null;
    }
  }

  function isUnavailableProductCard(target) {
    try {
      if (!target || typeof target.closest !== 'function') {
        return false;
      }

      const card = target.closest('.foodord-product-card');
      if (!card) {
        return false;
      }

      const availabilityFlag = String(card.getAttribute('data-foodord-available') || '').toLowerCase();
      return card.classList.contains('foodord-product-card--unavailable')
        || availabilityFlag === '0'
        || availabilityFlag === 'false'
        || availabilityFlag === 'no';
    } catch {
      return false;
    }
  }

  function blockUnavailableProductEvent(event) {
    if (!event) {
      return;
    }

    const card = event.target && typeof event.target.closest === 'function'
      ? event.target.closest('.foodord-product-card')
      : null;

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

  function showUnavailableProductToast(source) {
    if (window.FoodordStoreStatusToast && typeof window.FoodordStoreStatusToast.showUnavailableProduct === 'function') {
      window.FoodordStoreStatusToast.showUnavailableProduct(source);
    }
  }

  function getProductCardFromLocationTrigger(trigger) {
    if (!trigger || !trigger.element || typeof trigger.element.closest !== 'function') {
      return null;
    }

    return trigger.element.closest('.foodord-product-card');
  }

  function queuePendingProductModalRequest(trigger) {
    const productCard = getProductCardFromLocationTrigger(trigger);
    if (!productCard) {
      pendingProductModalRequest = null;
      return;
    }
    if (
      (productCard.dataset && productCard.dataset.foodordDirectAdd === '1') ||
      (trigger.element.closest && trigger.element.closest('[data-foodord-direct-add="1"]'))
    ) {
      pendingProductModalRequest = null;
      return;
    }

    const productId = parseInt(productCard.getAttribute('data-product-id'), 10) || 0;
    if (!productId) {
      pendingProductModalRequest = null;
      return;
    }

    pendingProductModalRequest = {
      productId: productId,
      trigger: productCard
    };
  }

  function clearPendingProductModalRequest() {
    pendingProductModalRequest = null;
  }

  function flushPendingProductModalRequest() {
    const request = pendingProductModalRequest;
    pendingProductModalRequest = null;

    if (!request || !request.productId) {
      return;
    }

    window.setTimeout(function () {
      try {
        if (typeof window.foodordHasLocation === 'function' && !window.foodordHasLocation()) {
          return;
        }
        if (!window.foodordModal || typeof window.foodordModal.openModal !== 'function') {
          return;
        }

        const trigger = request.trigger && document.contains(request.trigger) ? request.trigger : null;
        window.foodordModal.openModal(request.productId, trigger ? { trigger: trigger } : {});
      } catch { /* ignored */ }
    }, 120);
  }

  // Install global click interceptor immediately (before document ready)
  // This ensures it runs before other scripts that might be in document.ready
  function installClickInterceptor() {

    // Global gate: if no address, intercept product card or add-to-cart clicks and open modal instead
    document.addEventListener('click', function (e) {
      try {
        if (isUnavailableProductCard(e.target)) {
          blockUnavailableProductEvent(e);
          return;
        }

        const trigger = findLocationTrigger(e.target);
        if (!trigger) {
          return;
        }
        if (trigger.type === 'address') {
          if (e && typeof e.preventDefault === 'function') e.preventDefault();
          if (e && typeof e.stopPropagation === 'function') e.stopPropagation();
          if (e && typeof e.stopImmediatePropagation === 'function') e.stopImmediatePropagation();
          clearPendingProductModalRequest();
          modal.open();
          return;
        }
        const interactionMode = resolveModeForTrigger(trigger);
        if (!isStoreOpenForMode(interactionMode)) {
          handleStoreClosedEvent(e, interactionMode);
          return;
        }
        if (!shouldGateForLocation(interactionMode)) {
          return;
        }
        const isInsideProductModal = e.target.closest && e.target.closest('.foodord-product-modal, .product-modal, [data-modal="product"]');
        if (isInsideProductModal) {
          return;
        }
        if (e && typeof e.preventDefault === 'function') e.preventDefault();
        if (e && typeof e.stopPropagation === 'function') e.stopPropagation();
        if (e && typeof e.stopImmediatePropagation === 'function') e.stopImmediatePropagation();
        queuePendingProductModalRequest(trigger);

        // Ensure modal object exists before trying to open it
        if (modal && typeof modal.open === 'function') {
          modal.open();
        } else {
          // Fallback: try global function
          if (window.foodordOpenLocationModal) {
            window.foodordOpenLocationModal();
          }
        }
      } catch { 
        // Silently handle errors to prevent breaking other functionality
      }
    }, true); // capture phase - earliest possible
  }
  
  // Install immediately
  installClickInterceptor();
  document.addEventListener('foodord:locationSelected', flushPendingProductModalRequest);

  $(document).ready(function () {
    modal.el = $(modal.selectors.modal);

    // Expose minimal API for other scripts
    window.foodordOpenLocationModal = function () { modal.open(); };

    if (isRadiusMode) {
      initialiseRadiusFeaturesWhenReady();
      $(modal.selectors.radiusAddress).on('keydown', function (e) {
        if (e.key === 'Enter') {
          e.preventDefault();
          handleSave();
        }
      });
    } else {
      initLocationCustomDropdown();
    }


    // If server says not allowed on load, clear any stale cookies
    try {
      const cur = (window.foodord_location_vars && window.foodord_location_vars.current) || {};
      const allowed = !!(cur && (cur.allowed === true || cur.allowed === '1' || cur.allowed === 1));
      if (!allowed) { clearLocationCookies(); }
} catch (e) { /* no-op */ void e; }

    // Do not auto-open on load; open on interactions (clicks or delivery toggle).

    // Intercept form submits (single product pages)
    document.addEventListener('submit', function(e){
      try {
        const trigger = findLocationTrigger(e && e.target);
        if (!trigger) { return; }
        if (trigger.type === 'address') {
          modal.open();
          return;
        }
        const interactionMode = resolveModeForTrigger(trigger);
        if (!isStoreOpenForMode(interactionMode)) {
          handleStoreClosedEvent(e, interactionMode);
          return;
        }
        if (!shouldGateForLocation(interactionMode)) { return; }
        if (e && typeof e.preventDefault === 'function') e.preventDefault();
        if (e && typeof e.stopPropagation === 'function') e.stopPropagation();
        if (e && typeof e.stopImmediatePropagation === 'function') e.stopImmediatePropagation();
        modal.open();
      } catch{ /* ignored */ }
    }, true);

    // Defensive: intercept WooCommerce adding_to_cart jQuery event if available
    try {
      if (typeof jQuery !== 'undefined') {
        jQuery(document.body).on('adding_to_cart', function(evt){
          try {
            const trigger = findLocationTrigger(evt && evt.target);
            if (!trigger) { return; }
            if (trigger.type === 'address') {
              modal.open();
              return;
            }
            const interactionMode = resolveModeForTrigger(trigger);
            if (!isStoreOpenForMode(interactionMode)) {
              handleStoreClosedEvent(evt, interactionMode);
              return;
            }
            if (!shouldGateForLocation(interactionMode)) { return; }
            if (evt && typeof evt.preventDefault === 'function') evt.preventDefault();
            if (evt && typeof evt.stopPropagation === 'function') evt.stopPropagation();
            modal.open();
          } catch{ /* ignored */ }
        });
      }
} catch { }

    $(document).on('click', modal.selectors.close + ',' + modal.selectors.cancel, function (e) {
      if (e && typeof e.preventDefault === 'function') e.preventDefault();
      try { this.blur && this.blur(); } catch { /* ignored */ }
      clearPendingProductModalRequest();
      modal.close();
    });

    $(document).on('click', modal.selectors.save, function () {
      handleSave();
    });

    // Close when clicking outside of content
    $(document).on('click', function (e) {
      if (!$(e.target).closest('#foodord-location-modal .foodord-ttd__dropdown').length) {
        closeLocationDropdowns();
      }

      const $m = $(modal.selectors.modal);
      if ($m.length && $m.hasClass('is-open')) {
        const content = $m.find('.foodord-modal__content')[0];
        if (content && !content.contains(e.target) && e.target.id === 'foodord-location-modal') {
          clearPendingProductModalRequest();
          modal.close();
        }
      }
    });

    // Listen to delivery/pickup toggle changes to keep mode in sync at runtime
    document.addEventListener('wrc:deliveryModeChange', function (evt) {
      try {
        const m = evt && evt.detail && evt.detail.mode ? String(evt.detail.mode) : '';
        if (m === 'delivery' || m === 'pickup') {
          if (typeof window.foodord_location_vars === 'undefined') { window.foodord_location_vars = {}; }
          window.foodord_location_vars.mode = m;
			if (m === 'delivery') {
				const cur = (window.foodord_location_vars.current) || {};
				const need = !cur.city || !(cur.allowed === true || cur.allowed === '1' || cur.allowed === 1);
            if (need) {
              const $m = $("#foodord-location-modal");
              const isOpen = $m && $m.hasClass('is-open');
              if (!isOpen) {
                setTimeout(function(){ try { if (window.foodordOpenLocationModal) { window.foodordOpenLocationModal(); } } catch{ /* ignored */ } }, 50);
              }
            }
          }
        }
      } catch { /* no-op */ }
    });

    // ESC key closes modal
    $(document).on('keydown', function (e) {
      if (e.key === 'Escape') {
        clearPendingProductModalRequest();
        modal.close();
      }
    });
  });
})(jQuery);
