(function () {
  'use strict';

  function sync(checkbox, wrapper) {
    if (!checkbox || !wrapper) return;
    var select = wrapper.querySelector('select[name="integration_id"]');
    if (checkbox.checked) {
      wrapper.style.display = '';
      if (select) select.required = true;
    } else {
      wrapper.style.display = 'none';
      if (select) {
        select.required = false;
        select.value = '';
      }
    }
  }

  function init() {
    var checkbox = document.querySelector('[data-invoice-delegated]');
    var wrapper = document.querySelector('[data-invoice-delegation]');
    if (!checkbox || !wrapper) return;

    sync(checkbox, wrapper);
    checkbox.addEventListener('change', function () {
      sync(checkbox, wrapper);
    });
  }

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