
function isRadiusDeliveryMode() {
  try {
    return !!(window.foodord_location_vars && window.foodord_location_vars.delivery_mode === 'radius');
  } catch {
    return false;
  }
}

function extractStreetLine(raw) {
  if (!raw) return '';
  try {
    const str = String(raw);
    const firstLine = str.split('\n')[0];
    const firstSegment = firstLine.split(',')[0].trim();
    if (firstSegment) {
      return firstSegment;
    }
    return firstLine.trim();
  } catch {
    return String(raw);
  }
}

(function ($) {
'use strict';


  function setIfDifferent($el, value) {
    if (!$el || !$el.length) return false;
    const cur = ($el.val() || '').toString();
    if (cur === value) return false;
    $el.val(value);
    try { $el.trigger('input'); } catch { /* ignore */ }
    try { $el.trigger('change'); } catch { /* ignore */ }
    return true;
  }

  function fillCheckoutFields(city, postal, address) {
    const rawAddress = address ? address.toString() : '';
    let trimmedAddress = rawAddress;
    if (isRadiusDeliveryMode()) {
      const street = extractStreetLine(rawAddress);
      if (street) {
        trimmedAddress = street;
      }
    }
    const data = {
      city: city ? city.toString() : '',
      postal: postal ? postal.toString() : '',
      address: trimmedAddress
    };

    if (!data.city && !data.postal && !data.address) {
      return false;
    }

    if (data.city) {
      data.city = data.city.charAt(0).toUpperCase() + data.city.slice(1).toLowerCase();
    }

    const isBlocks = document.querySelector('.wp-block-woocommerce-checkout, .wc-block-checkout');
    if (isBlocks) {
      const storeUpdated = updateViaStoreAPI(data);
      enforceBlocksValues(data);
      return storeUpdated;
    }

    let changed = false;
    const $billingCity = $('#billing_city');
    const $billingPost = $('#billing_postcode');
    const $billingAddress = $('#billing_address_1');

    if ($billingCity.length || $billingPost.length || $billingAddress.length) {
      changed = setIfDifferent($billingCity, data.city) || changed;
      changed = setIfDifferent($billingPost, data.postal) || changed;
      changed = setIfDifferent($billingAddress, data.address) || changed;

      const shipDiffChecked = $('#ship-to-different-address input').is(':checked');
      if (shipDiffChecked) {
        const $shippingCity = $('#shipping_city');
        const $shippingPost = $('#shipping_postcode');
        const $shippingAddress = $('#shipping_address_1');
        changed = setIfDifferent($shippingCity, data.city) || changed;
        changed = setIfDifferent($shippingPost, data.postal) || changed;
        changed = setIfDifferent($shippingAddress, data.address) || changed;
      }

      if (changed && typeof jQuery !== 'undefined') {
        try { jQuery(document.body).trigger('update_checkout'); } catch { /* ignore */ }
      }
      return changed;
    }

    const storeUpdated = updateViaStoreAPI(data);
    tryDomForBlocks(data);
    return storeUpdated;
  }

  // WooCommerce Blocks Store API helper
  function updateViaStoreAPI(data) {
    try {
      const hasWP = typeof window.wp !== 'undefined' && wp.data && wp.data.select && wp.data.dispatch;
      if (!hasWP) { 
        return false; 
      }
      
      const sel = wp.data.select('wc/store/checkout');
      const disp = wp.data.dispatch('wc/store/checkout');
      
      if (!sel || !disp || typeof disp.setBillingAddress !== 'function') { 
        return false; 
      }

      const billing = (typeof sel.getBillingAddress === 'function') ? (sel.getBillingAddress() || {}) : {};
      const shipping = (typeof sel.getShippingAddress === 'function') ? (sel.getShippingAddress() || {}) : {};

      const newBilling = Object.assign({}, billing, { 
        address_1: data.address || billing.address_1 || '',
        city: data.city || billing.city || '', 
        postcode: data.postal || billing.postcode || '' 
      });
      
      const newShipping = Object.assign({}, shipping, { 
        address_1: data.address || shipping.address_1 || '',
        city: data.city || shipping.city || '', 
        postcode: data.postal || shipping.postcode || '' 
      });

      disp.setBillingAddress(newBilling);
      disp.setShippingAddress(newShipping);
      
      return true;
    } catch {
      return false;
    }
  }

  // Persistent enforcer: beat hydration/rerenders for a short time
  function enforceBlocksValues(data){
    if (data.city) {
      data.city = data.city.charAt(0).toUpperCase() + data.city.slice(1).toLowerCase();
    }
    const city = data.city;
    const postal = data.postal;
    const address = data.address;

    let tries = 0;
    const MAX = 30; // ~6s (30*200ms) - increased
    const timer = setInterval(function(){
      tries++;
      // Direct IDs seen in your DOM
      const byIdCity = document.getElementById('billing-city');
      const byIdPost = document.getElementById('billing-postcode');
      const byIdAddress = document.getElementById('billing-address-1');
      let changed = false;
      
      // Use native setter for React
      if (byIdCity && String(byIdCity.value) !== String(city)) { 
        setReactValue(byIdCity, city); 
        changed = true; 
      }
      if (byIdPost && String(byIdPost.value) !== String(postal)) { 
        setReactValue(byIdPost, postal); 
        changed = true; 
      }
      if (byIdAddress && String(byIdAddress.value) !== String(address)) {
        setReactValue(byIdAddress, address); 
        changed = true;
      }

      // Also try shipping fields
      const shipCity = document.getElementById('shipping-city');
      const shipPost = document.getElementById('shipping-postcode');
      const shipAddress = document.getElementById('shipping-address-1');
      if (shipCity && String(shipCity.value) !== String(city)) { 
        setReactValue(shipCity, city); 
        changed = true; 
      }
      if (shipPost && String(shipPost.value) !== String(postal)) { 
        setReactValue(shipPost, postal); 
        changed = true; 
      }
      if (shipAddress && String(shipAddress.value) !== String(address)) {
        setReactValue(shipAddress, address);
        changed = true;
      }

      // Also try generic selectors in case IDs differ
      if (!byIdCity) {
        const cgen = document.querySelector('input[autocomplete="address-level2"], input[name*="city"], input[id*="city"]');
        if (cgen && String(cgen.value) !== String(city)) { setReactValue(cgen, city); changed = true; }
      }
      if (!byIdPost) {
        const pgen = document.querySelector('input[autocomplete="postal-code"], input[name*="post"], input[id*="post"]');
        if (pgen && String(pgen.value) !== String(postal)) { setReactValue(pgen, postal); changed = true; }
      }
      if (!byIdAddress) {
        const agen = document.querySelector('input[autocomplete="address-line1"], input[name*="address"], input[id*="address"]');
        if (agen && String(agen.value) !== String(address)) { setReactValue(agen, address); changed = true; }
      }

      if (changed) { 
        try { 
          // Also update via WC Blocks Store API
          if (window.wp && wp.data && wp.data.dispatch('wc/store/checkout')) {
            const disp = wp.data.dispatch('wc/store/checkout');
            disp.setBillingAddress({ address_1: address, city: city, postcode: postal });
            disp.setShippingAddress({ address_1: address, city: city, postcode: postal });
          }
          jQuery && jQuery(document.body).trigger('update_checkout'); 
        } catch { /* ignore */ }
      }
      
      // Stop when both match or when max tries reached
      const okCity = byIdCity ? (String(byIdCity.value) === String(city)) : true;
      const okPost = byIdPost ? (String(byIdPost.value) === String(postal)) : true;
      const okAddress = byIdAddress ? (String(byIdAddress.value) === String(address)) : true;
      if ((okCity && okPost && okAddress) || tries >= MAX) { 
        clearInterval(timer); 
      }
    }, 200);
  }

  // Last resort: interact with Blocks DOM inputs via autocomplete attributes
  function focusWithoutScroll(el){
    if (!el || typeof el.focus !== 'function') return;
    const scrollX = window.pageXOffset || document.documentElement.scrollLeft || 0;
    const scrollY = window.pageYOffset || document.documentElement.scrollTop || 0;
    try {
      el.focus({ preventScroll: true });
      return;
    } catch { /* ignore */ }
    try {
      el.focus();
      window.scrollTo(scrollX, scrollY);
    } catch { /* ignore */ }
  }

  function setInputValue(el, val){
    if (!el) return false;
    if (String(el.value) === String(val)) return false;
    focusWithoutScroll(el);
    el.value = val || '';
    try { el.dispatchEvent(new Event('input', { bubbles: true })); } catch { /* ignore */ }
    try { el.dispatchEvent(new Event('change', { bubbles: true })); } catch { /* ignore */ }
    try { el.dispatchEvent(new Event('blur', { bubbles: true })); } catch { /* ignore */ }
    return true;
  }

  function typeInto(el, val){
    if (!el) return false;
    focusWithoutScroll(el);
    el.value = '';
    const s = String(val || '');
    for (let i=0;i<s.length;i++){
      el.value += s.charAt(i);
      try { el.dispatchEvent(new Event('input', { bubbles: true })); } catch { /* ignore */ }
    }
    try { el.dispatchEvent(new Event('change', { bubbles: true })); } catch { /* ignore */ }
    try { el.dispatchEvent(new Event('blur', { bubbles: true })); } catch { /* ignore */ }
    return true;
  }

  // Special setter for React controlled inputs
  function setReactValue(element, value) {
    if (!element) return false;
    
    // Use native setter for React 16+
    const valueSetter = Object.getOwnPropertyDescriptor(element.constructor.prototype, 'value').set;
    const prototype = Object.getPrototypeOf(element);
    const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
    
    if (valueSetter && valueSetter !== prototypeValueSetter) {
      prototypeValueSetter.call(element, value);
    } else {
      valueSetter.call(element, value);
    }
    
    // Trigger all events
    element.dispatchEvent(new Event('input', { bubbles: true }));
    element.dispatchEvent(new Event('change', { bubbles: true }));
    element.dispatchEvent(new Event('blur', { bubbles: true }));
    
    // Focus/blur cycle helps React capture the update
    try {
      focusWithoutScroll(element);
      element.blur();
    } catch { /* ignore */ }
    
    return true;
  }

function tryDomForBlocks(data, attempt){
    attempt = typeof attempt === 'number' ? attempt : 0;
    const MAX_ATTEMPTS = 12; // ~3s total (12 * 250ms)
    try {
      let changed = false;

      // Billing containers (wide selection for various versions)
      const billingRoots = document.querySelectorAll('.wc-block-checkout__billing-fields, .wc-block-components-address-form--billing, .wc-block-components-address-form');
      let billCity = null, billPost = null, billAddress = null;
      billingRoots.forEach(function(root){
        if (!billCity) billCity = root.querySelector('input[autocomplete="address-level2"], input[name="city"], input[name="billing_city"], input[id*="city"]');
        if (!billPost) billPost = root.querySelector('input[autocomplete="postal-code"], input[name="postcode"], input[name="billing_postcode"], input[id*="postal"], input[id*="postcode"]');
        if (!billAddress) billAddress = root.querySelector('input[autocomplete="address-line1"], input[name="address_1"], input[name="billing_address_1"], input[id*="address"]');
      });
      // Last resort: first match in the entire page
      if (!billCity) billCity = document.querySelector('input[autocomplete="address-level2"], input[name="city"], input[name="billing_city"], input[id*="city"]');
      if (!billPost) billPost = document.querySelector('input[autocomplete="postal-code"], input[name="postcode"], input[name="billing_postcode"], input[id*="postal"], input[id*="postcode"]');
      if (!billAddress) billAddress = document.querySelector('input[autocomplete="address-line1"], input[name="address_1"], input[name="billing_address_1"], input[id*="address"]');

      const c1 = setInputValue(billCity, data.city); changed = c1 || changed;
      const c2 = setInputValue(billPost, data.postal); changed = c2 || changed;
      const c3 = setInputValue(billAddress, data.address); changed = c3 || changed;
      if (!c1 && billCity && String(billCity.value) !== String(data.city)) { typeInto(billCity, data.city); changed = true; }
      if (!c2 && billPost && String(billPost.value) !== String(data.postal)) { typeInto(billPost, data.postal); changed = true; }
      if (!c3 && billAddress && String(billAddress.value) !== String(data.address)) { typeInto(billAddress, data.address); changed = true; }

      // Shipping (if exists)
      const shipRoots = document.querySelectorAll('.wc-block-checkout__shipping-fields, .wc-block-components-address-form--shipping, .wc-block-components-shipping-address');
      shipRoots.forEach(function(root){
        const sc = root.querySelector('input[autocomplete="address-level2"], input[name="city"], input[id*="city"]');
        const sp = root.querySelector('input[autocomplete="postal-code"], input[name="postcode"], input[id*="postal"], input[id*="postcode"]');
        const sa = root.querySelector('input[autocomplete="address-line1"], input[name="address_1"], input[id*="address"]');
        const cs = setInputValue(sc, data.city); changed = cs || changed;
        const ps = setInputValue(sp, data.postal); changed = ps || changed;
        const as = setInputValue(sa, data.address); changed = as || changed;
        if (!cs && sc && String(sc.value) !== String(data.city)) { typeInto(sc, data.city); changed = true; }
        if (!ps && sp && String(sp.value) !== String(data.postal)) { typeInto(sp, data.postal); changed = true; }
        if (!as && sa && String(sa.value) !== String(data.address)) { typeInto(sa, data.address); changed = true; }
      });

      // Retry if values didn't stick or fields haven't mounted yet
      let needRetry = false;
      if (billCity && data.city && billCity.value !== String(data.city)) needRetry = true;
      if (billPost && data.postal && billPost.value !== String(data.postal)) needRetry = true;
      if (billAddress && data.address && billAddress.value !== String(data.address)) needRetry = true;
      if ((!billCity || !billPost || !billAddress) && attempt < MAX_ATTEMPTS) needRetry = true;

      if (needRetry && attempt < MAX_ATTEMPTS) {
        setTimeout(function(){ tryDomForBlocks(data, attempt + 1); }, 250);
      }

      // Some setups may need to trigger totals recalculation
      try { jQuery && jQuery(document.body).trigger('update_checkout'); } catch { /* ignore */ }
      return changed;
    } catch {
      if (attempt < MAX_ATTEMPTS) {
        setTimeout(function(){ tryDomForBlocks(data, attempt + 1); }, 250);
      }
      return false;
    }
  }

function getCurrentFromVars() {
    try {
      const cur = (window.foodord_location_vars && window.foodord_location_vars.current) || {};
      let city = (cur.city || '').toString();
      let postal = (cur.postal || '').toString();
      let address = (cur.address || '').toString();
      let allowed = !!(cur && (cur.allowed === true || cur.allowed === '1' || cur.allowed === 1));
      // Fallback to cookie if not allowed
      if (!allowed) {
        try {
          const c = getCookie('foodord_location');
          if (c) {
            const obj = JSON.parse(c);
            if (obj && obj.allowed === true) {
              city = (obj.city || '').toString();
              postal = (obj.postal || '').toString();
              address = (obj.address || '').toString();
              allowed = true;
            }
          }
        } catch { /* ignore */ }
      }
      return { city: city, postal: postal, address: address, allowed: allowed };
    } catch { return { city: '', postal: '', address: '', allowed: false }; }
  }

  function getCookie(name){
    try { 
      const v = document.cookie.split(';').map(function(s){return s.trim();}).find(function(s){return s.indexOf(name+'=')===0;}); 
      return v ? decodeURIComponent(v.split('=')[1]) : null; 
    } catch { 
      return null; 
    } 
  }

  function initPrefillOnLoad() {
    // Prefill on load only if fields are empty to avoid overriding user's manual edits
    const cur = getCurrentFromVars();
    if (!cur.allowed) { return; }

    const $billingAddress = $('#billing_address_1');
    const currentBillingAddress = ($billingAddress.val() || '').toString().trim();
    const trimmed = isRadiusDeliveryMode() ? extractStreetLine(cur.address) : cur.address;

    const needCity = ($('#billing_city').val() || '').toString().trim() === '';
    const needPost = ($('#billing_postcode').val() || '').toString().trim() === '';
    const needAddress = currentBillingAddress === '';
    const addressMismatch = isRadiusDeliveryMode() && trimmed && currentBillingAddress && currentBillingAddress !== trimmed;

    if (needCity || needPost || needAddress || addressMismatch) {
      fillCheckoutFields(cur.city, cur.postal, cur.address);
    }
  }

  // On event from location modal, immediately write values to the form
  document.addEventListener('foodord:locationSelected', function (evt) {
    try {
      const d = (evt && evt.detail) || {};
      const cc = d.city || '';
      const pp = d.postal || '';
      const aa = d.address || '';
      fillCheckoutFields(cc, pp, aa);
    } catch { /* no-op */ }
  });

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