(function(){
  'use strict';

  const SELECTORS = [
    '.wc-block-components-address-form__country',
    '.wc-block-components-country-input',
    '.wc-block-components-country-select',
    '.wc-block-components-address-form__state',
    '.wc-block-components-state-input',
    '.wc-block-components-state-select',
    '[data-field="country"]',
    '[data-field-key="country"]',
    '[data-field="state"]',
    '[data-field-key="state"]',
    '#billing_country_field',
    '#shipping_country_field',
    '#billing_state_field',
    '#shipping_state_field',
    'select#billing_country',
    'select#shipping_country',
    'select#billing_state',
    'select#shipping_state',
    'input#billing_state',
    'input#shipping_state'
  ];

  function pickContainer(node){
    return node.closest('.wc-block-components-country-input')
        || node.closest('.wc-block-components-country-select')
        || node.closest('.wc-block-components-address-form__country')
        || node.closest('.wc-block-components-state-input')
        || node.closest('.wc-block-components-state-select')
        || node.closest('.wc-block-components-address-form__state')
        || node.closest('[data-field="country"]')
        || node.closest('[data-field-key="country"]')
        || node.closest('[data-field="state"]')
        || node.closest('[data-field-key="state"]')
        || node.closest('.form-row')
        || node;
  }

  function removeOnce(context){
    context = context || document;
    let removed = 0;


    SELECTORS.forEach(function(sel){
      const nodes = Array.prototype.slice.call(context.querySelectorAll(sel));
      if (!nodes.length){
        return;
      }
      nodes.forEach(function(node){
        const container = pickContainer(node);
        if (container && container.parentNode){
          container.parentNode.removeChild(container);
          removed++;
        }
      });
    });

    return removed > 0;
  }

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

  function init(){
    removeOnce(document);
    setupObserver();
  }

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