function createDependentDropdownField(container, field, dependentdropdown, alldata) {
  console.log("createDependentDropdown", container, field, dependentdropdown, alldata);
  
  console.log("Fields Data :", field.required_for_agents);

  // Check if the label for this field already exists
  if (!container.querySelector(`label[for='field_${field.value}']`)) {
    const fieldLabelElement = document.createElement('label');
    fieldLabelElement.innerHTML = `${field.label} <span style="color: red;">*</span>`;
    fieldLabelElement.setAttribute('for', `field_${field.value}`);
    fieldLabelElement.style.marginBottom = '8px';
    fieldLabelElement.style.fontWeight = '600';
    container.appendChild(fieldLabelElement);
  }

  const fieldContainer = document.createElement('div');
  fieldContainer.classList.add('form-group');

  const dropdownContainer = document.createElement('div');
  dropdownContainer.style.display = 'flex';
  dropdownContainer.style.alignItems = 'center';

  const selectWrapper = document.createElement('div');
  selectWrapper.style.flexGrow = '1';

  const select = document.createElement('fw-select');
  select.setAttribute('required', 'true');
  select.setAttribute('id', `field_${field.value}`);
  select.setAttribute('name', field.name);
  select.setAttribute('placeholder', `Select ${field.label}`);
  select.setAttribute('hint-text', 'Select singular option');
  select.style.width = '100%';
  selectWrapper.appendChild(select);

  populateDropdown(select, field.choices, dependentdropdown);

  if (alldata.mandatory_fields && alldata.mandatory_fields[field.name]) {
    const initialLevelOne = alldata.mandatory_fields[field.name];
    select.value = initialLevelOne;
    handleLevelOneChange(select, field.choices, selectWrapper, field, alldata);
  }

  select.addEventListener('fwChange', (event) => {
    const selectedValue = event.detail.value;
    if (selectedValue !== 'default') {
      handleLevelOneChange(select, field.choices, selectWrapper, field, alldata);
    }
  });

  dropdownContainer.appendChild(selectWrapper);

  // Tooltip and delete button
  const tooltip = document.createElement('fw-tooltip');
  tooltip.setAttribute('content', 'This field cannot be deleted');

  const deleteButton = document.createElement('fw-button');
  deleteButton.setAttribute('size', 'icon');
  deleteButton.setAttribute('color', 'secondary');
  deleteButton.style.marginLeft = '8px';

  const deleteIcon = document.createElement('fw-icon');
  deleteIcon.setAttribute('name', 'delete');
  deleteIcon.setAttribute('size', '20');
  deleteButton.appendChild(deleteIcon);

  if (field.required_for_agents) {
    deleteButton.setAttribute('disabled', 'true');
    tooltip.appendChild(deleteButton);
  } else {
    deleteButton.addEventListener('click', () => {
      removeNestedDropdowns(fieldContainer, field.name, 1);
      container.removeChild(fieldContainer);
      delete selectedMandatoryFields[field.name];
      console.log('Remaining values:', selectedMandatoryFields);
    });
    dropdownContainer.appendChild(deleteButton);
  }

  if (field.required_for_agents) {
    dropdownContainer.appendChild(tooltip);
  }

  fieldContainer.appendChild(dropdownContainer);
  container.appendChild(fieldContainer);
}

function handleLevelOneChange(parentDropdown, choices, container, field, alldata) {
  // Remove nested dropdowns beyond the first level
  removeNestedDropdowns(container, field.name, 1);

  // Get the selected value from the dropdown
  const selectedValue = parentDropdown.value;
  const selectedChoice = findChoiceByValue(selectedValue, choices);

  // Ensure `field.nested_fields` exists and has at least one entry
  if (selectedChoice && Array.isArray(field.nested_fields) && field.nested_fields[0]) {
    const levelTwoFieldName = field.nested_fields[0].name;

    // Safeguard: Check if `alldata.mandatory_fields` is valid and contains the required field
    const initialLevelTwo = alldata.mandatory_fields ? alldata.mandatory_fields[levelTwoFieldName] : null;

    // Create the second-level dropdown
    createLevelTwoDropdown(container, selectedChoice, field, alldata, initialLevelTwo);
  } else {
    console.error(`Invalid nested fields or missing data for field: ${field.name}.`);
  }

  // Update the selected mandatory fields
  selectedMandatoryFields[field.name] = selectedValue;
  console.log("selectedMandatoryFields----", field, selectedMandatoryFields);
}

function createLevelTwoDropdown(container, selectedChoice, field, alldata, initialValue) {
  // Remove existing second-level dropdown and label
  removeNestedDropdowns(container, field.name, 2);

  // Check if the label for this level already exists
  const existingLabel = container.querySelector(`label[for="${field.name}_level_2"]`);
  if (!existingLabel) {
      const levelTwoLabelElement = document.createElement('label');
      levelTwoLabelElement.style.marginTop = '16px';
      levelTwoLabelElement.innerHTML = `${field.nested_fields[0].label} <span style="color: red;">*</span>`;
      levelTwoLabelElement.setAttribute('for', `${field.name}_level_2`);
      levelTwoLabelElement.style.marginLeft = '20px';
      levelTwoLabelElement.style.marginBottom = '3px';
      levelTwoLabelElement.style.fontWeight = '600';
      container.appendChild(levelTwoLabelElement);
  }
  // Create second-level dropdown
  const nestedSelect = document.createElement('fw-select');
  nestedSelect.setAttribute('name', `${field.name}_level_2`);
  nestedSelect.setAttribute('placeholder', `Select ${selectedChoice.label || 'an option'}`);
  nestedSelect.setAttribute('hint-text', 'Select singular option');
  nestedSelect.classList.add('ms-3', 'my-2'); // Bootstrap classes for margin
  populateDropdown(nestedSelect, selectedChoice.nested_options);
  container.appendChild(nestedSelect);

  if (initialValue) {
    nestedSelect.value = initialValue;
    handleLevelTwoChange(nestedSelect, selectedChoice.nested_options, container, field, alldata);
  }

  nestedSelect.addEventListener('fwChange', (event) => {
    const selectedValue = event.detail.value;
    selectedMandatoryFields[field.nested_fields[0].name] = selectedValue;
    handleLevelTwoChange(nestedSelect, selectedChoice.nested_options, container, field, alldata);
  });
}

function handleLevelTwoChange(parentDropdown, choices, container, field, alldata) {
  // Remove nested dropdowns beyond the second level
  removeNestedDropdowns(container, field.name, 2);

  // Get the selected value and choice
  const selectedValue = parentDropdown.value;
  const selectedChoice = findChoiceByValue(selectedValue, choices);

  // Update the selected mandatory fields
  selectedMandatoryFields[field.nested_fields[0].name] = selectedValue;

  // Check if nested_fields exists, is an array, and has at least two elements
  if (
    selectedChoice &&
    selectedChoice.nested_options &&
    Array.isArray(field.nested_fields) &&
    field.nested_fields.length > 1
  ) {
    const levelThreeFieldName = field.nested_fields[1].name;

    // Safeguard: Check if alldata.mandatory_fields is valid and contains the required field
    const initialLevelThree = alldata.mandatory_fields
      ? alldata.mandatory_fields[levelThreeFieldName]
      : null;

    // Create the third-level dropdown
    createLevelThreeDropdown(container, selectedChoice, field, alldata, initialLevelThree);
  } else {
    console.log(`No valid nested options for field: ${field.nested_fields[0].name}`);
  }
}

function createLevelThreeDropdown(container, selectedChoice, field, alldata, initialValue) {
  // Remove existing third-level dropdown and label
  removeNestedDropdowns(container, field.name, 3);

  // Check if the label for this level already exists
  const existingLabel = container.querySelector(`label[for="${field.name}_level_3"]`);
  if (!existingLabel) {
      const levelThreeLabelElement = document.createElement('label');
      levelThreeLabelElement.innerHTML = `${field.nested_fields[1].label} <span style="color: red;">*</span>`;
      levelThreeLabelElement.setAttribute('for', `${field.name}_level_3`);
      levelThreeLabelElement.style.marginLeft = '20px';
      levelThreeLabelElement.style.marginBottom = '3px';
      levelThreeLabelElement.style.fontWeight = '600';
      container.appendChild(levelThreeLabelElement);
  }
  // Create third-level dropdown
  const nestedSelect = document.createElement('fw-select');
  nestedSelect.setAttribute('name', `${field.name}_level_3`);
  nestedSelect.setAttribute('placeholder', `Select ${selectedChoice.label || 'an option'}`);
  nestedSelect.setAttribute('hint-text', 'Select singular option');
  nestedSelect.classList.add('ms-3', 'my-2'); // Bootstrap classes for margin
  populateDropdown(nestedSelect, selectedChoice.nested_options);
  container.appendChild(nestedSelect);

  if (initialValue) {
    nestedSelect.value = initialValue;
    selectedMandatoryFields[field.nested_fields[1].name] = nestedSelect.value;
  }

  nestedSelect.addEventListener('fwChange', () => {
    selectedMandatoryFields[field.nested_fields[1].name] = nestedSelect.value;
  });
}

function removeDropdownSet(container, fieldName) {
  const elementsToRemove = container.querySelectorAll(`fw-select[name^="${fieldName}"], label[for^="${fieldName}"]`);

  elementsToRemove.forEach((element) => {
      const name = element.getAttribute('name');
      delete selectedMandatoryFields[name];
      container.removeChild(element);
  });

  // Remove the entire field container
  container.parentNode.removeChild(container);
  console.log("Remaining selectedMandatoryFields:", selectedMandatoryFields);
}

function removeNestedDropdowns(container, fieldName, level) {
  const children = container.querySelectorAll(`fw-select[name^="${fieldName}_level_"]`);
  children.forEach(child => {
      const childLevel = parseInt(child.getAttribute('name').split('_').pop(), 10);
      if (childLevel > level) {
          delete selectedMandatoryFields[child.getAttribute('name')];
          container.removeChild(child);
      }
  });
}

function populateDropdown(dropdown, choices) {
  if (!Array.isArray(choices)) {
      console.error('Choices is not an array:', choices);
      return;
  }

  choices.forEach(choice => {
      const option = document.createElement('fw-select-option');
      option.setAttribute('value', choice.value); // Updated to use `value` instead of `id`
      option.textContent = choice.value;
      dropdown.appendChild(option);
  });
}

function findChoiceByValue(value, choices) {
  for (const choice of choices) {
      if (choice.value == value) { // Updated to compare `value`
          return choice;
      }
      if (choice.nested_options) {
          const result = findChoiceByValue(value, choice.nested_options);
          if (result) {
              return result;
          }
      }
  }
  return null;
}


in this, when i change 1st dropdown, 2nd dropdown should create as new