(function(){
  'use strict';

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

  function pickContainer(node){
    return node.closest('.wc-block-components-country-input')
        || node.closest('.wc-block-components-address-form__country')
        || node.closest('.wc-block-components-address-form')
        || node.closest('.wc-block-components-form')
        || node.closest('.wc-block-checkout__form')
        || 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();
  }
})();
