why in this in intial time it maps to field-name-container and choicesDiv but in existing mapping / if selectedfieldname why it adds to its child ? that should not. just give me this fixed part 

async function fieldschoosingvalues(
  selectedEventValue,
  fieldNameContainer,
  choicesContainer,
  buttonContainer,
  container,
  selectedFieldName = null,
  selectedChoices = [], 
  obj,
  ruleIndex,
  fieldIndex
) {
  
  if (!selectedEventValue) {
    console.error("fieldschoosingvalues called with an undefined selectedEventValue.");
    return;
  }

  try {

    let statusResp = await makeApiCall(apiKeyInput1.value, domainInput1.value);

    // await makeApiCallMandatory2(apiKeyInput1.value, domainInput1.value, merchantWorkspaceFieldsAsNumber);

    if (statusResp && statusResp.ticket_fields) {
      let fields = statusResp.ticket_fields.filter(field =>
        field.field_type.startsWith('default_') &&
        field.choices &&
        field.choices.length > 0 &&
        field.name !== "ticket_type"
        // field.required_for_agents
      );

      console.log(`Starting fieldschoosingvalues with selectedEventValue: ${selectedEventValue}`);
      console.log(`Mapping field name: ${selectedFieldName}`);
      console.log(`Mapping choice values: ${JSON.stringify(selectedChoices)}`); 

      if (selectedFieldName) {

        const fieldContainer = document.createElement('div');
        fieldContainer.classList.add('field-container');
        fieldNameContainer.appendChild(fieldContainer);

        const choicesDiv = document.createElement('div');
        choicesDiv.classList.add('choices-container');
        choicesContainer.appendChild(choicesDiv);

        await getFieldnamesfrom1stapi(
          fieldContainer,
          fields,
          choicesDiv,
          selectedEventValue,
          buttonContainer,
          container,
          selectedFieldName,
          selectedChoices, 
          obj,
          ruleIndex,
          fieldIndex
        );

      } else {
        await getFieldnamesfrom1stapi(
          fieldNameContainer,
          fields,
          choicesContainer,
          selectedEventValue,
          buttonContainer,
          container,
          null,
          [],
          obj,
          ruleIndex,
          fieldIndex
        );
      }


      


    } else {
      console.error('No fields found or data not available');
    }
  } catch (error) {
    console.error("Error fetching data for Dropdown:", error);
  }
}

async function getFieldnamesfrom1stapi(
  fieldNameContainer,
  fields,
  choicesContainer,
  selectedEventValue,
  buttonContainer,
  container,
  selectedFieldName = null,
  selectedChoices = [], 
  obj,
  ruleIndex,
  fieldIndex
) {
  if (!selectedEventValue) {
    console.error("Select an event before proceeding.");
    return;
  }
  // Create the field dropdown
const fieldDropdown = document.createElement('fw-select');
fieldDropdown.classList.add('field-name-dropdown');
fieldDropdown.setAttribute('label', 'Ticket Fields');
fieldDropdown.setAttribute('required', 'true');
fieldDropdown.setAttribute('placeholder', 'Choose a field');
fieldDropdown.setAttribute('hint-text', 'Select singular option ');
// fieldDropdown.style.marginBottom = '30px'; 

  const selectedFields = Array.from(container.querySelectorAll('.field-name-dropdown'))
    .map((dropdown) => dropdown.value)
    .filter((value) => value);

  fields
    .filter((field) => !selectedFields.includes(field.name))
    .forEach((field) => {
      const option = document.createElement('fw-select-option');
      option.setAttribute('value', field.name);
      option.textContent = field.label;
      fieldDropdown.appendChild(option);

      if (selectedFieldName && field.name === selectedFieldName) {
        option.setAttribute('selected', 'selected');
      }
    });

  fieldNameContainer.appendChild(fieldDropdown);
  
  const deleteButton = document.createElement('fw-button');
  deleteButton.setAttribute('size', 'icon');
  deleteButton.classList.add('delete-button');
  deleteButton.innerHTML = '<fw-icon name="delete" size="20" color="white"></fw-icon>';

  const deleteButtonWrapper = document.createElement('div');
  deleteButtonWrapper.classList.add('delete-button-container', 'mt-5');  
  deleteButtonWrapper.style.marginBottom = '80px'; 

  deleteButtonWrapper.appendChild(deleteButton);
  buttonContainer.appendChild(deleteButtonWrapper);

  const existingAddButton = container.querySelector('.add-button');
  if (existingAddButton) {
    existingAddButton.remove();
  }

  const addButton = document.createElement('fw-button');
addButton.setAttribute('size', 'icon');
addButton.classList.add('add-button');
addButton.innerHTML = '<fw-icon name="plus" size="20" color="white"></fw-icon>';
addButton.disabled = true;



const isFirstSet = container.querySelectorAll('.field-name-dropdown').length === 1;

addButton.style.marginTop = ''; 


if (isFirstSet) {
  addButton.style.marginTop = '48px'; 
} else {
  addButton.style.marginTop = '-150px'; 
}

buttonContainer.appendChild(addButton);

 
if (fieldIndex === container.querySelectorAll('.field-name-dropdown').length - 1) {
    buttonContainer.appendChild(addButton);
  }

addButton.addEventListener("click", () => {
    console.log("Add Button clicked. Freezing dropdowns and choices.");
   
   const dropdowns = container.querySelectorAll(".field-name-dropdown");
    dropdowns.forEach((dropdown) => {
        dropdown.disabled = true; 
    });

    const newIndex = ticketworkflowconditions[ruleIndex].event.combination.length;
    createAdditionalDropdowns(container, obj, ruleIndex, newIndex);

    checkAddButtonVisibility();
});
  
if (container.querySelectorAll('.field-name-dropdown').length > 1) {
  const deleteButton = document.createElement('fw-button');
  deleteButton.setAttribute('size', 'icon');
  deleteButton.classList.add('delete-button');
  deleteButton.innerHTML = '<fw-icon name="delete" size="20" color="white"></fw-icon>';
}

deleteButton.addEventListener("click", () => {
  console.log(`Delete button clicked for mapping at index ${fieldIndex}`);

  const modal = document.getElementById("composition");
  if (modal) {
    modal.setAttribute("is-open", "true");
    modal.querySelector("fw-modal-title").innerHTML = `<span>Delete Mapping</span>`;
    modal.querySelector("fw-modal-content").innerHTML = `<span>Are you sure you want to delete this field mapping?</span>`;

    modal.addEventListener(
      "fwSubmit",
      () => {

        const findRule = ticketworkflowconditions[ruleIndex];
        if (findRule) {
          const currentDropdowns = container.querySelectorAll(".field-name-dropdown");
          const currentDropdownIndex = Array.from(currentDropdowns).indexOf(fieldDropdown);

          if (currentDropdownIndex !== -1) {
            const combination = findRule.event.combination;
            combination.splice(currentDropdownIndex, 1);

            // if (combination.length === 1) {
            //   console.log("This is the last combination being deleted.");

            //   // Remove the existing delete button
            //   const existingDeleteButton = container.querySelector('.delete-button-container');
            //   if (existingDeleteButton) {
            //     existingDeleteButton.remove();
            //   }

            //   // Apply marginTop to addButton
            //   if (addButton) {
            //     addButton.style.marginTop = ''; 
            //     addButton.style.marginTop = '48px'; // Add new marginTop
            //   }
            // }
 
            const fieldremoveContainer = fieldNameContainer.closest(".field-container");
            if (fieldremoveContainer) {
              fieldremoveContainer.remove();
            }

            const choiceremoveContainer = fieldNameContainer.closest(".choices-container");
            if (choiceremoveContainer) {
              choiceremoveContainer.remove();
            }

            ticketworkflowconditions[ruleIndex] = {
              ...findRule,
              event: { ...findRule.event, combination },
            };

            fieldNameContainer.removeChild(fieldDropdown);
            choicesContainer.innerHTML = ""; 
            buttonContainer.removeChild(deleteButtonWrapper);

            const spacingElement = container.querySelectorAll('.field-name-dropdown');
            if (spacingElement.length === 0) {              
              container.style.marginTop = ''; 
            }
          }
        }

        console.log("Updated ticketworkflowconditions:", JSON.stringify(ticketworkflowconditions, null, 2));
        modal.removeAttribute("is-open");
        checkAddButtonVisibility();
      },
      { once: true }
    );

    modal.querySelector("fw-modal-footer").addEventListener(
      "fwClose",
      () => {
        modal.removeAttribute("is-open");
        console.log("Delete operation was cancelled.");
      },
      { once: true }
    );
  } else {
    console.error("Modal element with ID 'composition' not found.");
  }
});

checkDeleteButtonVisibility();

fieldDropdown.addEventListener("fwChange", async (event) => {
  const newSelectedFieldName = event.target.value;

  if (!newSelectedFieldName) {
    choicesContainer.innerHTML = "";
    const findRule = ticketworkflowconditions[ruleIndex];
    if (findRule) {
      findRule.event.combination[fieldIndex] = {}; 
    }
    console.log("Field deselected. Choices cleared.");
    return;
  }

  const newSelectedField = fields.find((field) => field.name === newSelectedFieldName);
  if (newSelectedField) {
    const findRule = ticketworkflowconditions[ruleIndex];
    
    if (findRule) {      
      findRule.event.combination[fieldIndex] = {
        [newSelectedFieldName]: selectedChoices || [], 
      };
    }
    
    console.log(`Field changed. Updated backend:`, JSON.stringify(ticketworkflowconditions, null, 2));

    await showingitschoices(
      choicesContainer,
      newSelectedField,
      selectedEventValue,
      newSelectedFieldName,
      buttonContainer,
      container,
      fieldNameContainer,
      [], 
      obj,
      ruleIndex,
      fieldIndex
    );

    console.log(`Field changed to: ${newSelectedFieldName}`);    
    // fieldDropdown.disabled = true; 

  } else {
    console.error("Field not found in the Dropdown");
  }

  checkAddButtonVisibility();
});

if (selectedFieldName) {
  const selectedField = fields.find((field) => field.name === selectedFieldName);

  if (selectedField) {
    await showingitschoices(
      choicesContainer,
      selectedField,
      selectedEventValue,
      selectedFieldName,
      buttonContainer,
      container,
      fieldNameContainer,
      selectedChoices,
      obj,
      ruleIndex,
      fieldIndex
    );

    fieldDropdown.disabled = true; 

    const findRule = ticketworkflowconditions[ruleIndex];
    if (findRule) {
      // Ensure the field index is updated rather than appending
      findRule.event.combination[fieldIndex] = {
        [selectedFieldName]: selectedChoices || [],
      };
      console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
    }

  } else {
    console.error(`Field not found in Dropdown for existing mapping: ${selectedFieldName}`);
  }
}


function checkAddButtonVisibility() {
    const dropdowns = container.querySelectorAll(".field-name-dropdown");
    const selectedFieldValues = Array.from(dropdowns)
        .map((dropdown) => dropdown.value)
        .filter((value) => value !== "");

    const areAllFieldsSelected = selectedFieldValues.length >= fields.length;

    const lastDropdownWrapper =
        dropdowns.length > 0
            ? dropdowns[dropdowns.length - 1].closest(".button-container")
            : null;

    if (areAllFieldsSelected) {
        console.log("All fields are selected. Hiding Add Button.");

        if (addButton.parentNode) {            
            if (lastDropdownWrapper && lastDropdownWrapper.contains(addButton)) {
                lastDropdownWrapper.removeChild(addButton);
            }
        }
    } else {
        console.log("Fields are still available. Add Button will be shown.");
        if (dropdowns.length > 0 && lastDropdownWrapper) {
            if (!lastDropdownWrapper.contains(addButton)) {
                lastDropdownWrapper.appendChild(addButton);
                addButton.style.visibility = "visible"; 
            }
        }
    }    
    addButton.disabled = false;
}

function checkDeleteButtonVisibility() {
  const dropdowns = container.querySelectorAll(".field-name-dropdown");
  const firstSetDeleteButtons = container.querySelectorAll(".delete-button-container");
  
  firstSetDeleteButtons.forEach((buttonWrapper, index) => {
    if (index === 0) { 
      if (dropdowns.length === 1) {
        buttonWrapper.style.display = "none";
      } else {
        buttonWrapper.style.display = "block"; 
        
      }
    }
  });
}


}

async function showingitschoices(
  choicesContainer,
  selectedField,
  selectedEventValue,
  selectedFieldName,
  buttonContainer,
  container,
  fieldNameContainer,
  selectedChoices = [], 
  obj,
  ruleIndex,
  fieldIndex
) {
  
  choicesContainer.innerHTML = '';
   
  const choicesDropdown = document.createElement('fw-select');
  choicesDropdown.classList.add('choices-dropdown');
  choicesDropdown.setAttribute('label', `${selectedFieldName}`);
  choicesDropdown.setAttribute('required', 'true');
  choicesDropdown.setAttribute('placeholder', `Choose ${selectedFieldName}`);
  choicesDropdown.setAttribute('hint-text', 'Select singular or multiple options'); 
  
  choicesDropdown.setAttribute('multiple', 'true'); 
  // choicesDropdown.setAttribute('max-height', '60px'); 
  
  selectedField.choices.forEach(choice => {
    const option = document.createElement('fw-select-option');
    option.setAttribute('value', choice.id);
    option.textContent = choice.value;
    choicesDropdown.appendChild(option);
    
    if (selectedChoices.includes(String(choice.id))) {
      option.setAttribute('selected', 'selected');
    }
  });

  choicesContainer.appendChild(choicesDropdown);

  choicesDropdown.addEventListener('fwChange', (event) => {
  const selectedChoiceIds = Array.isArray(event.target.value)
    ? event.target.value
    : [event.target.value]; 

  const findRule = ticketworkflowconditions[ruleIndex];
  if (findRule) {
    const combination = findRule.event.combination;
    
    const existingCombinationIndex = combination.findIndex(
      (entry) => Object.keys(entry)[0] === selectedFieldName
    );

    if (existingCombinationIndex !== -1) {
      combination[existingCombinationIndex][selectedFieldName] = selectedChoiceIds;
    } else {      
      combination.push({ [selectedFieldName]: selectedChoiceIds });
    }

    console.log(`Updated JSON with field: ${selectedFieldName}, choices: ${selectedChoiceIds}`);
    console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
  } else {
    console.error(`Rule not found for index: ${ruleIndex}`);
  }
});



}