(function(){
  'use strict';
  function init(editor){
    if (!editor || editor.dataset.companyContactsReady === '1') return;
    editor.dataset.companyContactsReady = '1';
    var list = editor.querySelector('[data-company-contacts]');
    var template = editor.querySelector('[data-company-contact-template]');
    var add = editor.querySelector('[data-company-contact-add]');
    if (!list || !template || !add) return;
    add.addEventListener('click', function(){
      list.appendChild(template.content.cloneNode(true));
      var rows = list.querySelectorAll('[data-company-contact-row]');
      var input = rows[rows.length - 1] && rows[rows.length - 1].querySelector('input[name="contact_value[]"]');
      if (input) input.focus();
    });
    list.addEventListener('click', function(event){
      var remove = event.target.closest && event.target.closest('[data-company-contact-remove]');
      if (!remove) return;
      var row = remove.closest('[data-company-contact-row]');
      if (!row) return;
      var rows = list.querySelectorAll('[data-company-contact-row]');
      if (rows.length === 1) {
        row.querySelectorAll('input').forEach(function(input){ input.value = ''; });
        var select = row.querySelector('select');
        if (select) select.value = 'mobile';
        return;
      }
      row.remove();
    });
  }
  function boot(){ document.querySelectorAll('.cpi-contact-editor').forEach(init); }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot();
})();

