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

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

  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();
  return () => {
    enabledInput.removeEventListener('change', updateUi);
    if (syncToggle instanceof HTMLInputElement) {
      syncToggle.removeEventListener('change', updateUi);
    }
    if (sharedToggle instanceof HTMLInputElement) {
      sharedToggle.removeEventListener('change', updateUi);
    }
  };
};

export const initTenantSsoToggle = createConditionalToggleInit({
  rootSelector: '[data-tenant-sso-root]',
  boundKey: 'tenantSsoToggleBound',
  initRoot,
});
