(function(){
  'use strict';

  const FIELDS = [
    {
      label: 'Billing Address 1',
      selectors: [
        '#billing_address_1_field','.form-row.billing_address_1','[data-field="address_1"].billing',
        '.wc-block-components-address-form__address_1','input#billing_address_1','input[name="billing_address_1"]'
      ]
    },
    {
      label: 'Billing City',
      selectors: [
        '#billing_city_field','.form-row.billing_city','[data-field="city"].billing',
        '.wc-block-components-address-form__city','input#billing_city','input[name="billing_city"]','input#billing-city'
      ]
    },
    {
      label: 'Billing Postcode',
      selectors: [
        '#billing_postcode_field','.form-row.billing_postcode','[data-field="postcode"].billing',
        '.wc-block-components-address-form__postcode','input#billing_postcode','input[name="billing_postcode"]','input#billing-postcode'
      ]
    },
    {
      label: 'Shipping Address 1',
      selectors: [
        '#shipping_address_1_field','.form-row.shipping_address_1','[data-field="address_1"].shipping',
        '.wc-block-components-address-form__address_1--shipping','input#shipping_address_1','input[name="shipping_address_1"]'
      ]
    },
    {
      label: 'Shipping City',
      selectors: [
        '#shipping_city_field','.form-row.shipping_city','[data-field="city"].shipping',
        '.wc-block-components-address-form__city--shipping','input#shipping_city','input[name="shipping_city"]','input#shipping-city'
      ]
    },
    {
      label: 'Shipping Postcode',
      selectors: [
        '#shipping_postcode_field','.form-row.shipping_postcode','[data-field="postcode"].shipping',
        '.wc-block-components-address-form__postcode--shipping','input#shipping_postcode','input[name="shipping_postcode"]','input#shipping-postcode'
      ]
    }
  ];

  const LOCK_SELECTORS = [
    'input#billing_city','input#shipping_city',
    'input[name="billing_city"]','input[name="shipping_city"]',
    'input#billing-city','input#shipping-city',
    '.wc-block-components-address-form__city input'
  ];

  const BLOCK_CARD_SELECTOR = '.wc-block-components-address-card';


  const config = window.foodord_lock_vars || {};
  const isPickupMode = config.mode === 'pickup';
  const debugEnabled = Boolean(config.debug);

  const tooltipText = config.tooltip
    || 'To change your city and postal code, please go back to the order page and use the Address Changer.';
  const iconLabel   = config.iconLabel
    || 'Locked field';

  function debugLog(){
    if (!debugEnabled || typeof window === 'undefined' ) {
      return;
    }
    try {
      const args = Array.prototype.slice.call(arguments);
      args.unshift('[FoodOrd Pickup]');
      if (!Array.isArray(window.foodordPickupLog)) {
        window.foodordPickupLog = [];
      }
      window.foodordPickupLog.push(args);
    } catch (err) {
      // Swallow logging issues quietly.
      void err;
    }
  }

  function pickContainer(input){
    if (!input || !(input instanceof HTMLElement)) {
      return null;
    }

    return input.closest('.form-row')
        || input.closest('[data-field]')
        || input.closest('[data-field-key]')
        || input.closest('.wc-block-components-address-form__address_1')
        || input.closest('.wc-block-components-address-form__address_2')
        || input.closest('.wc-block-components-address-form__city')
        || input.closest('.wc-block-components-address-form__postcode')
        || input.closest('.wc-block-components-address-form__state')
        || input.closest('.wc-block-components-address-form__country')
        || input.closest('.wc-block-components-text-input')
        || input.closest('.wc-block-components-combobox')
        || input.closest('.wc-block-components-select')
        || input.closest('.woocommerce-input-wrapper')
        || input.parentElement;
  }

  function ensureInputShell(input){
    if (!input || !input.parentNode) {
      return null;
    }

    const existing = input.closest('.foodord-lock-shell');
    if (existing) {
      existing.classList.add('foodord-input-wrap');
      return existing;
    }

    const shell = document.createElement('span');
    shell.className = 'foodord-lock-shell foodord-input-wrap';
    const parent = input.parentNode;
    parent.insertBefore(shell, input);
    shell.appendChild(input);
    return shell;
  }

  function ensureIcon(container){
    if (!container) return;
if (container.querySelector('.foodord-lockmark')) return; // already injected

    const icon = document.createElement('span');
    icon.className = 'foodord-lockmark';
    icon.setAttribute('tabindex','0');
    icon.setAttribute('role','img');
    icon.setAttribute('aria-label', iconLabel);
    icon.innerHTML = '\n      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">\n        <path d="M17 11H7a2 2 0 0 0-2 2v5a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-5a2 2 0 0 0-2-2Zm-5 4v2m4-6V9a4 4 0 0 0-8 0v2" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n      </svg>';

    // Remove any legacy sibling tooltip if present to avoid duplicates
    const legacy = container.querySelector('.foodord-lock-tooltip');
if (legacy) { try { legacy.remove(); } catch { } }

    // Use CSS-driven tooltip via data attribute (no inline styles)
    icon.setAttribute('data-tip', tooltipText);

    container.appendChild(icon);
  }

  function shouldSkipLock(el) {
    if (!el) {
      return false;
    }
    const id = (el.id || '').toLowerCase();
    const name = (el.name || '').toLowerCase();
    return (
      id.includes('postcode') ||
      id.includes('postal') ||
      name.includes('postcode') ||
      name.includes('postal')
    );
  }

  function lockInput(el){
    try {
      if (!el) return false;
      if (el.classList.contains('foodord-locked-input')) return true;

      if (shouldSkipLock(el)) {
        el.readOnly = false;
        el.removeAttribute('aria-readonly');
        el.classList.remove('foodord-locked-input');
        return false;
      }

      el.readOnly = true;
      el.setAttribute('aria-readonly','true');
      el.tabIndex = -1;
      el.classList.add('foodord-locked-input');

      // Block user interactions
      const stop = function(e){ e.preventDefault(); e.stopPropagation(); return false; };
      el.addEventListener('keydown', stop, true);
      el.addEventListener('keypress', stop, true);
      el.addEventListener('paste', stop, true);
      el.addEventListener('mousedown', stop, true);

      // Mark container and inject icon/tooltip
      const container = pickContainer(el);
      if (container) {
        container.classList.add('foodord-locked-container');
        // Wrap the input so the lock icon anchors to the field height only.
        const wrap = ensureInputShell(el)
          || el.parentElement
          || el.closest('.wc-block-components-text-input')
          || el.closest('.woocommerce-input-wrapper');

        if (wrap) {
          wrap.classList.add('foodord-input-wrap');
        }
        ensureIcon(wrap || container);
      }
      return true;
    } catch { return false; }
  }

  function lockAll(context){
    context = context || document;
    LOCK_SELECTORS.forEach(function(sel){
      const nodes = Array.prototype.slice.call(context.querySelectorAll(sel));
      nodes.forEach(function(node){ lockInput(node); });
    });
  }

  function markPickupMode(){
    const root = document.documentElement;
    const body = document.body;
    if (root && !root.classList.contains('foodord-pickup-mode')) {
      root.classList.add('foodord-pickup-mode');
    }
    if (body && !body.classList.contains('foodord-pickup-mode')) {
      body.classList.add('foodord-pickup-mode');
    }
  }

  function findFirstSelector(selectors, context){
    context = context || document;
    for (let i = 0; i < selectors.length; i++) {
      const sel = selectors[i];
      try {
        const node = context.querySelector(sel);
        if (node) {
          return { node, selector: sel };
        }
      } catch (err) {
        debugLog('Invalid selector skipped', sel, err);
      }
    }
    return null;
  }

  function hideFieldSet(field){
    const match = findFirstSelector(field.selectors);
    if (!match) {
      debugLog(field.label + ' bulunamadı', field.selectors);
      return;
    }

    let target = match.node;
    if (target.matches && target.matches('input, select, textarea')) {
      const container = pickContainer(target);
      if (container) {
        target = container;
      }
    }

    if (target instanceof HTMLElement) {
      if (target.matches('.wc-block-components-form, .wc-block-checkout__form')) {
        debugLog(field.label + ' güvenlik nedeniyle gizlenmedi', match.selector);
        return;
      }

      target.style.setProperty('display','none','important');
      target.setAttribute('aria-hidden','true');
      target.classList.add('foodord-pickup-hidden-field');
      debugLog(field.label + ' gizlendi', match.selector);
    }
  }

  function hidePickupFields(){
    FIELDS.forEach(hideFieldSet);
  }

  let storeSubscription = null;

  function ensureBlocksFormsOpen(){
    if (!window.wp || !window.wp.data || !window.wp.data.select || !window.wp.data.dispatch) {
      return false;
    }

    const storeName = 'wc/store/checkout';
    const dispatchers = window.wp.data.dispatch(storeName);
    const selectors = window.wp.data.select(storeName);

    if (!dispatchers || !selectors ||
      typeof dispatchers.setEditingBillingAddress !== 'function' ||
      typeof dispatchers.setEditingShippingAddress !== 'function' ||
      typeof selectors.getEditingBillingAddress !== 'function' ||
      typeof selectors.getEditingShippingAddress !== 'function') {
      return false;
    }

    const enforce = function(){
      try {
        const currentSelectors = window.wp.data.select(storeName);
        if (!currentSelectors) {
          return;
        }

        if (!currentSelectors.getEditingBillingAddress()) {
          dispatchers.setEditingBillingAddress(true);
        }

        if (!currentSelectors.getEditingShippingAddress()) {
          dispatchers.setEditingShippingAddress(true);
        }
      } catch (err) {
        debugLog('Adres formu state kontrolünde hata', err);
      }
    };

    enforce();

    if (storeSubscription) {
      return true;
    }

    storeSubscription = window.wp.data.subscribe(enforce);
    debugLog('Adres formları wp.data ile açık tutuluyor');
    return true;
  }

  function forceOpenAddressCardsFallback(context){
    context = context || document;
    const cards = Array.prototype.slice.call(context.querySelectorAll(BLOCK_CARD_SELECTOR));
    if (!cards.length) {
      debugLog('Block adres kartı bulunamadı');
      return;
    }

    cards.forEach(function(card){
      if (!(card instanceof HTMLElement)) {
        return;
      }

      card.classList.add('foodord-address-card-open');

      const editBtn = card.querySelector('.wc-block-components-address-card__edit');
      if (editBtn instanceof HTMLElement) {
        editBtn.style.setProperty('display', 'none', 'important');
        editBtn.setAttribute('aria-hidden', 'true');
        editBtn.setAttribute('tabindex', '-1');
      }

      const summary = card.querySelector('.wc-block-components-address-card__summary');
      if (summary instanceof HTMLElement) {
        summary.style.setProperty('display', 'none', 'important');
        summary.setAttribute('aria-hidden', 'true');
      }

      const form = card.querySelector('.wc-block-components-address-card__form');
      if (form instanceof HTMLElement) {
        form.style.removeProperty('display');
        form.removeAttribute('hidden');
        form.classList.add('foodord-address-card__form-open');
      }
    });
    debugLog('Fallback DOM yöntemi ile adres formları açıldı');
  }

  function openAddressFormsWithRetry(attempt){
    attempt = attempt || 0;
    if (ensureBlocksFormsOpen()) {
      return;
    }
    if (attempt > 20) {
      debugLog('wp.data store erişilemedi, fallback DOM tetiklendi');
      forceOpenAddressCardsFallback(document);
      return;
    }
    setTimeout(function(){ openAddressFormsWithRetry(attempt + 1); }, 150);
  }

  function setupObserver(callback){
    if (typeof MutationObserver !== 'function') {
      return;
    }
    const observer = new MutationObserver(function(mutations){
      for (let i=0; i<mutations.length; i++){
        const m = mutations[i];
        if (m.addedNodes && m.addedNodes.length){
          callback();
          break;
        }
      }
    });
    observer.observe(document.documentElement || document.body, { childList: true, subtree: true });
  }

  function clearPickupValidationErrors() {
    if (!window.wp || !window.wp.data || !window.wp.data.dispatch) {
      return;
    }
    try {
      const validationDispatch = window.wp.data.dispatch('wc/store/validation');
      if (validationDispatch && typeof validationDispatch.clearValidationError === 'function') {
        validationDispatch.clearValidationError('billing_address_1');
        validationDispatch.clearValidationError('billing_postcode');
        validationDispatch.clearValidationError('billing_city');
        validationDispatch.clearValidationError('shipping_address_1');
        validationDispatch.clearValidationError('shipping_postcode');
        validationDispatch.clearValidationError('shipping_city');
        debugLog('Validation errors cleared for pickup');
      }
    } catch (err) {
      debugLog('Error clearing validation:', err);
    }
  }

  function fillPickupDefaults() {
    if (!window.wp || !window.wp.data) {
      return;
    }
    try {
      const cartDispatch = window.wp.data.dispatch('wc/store/cart');
      if (cartDispatch && typeof cartDispatch.setBillingAddress === 'function') {
        const storeAddress = config.storeAddress || 'Pickup Location';
        const storeCity = config.storeCity || 'Store';
        const storePostcode = config.storePostcode || '0000';
        
        cartDispatch.setBillingAddress({
          address_1: storeAddress,
          city: storeCity,
          postcode: storePostcode
        });
        cartDispatch.setShippingAddress({
          address_1: storeAddress,
          city: storeCity,
          postcode: storePostcode
        });
        debugLog('Pickup defaults filled');
      }
      clearPickupValidationErrors();
    } catch (err) {
      debugLog('Error filling pickup defaults:', err);
    }
  }

  function setupPickupValidationFix() {
    if (!isPickupMode) {
      return;
    }
    setTimeout(fillPickupDefaults, 1000);
    setTimeout(fillPickupDefaults, 2000);
    setTimeout(clearPickupValidationErrors, 3000);
  }

  function init(){
    debugLog('Başlatılıyor. Pickup modu:', isPickupMode, config);

    openAddressFormsWithRetry(0);

    if (isPickupMode) {
      markPickupMode();
      hidePickupFields();
      setupPickupValidationFix();
      setupObserver(function(){
        openAddressFormsWithRetry(0);
        hidePickupFields();
      });
      return;
    }

    lockAll(document);
    setupObserver(function(){
      openAddressFormsWithRetry(0);
      lockAll(document);
    });
  }

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