(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) {
		return a.radius - b.radius;
	}) : [];
	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 radiusPacContainer = null;
	let radiusDropdownEventsBound = false;
	let radiusDropdownObserver = null;
	let radiusFormatDebounce = null;
	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');
		}
	}

	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('');
			} 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();
	}

  const modal = {
    el: null,
    lastFocus: 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',
      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) {
        // Remember previously focused element to restore on close
        this.lastFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
        $m.addClass('is-open').attr('aria-hidden', 'false').removeAttr('inert');
        $('body').css('overflow', 'hidden');
        if (isRadiusMode) {
          initialiseRadiusFeaturesWhenReady();
        }
        // Focus first field for a11y
		const focusSelector = isRadiusMode ? this.selectors.radiusAddress : '#foodord-location-modal .foodord-ttd__trigger';
        const $field = $(focusSelector);
        if ($field.length) {
try { $field.trigger('focus'); } catch { }
        } else {
try { $(this.selectors.save).trigger('focus'); } catch { }
        }
        if (isRadiusMode) {
    ensureRadiusDropdownAttached();
    repositionRadiusDropdown();
			updateRadiusClearState();
        }
		}
    },
    close() {
      const $m = $(this.selectors.modal);
      if ($m.length) {
        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; }
        }

        // Defer hiding to next frame to ensure the focus move is applied first
        const hide = () => {
          $m.removeClass('is-open').attr('aria-hidden', 'true').attr('inert', '');
          $('body').css('overflow', '');
          $(this.selectors.feedback).text('');
          $(this.selectors.radiusFeedback).text('');
          if (radiusPacContainer) {
            radiusPacContainer.style.display = 'none';
          }
			if (radiusDropdownObserver) {
				radiusDropdownObserver.disconnect();
				radiusDropdownObserver = null;
			}
			radiusPacContainer = null;
        };
        if (typeof window.requestAnimationFrame === 'function') {
          window.requestAnimationFrame(hide);
        } else {
          setTimeout(hide, 0);
        }
      }
    },
	    setFeedback(msg, type) {
      const targetSelector = isRadiusMode ? this.selectors.radiusFeedback : this.selectors.feedback;
      const $fb = $(targetSelector);
      if (!$fb.length) {
        return;
      }
      $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').prop('disabled', false).removeAttr('aria-busy');
  }

	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() {
    const address = $(modal.selectors.radiusAddress).val().trim();
    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;
    }

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

    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) {
            setSaveButtonLoadingState(false);
	          if (!resp || resp.success !== true) {
	            modal.setFeedback((locationVars.labels && locationVars.labels.fail) || 'Address not in delivery area.', 'error');
	            return;
          }
          const data = resp.data || {};
          if (data.allowed) {
            const distanceVal = typeof data.distance === 'number' ? data.distance : null;
            let successMsg = (locationVars.labels && locationVars.labels.success) || 'Delivery available for this address.';
            if (distanceVal !== null) {
              successMsg += ' (' + distanceVal.toFixed(2) + ' km)';
            }
            modal.setFeedback(successMsg, 'success');
            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);
            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;
              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 {
            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: '' };
    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.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) {
    if (!selection) {
      return;
    }
    $(modal.selectors.radiusAddress).val(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;
    }

	setTimeout(function () {
		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 () {
					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.display = '';
			radiusPacContainer.style.visibility = 'visible';
			radiusPacContainer.style.pointerEvents = 'auto';
			radiusPacContainer.style.zIndex = '100000';
			applyRadiusDropdownBranding();
			updateRadiusDropdownDimensions();
			scheduleFormatUpdate();
			setTimeout(function () {
				updateRadiusDropdownDimensions();
				scheduleFormatUpdate();
			}, 50);
			setTimeout(function () {
				updateRadiusDropdownDimensions();
				scheduleFormatUpdate();
			}, 120);
		}
	}, 0);
	}

	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) {
      return;
    }
    radiusInitialised = true;

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

	initRadiusClearControl(input);

	    if (!radiusDropdownEventsBound) {
	      radiusDropdownEventsBound = true;
	      document.addEventListener('scroll', repositionRadiusDropdown, 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 () {
      ensureRadiusDropdownAttached();
      repositionRadiusDropdown();
    });

    input.addEventListener('click', function () {
      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');
        return;
      }

      const lat = place.geometry.location.lat();
      const lng = place.geometry.location.lng();
      const parts = extractAddressParts(place.address_components || []);
      const formatted = place.formatted_address || input.value;

      radiusSelection = {
        address: formatted,
        lat: lat,
        lng: lng,
        city: parts.city || '',
        postal: parts.postal || ''
      };

      populateRadiusFieldsFromSelection(radiusSelection);

		if (Number.isFinite(storeLat) && Number.isFinite(storeLng)) {
			const distance = haversineDistance(storeLat, storeLng, lat, lng);
			let matchedZone = null;
			if (radiusZones.length) {
				matchedZone = findMatchingRadiusZone(distance);
			} else if (maxRadiusKm > 0) {
				matchedZone = distance <= maxRadiusKm ? { radius: maxRadiusKm } : null;
			}
			if (matchedZone) {
				modal.setFeedback('', null);
			} else {
				const failText = (locationVars.labels && locationVars.labels.fail) ? locationVars.labels.fail : 'We do not deliver to this address.';
				modal.setFeedback(failText, 'error');
			}
		} else {
			modal.setFeedback('', null);
		}
    });

    if (!input.dataset.wrcRadiusInputBound) {
      input.addEventListener('input', function () {
        $(modal.selectors.radiusLat).val('');
        $(modal.selectors.radiusLng).val('');
        $(modal.selectors.radiusCity).val('');
        $(modal.selectors.radiusPostal).val('');
        radiusSelection = null;
        modal.setFeedback('', null);
        ensureRadiusDropdownAttached();
        repositionRadiusDropdown();
      });
      input.dataset.wrcRadiusInputBound = '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';
    }

    ensureRadiusDropdownAttached();
    repositionRadiusDropdown();

    const current = locationVars.current || {};
    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);
    }
  }

  // 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;
    }

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

  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);
