async function loadExistingWorkflowConditions() {
  console.log("Mapping Data for Workflows:", alldata.ticket_workflow_conditions);
  for (const [eventName, fieldMappings] of Object.entries(alldata.ticket_workflow_conditions)) {
    console.log('Loading rule for event:', eventName);
    await addNewRule(eventName, fieldMappings);
  }
}

async function addNewRule(eventName, fieldMappings) {
  
  const ticketworkflowContainer = document.getElementById('ticketworkflow-container');
  const eventContainer = document.createElement('div');
  eventContainer.classList.add('event-container');
  eventContainer.style.boxShadow = '0 5px 10px 0 rgba(0, 0, 0, 0.2)';
  eventContainer.style.padding = '30px';
  eventContainer.style.marginBottom = '15px';
  eventContainer.style.borderRadius = '5px';
  eventContainer.style.backgroundColor = '#fff';


  const newDropdownSet = await createEventDropdownSet(eventName);
  eventContainer.appendChild(newDropdownSet);


  ticketworkflowContainer.appendChild(eventContainer);
  await initializeEventDropdown(newDropdownSet, fieldMappings);
}

async function createEventDropdownSet(eventName) {

  console.log("Creating Event Dropdown");
  const newDropdownSet = document.createElement('div');
  newDropdownSet.classList.add('row', 'ticketworkflow-dropdown');

  const selectedEvent = typeof eventName === 'string' ? eventName : '';

  newDropdownSet.innerHTML = `
      <div class="col-md-2 event-name-container">
          <fw-select
              class="event-name-dropdown"
              label="Select Event Name"
              required="true"
              placeholder="Your choice"
              hint-text="Select singular option">
              <fw-select-option value="TicketCreate" ${selectedEvent === "TicketCreate" ? "selected" : ""}>Ticket Create</fw-select-option>
              <fw-select-option value="TicketUpdate" ${selectedEvent === "TicketUpdate" ? "selected" : ""}>Ticket Update</fw-select-option>
              <fw-select-option value="TicketCreateandUpdate" ${selectedEvent === "TicketCreateandUpdate" ? "selected" : ""}>Ticket Create and Update</fw-select-option>
          </fw-select>
      </div>
  `;

  const eventSelect = newDropdownSet.querySelector('.event-name-dropdown');
  if (selectedEvent) {
    eventSelect.value = selectedEvent;
  }

  return newDropdownSet;
}

async function initializeEventDropdown(container, fieldMappings = null, eventContainer) {
  const eventSelect = container.querySelector('.event-name-dropdown');
  console.log(`initializeEventDropdown - Initial selected event: ${eventSelect.value}`);

  let fieldNameContainer = container.querySelector('.field-name-container');
  let choicesContainer = container.querySelector('.choices-container');
  let buttonContainer = container.querySelector('.button-container');

  if (!fieldNameContainer) {
    fieldNameContainer = document.createElement('div');
    fieldNameContainer.classList.add('col-md-2', 'field-name-container');
    container.appendChild(fieldNameContainer);
  }

  if (!choicesContainer) {
    choicesContainer = document.createElement('div');
    choicesContainer.classList.add('col-md-2', 'choices-container');
    container.appendChild(choicesContainer);
  }

  if (!buttonContainer) {
    buttonContainer = document.createElement('div');
    buttonContainer.classList.add('col-md-3', 'button-container');
    buttonContainer.style.marginTop = '25px';
    container.appendChild(buttonContainer);
  }

  if (!buttonContainer.querySelector('.delete-event-button')) {
    const deleteEventButton = document.createElement('fw-button');
    deleteEventButton.classList.add('delete-event-button');
    deleteEventButton.setAttribute('color', 'danger');
    deleteEventButton.textContent = 'Delete Event';
    buttonContainer.appendChild(deleteEventButton);

    deleteEventButton.addEventListener('click', () => {
      const eventContainer = container.closest('.event-container');
      if (eventContainer) {
        eventContainer.remove();
        delete ticketworkflowconditions[eventSelect.value];
        console.log("Delete Event button clicked. Event removed from DOM and ticketworkflowconditions.");
      }
    });
  }

  if (fieldMappings) {
    for (const [selectedFieldName, selectedChoices] of Object.entries(fieldMappings)) {
      console.log(`Mapping existing value: Event - ${eventSelect.value}, Field - ${selectedFieldName}, Choices - ${selectedChoices}`);
      for (const choice of selectedChoices) {
        await fieldschoosingvalues(
          eventSelect.value,
          fieldNameContainer,
          choicesContainer,
          buttonContainer,
          container,
          selectedFieldName,
          [choice]
        );
      }
    }
  }

  eventSelect.addEventListener('fwChange', async function () {
    const selectedEventValue = eventSelect.value;
    console.log(`Event changed to: ${selectedEventValue}`);

    fieldNameContainer.innerHTML = '';
    choicesContainer.innerHTML = '';
    buttonContainer.innerHTML = '';

    if (!selectedEventValue) {
      console.error("Selected event value is undefined or empty.");
      return;
    }

    if (!ticketworkflowconditions[selectedEventValue]) {
      ticketworkflowconditions[selectedEventValue] = {};
    }

    await fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container);
  });
}

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

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

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

      console.log(`Starting fieldschoosingvalues with selectedEventValue: ${selectedEventValue}`);
      console.log(`Starting field name to map: ${selectedFieldName}`);
      console.log(`Starting choice name to map: ${selectedChoices}`);

      if (selectedFieldName) {
        const individualFieldContainer = document.createElement('div');
        individualFieldContainer.classList.add('field-container');
        fieldNameContainer.appendChild(individualFieldContainer);

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

        for (const choice of selectedChoices) {
          console.log(`Mapping existing choice ${choice} to dropdown for field ${selectedFieldName} in event ${selectedEventValue}`);

          if (!ticketworkflowconditions[selectedEventValue]) {
            ticketworkflowconditions[selectedEventValue] = {};
          }

          if (!ticketworkflowconditions[selectedEventValue][selectedFieldName]) {
            ticketworkflowconditions[selectedEventValue][selectedFieldName] = [];
          }

          if (!ticketworkflowconditions[selectedEventValue][selectedFieldName].includes(choice)) {
            ticketworkflowconditions[selectedEventValue][selectedFieldName].push(choice);
            console.log(`Added choice ${choice} to ticketworkflowconditions for field ${selectedFieldName} under event ${selectedEventValue}`);
          } else {
            console.log(`Choice ${choice} already exists for field ${selectedFieldName} under event ${selectedEventValue}`);
          }

          await getFieldnamesfrom1stapi(
            individualFieldContainer,
            fields,
            individualChoicesContainer,
            selectedEventValue,
            buttonContainer,
            container,
            selectedFieldName,
            [choice]
          );
        }
      } else {
        await getFieldnamesfrom1stapi(fieldNameContainer, fields, choicesContainer, selectedEventValue, buttonContainer, container);
      }
    } 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 = null) {
  if (!selectedEventValue) {
    console.error("getFieldnamesfrom1stapi called with an undefined selectedEventValue.");
    return;
  }

  console.log(`Initializing field dropdown for event ${selectedEventValue}, field: ${selectedFieldName}`);

  const firstDropdown = document.createElement('fw-select');
  firstDropdown.classList.add('field-name-dropdown');
  firstDropdown.setAttribute('label', 'Ticket Fields');
  firstDropdown.setAttribute('required', 'true');
  firstDropdown.setAttribute('placeholder', 'Choose a field');
  firstDropdown.setAttribute('hint-text', 'Select singular option');

  // const defaultOption = document.createElement('fw-select-option');
  // defaultOption.setAttribute('value', 'default');
  // defaultOption.textContent = 'Select Field';
  // firstDropdown.appendChild(defaultOption);

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

    if (selectedFieldName && field.name === selectedFieldName) {
      option.setAttribute('selected', 'selected');
      console.log(`Pre-selected field: ${selectedFieldName}`);
    }
  });

  fieldNameContainer.appendChild(firstDropdown);

  if (selectedFieldName) {
    const selectedField = fields.find(field => field.name === selectedFieldName);
    if (selectedField) {
      await showingitschoices(choicesContainer, selectedField, selectedEventValue, selectedFieldName, buttonContainer, container, fieldNameContainer, selectedChoices);
    }
  }

  firstDropdown.addEventListener('fwChange', async (event) => {
    const selectedFieldName = event.target.value;
    choicesContainer.innerHTML = '';

    const selectedField = fields.find(field => field.name === selectedFieldName);
    if (selectedField) {
      await showingitschoices(choicesContainer, selectedField, selectedEventValue, selectedFieldName, buttonContainer, container, fieldNameContainer);
    } else {
      console.error('Selected Field not found in fields.');
    }
  });
}

async function showingitschoices(
  choicesContainer,
  selectedField,
  selectedEventValue,
  selectedFieldName,
  buttonContainer,
  container,
  fieldNameContainer,
  selectedChoices = null
) {
  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 option');

  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 && selectedChoices.includes(String(choice.id))) {
      option.setAttribute('selected', 'selected');
      console.log(`Pre-selected choice: ${choice.id} for field: ${selectedFieldName}`);
    }
  });

  choicesContainer.appendChild(choicesDropdown);

  if (buttonContainer.childNodes.length === 0) {
    // Create the Add button
    const addButton = document.createElement('fw-button');
    addButton.setAttribute('color', 'primary');
    addButton.textContent = 'Add';
    buttonContainer.appendChild(addButton);

    // Create the Delete button for individual fields and choices
    const deleteFieldButton = document.createElement('fw-button');
    deleteFieldButton.setAttribute('color', 'warning');
    deleteFieldButton.textContent = 'Delete';
    buttonContainer.appendChild(deleteFieldButton);

    // Only add the Delete Event button if this is the first dropdown set
    if (container.querySelectorAll('.choices-container').length === 1 && !buttonContainer.querySelector('.delete-event-button')) {
      const deleteEventButton = document.createElement('fw-button');
      deleteEventButton.classList.add('delete-event-button');
      deleteEventButton.setAttribute('color', 'danger');
      deleteEventButton.textContent = 'Delete Event';
      buttonContainer.appendChild(deleteEventButton);

      deleteEventButton.addEventListener('click', () => {
        const eventContainer = container.closest('.event-container');
        if (eventContainer) {
          eventContainer.remove();
          delete ticketworkflowconditions[selectedEventValue];
          console.log('Delete Event button clicked. Event removed from DOM and ticketworkflowconditions.');
        } else {
          console.error('Event container not found for deletion.');
        }
      });
    }

    addButton.addEventListener('click', () => {
      createAdditionalDropdowns(container);
    });

    deleteFieldButton.addEventListener('click', () => {
      fieldNameContainer.remove();
      choicesContainer.remove();
      buttonContainer.remove();
      delete ticketworkflowconditions[selectedEventValue][selectedFieldName];
      console.log(`Delete button clicked. Removed field: ${selectedFieldName} and its choices.`);
    });
  }

  choicesDropdown.addEventListener('fwChange', (event) => {
    const selectedChoiceId = event.target.value;

    if (!selectedEventValue || !selectedFieldName) {
      console.error('Event or field name is undefined');
      return;
    }

    if (!ticketworkflowconditions[selectedEventValue]) {
      ticketworkflowconditions[selectedEventValue] = {};
    }

    if (!ticketworkflowconditions[selectedEventValue][selectedFieldName]) {
      ticketworkflowconditions[selectedEventValue][selectedFieldName] = [];
    }

    if (!ticketworkflowconditions[selectedEventValue][selectedFieldName].includes(selectedChoiceId)) {
      ticketworkflowconditions[selectedEventValue][selectedFieldName].push(selectedChoiceId);
      console.log(`Added choice ID ${selectedChoiceId} to field ${selectedFieldName} for event ${selectedEventValue}`);
    } else {
      console.warn(`Choice ID ${selectedChoiceId} already exists in ${selectedFieldName}`);
    }

    console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
  });
}

function createAdditionalDropdowns(container) {
  const fieldNameContainer = document.createElement('div');
  fieldNameContainer.classList.add('col-md-2', 'field-name-container');
  fieldNameContainer.classList.add('offset-md-2');
  
  const choicesContainer = document.createElement('div');
  choicesContainer.classList.add('col-md-2', 'choices-container');
  
  const buttonContainer = document.createElement('div');
  buttonContainer.classList.add('col-md-3', 'button-container', 'mt-3');
  
  container.appendChild(fieldNameContainer);
  container.appendChild(choicesContainer);
  container.appendChild(buttonContainer);

  // Call `fieldschoosingvalues` for this additional dropdown
  fieldschoosingvalues(
    container.querySelector('.event-name-dropdown').value,
    fieldNameContainer,
    choicesContainer,
    buttonContainer,
    container
  );
}


do this :

on creating additional remove add button keep delete button alone