(function () {
  const syncWidthRows = () => {
    document.querySelectorAll('select[name^="calio_megamenu_width_mode["]').forEach((select) => {
      const wrapper = select.closest('.calio-megamenu-fields');
      if (!wrapper) {
        return;
      }

      const row = wrapper.querySelector('.calio-mega-custom-width-row');
      if (!row) {
        return;
      }

      row.style.display = select.value === 'custom' ? '' : 'none';
    });
  };

  document.addEventListener('change', (event) => {
    const target = event.target;
    if (!(target instanceof HTMLSelectElement)) {
      return;
    }

    if (target.name && target.name.indexOf('calio_megamenu_width_mode[') === 0) {
      syncWidthRows();
    }
  });

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