/**
 * Shows/hides LDAP configuration fields based on tenant LDAP toggle.
 */
import { syncControlState, createConditionalToggleInit } from '../core/app-conditional-controls.js';

const initRoot = (root) => {
  const enabledInput = root.querySelector('[data-tenant-ldap-enabled]');
  if (!(enabledInput instanceof HTMLInputElement)) {
    return null;
  }

  const syncToggle = root.querySelector('[data-tenant-ldap-sync-toggle]');
  const enabledBlocks = root.querySelectorAll('[data-tenant-ldap-when-enabled]');
  const syncFieldsBlock = root.querySelector('[data-tenant-ldap-sync-fields]');

  const updateUi = () => {
    const ldapEnabled = enabledInput.checked;
    const syncEnabled = syncToggle instanceof HTMLInputElement ? syncToggle.checked : false;

    enabledBlocks.forEach((block) => syncControlState(block, ldapEnabled));
    syncControlState(syncFieldsBlock, ldapEnabled && syncEnabled);
  };

  enabledInput.addEventListener('change', updateUi);
  if (syncToggle instanceof HTMLInputElement) {
    syncToggle.addEventListener('change', updateUi);
  }

  updateUi();
  return () => {
    enabledInput.removeEventListener('change', updateUi);
    if (syncToggle instanceof HTMLInputElement) {
      syncToggle.removeEventListener('change', updateUi);
    }
  };
};

export const initTenantLdapToggle = createConditionalToggleInit({
  rootSelector: '[data-tenant-ldap-root]',
  boundKey: 'tenantLdapToggleBound',
  initRoot,
});
