const roots = document.querySelectorAll('[data-tenant-sso-root]');

const syncControlState = (container, show) => {
  if (!container) {
    return;
  }

  container.hidden = !show;

  container.querySelectorAll('input, select, textarea, button').forEach((control) => {
    if ((control instanceof HTMLInputElement) && control.type === 'hidden') {
      return;
    }

    if (!control.dataset.initialDisabled) {
      control.dataset.initialDisabled = control.hasAttribute('disabled') ? '1' : '0';
    }

    if (!show) {
      control.setAttribute('disabled', 'disabled');
      return;
    }

    if (control.dataset.initialDisabled === '1') {
      control.setAttribute('disabled', 'disabled');
      return;
    }

    control.removeAttribute('disabled');
  });
};

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

  const syncToggle = root.querySelector('[data-tenant-sso-sync-toggle]');
  const sharedToggle = root.querySelector('[data-tenant-sso-shared-toggle]');
  const enabledBlocks = root.querySelectorAll('[data-tenant-sso-when-enabled]');
  const syncFieldsBlock = root.querySelector('[data-tenant-sso-sync-fields]');
  const overrideDetails = root.querySelector('[data-tenant-sso-override-details]');
  const overrideFields = root.querySelectorAll('[data-tenant-sso-override-fields]');

  const updateUi = () => {
    const ssoEnabled = enabledInput.checked;
    const syncEnabled = syncToggle instanceof HTMLInputElement ? syncToggle.checked : false;
    const useSharedApp = sharedToggle instanceof HTMLInputElement ? sharedToggle.checked : true;

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

    if (overrideDetails instanceof HTMLElement) {
      overrideDetails.hidden = !ssoEnabled;
      if (!ssoEnabled && overrideDetails instanceof HTMLDetailsElement) {
        overrideDetails.open = false;
      }
    }

    overrideFields.forEach((block) => syncControlState(block, ssoEnabled && !useSharedApp));
  };

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

  updateUi();
};

roots.forEach(initRoot);
