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) {
  const eventSelect = container.querySelector('.event-name-dropdown');
  console.log(`initializeEventDropdown - Initial selected event: ${eventSelect.value}`);

  // Logic to add field containers
  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 (fieldMappings) {
      for (const [selectedFieldName, selectedChoices] of Object.entries(fieldMappings)) {
          for (const choice of selectedChoices) {
              await fieldschoosingvalues(
                  eventSelect.value,
                  fieldNameContainer,
                  choicesContainer,
                  buttonContainer,
                  container,
                  selectedFieldName,
                  [choice]
              );
          }
      }
  }

  eventSelect.addEventListener('fwChange', async function () {
      const selectedEventValue = eventSelect.value;
      
      fieldNameContainer.innerHTML = '';
      choicesContainer.innerHTML = '';
      buttonContainer.innerHTML = '';
      
      // Find or create the corresponding event object
      let eventObj = ticketworkflowconditions.find(event => event.eventName === selectedEventValue);
      
      if (!eventObj) {
          eventObj = { eventName: selectedEventValue, combinations: [] };
          ticketworkflowconditions.push(eventObj);
      }

      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
          );

          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) {
                  // Find or create event and combination for the current event
                  let eventObj = ticketworkflowconditions.find(event => event.eventName === selectedEventValue);

                  if (!eventObj) {
                      eventObj = { eventName: selectedEventValue, combinations: [] };
                      ticketworkflowconditions.push(eventObj);
                  }

                  let combination = eventObj.combinations.find(combo => combo.fields.some(field => field.name === selectedFieldName));

                  if (!combination) {
                      combination = { isEnabled: true, fields: [] };
                      eventObj.combinations.push(combination);
                  }

                  // Add the field and choice to the combination
                  combination.fields.push({ name: selectedFieldName, value: choice });

                  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');
      }
  });

  choicesContainer.appendChild(choicesDropdown);

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

      const deleteFieldButton = document.createElement('fw-button');
      deleteFieldButton.setAttribute('color', 'warning');
      deleteFieldButton.textContent = 'Delete';
      buttonContainer.appendChild(deleteFieldButton);

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

      deleteFieldButton.addEventListener('click', () => {
          fieldNameContainer.remove();
          choicesContainer.remove();
          buttonContainer.remove();

          let eventObj = ticketworkflowconditions.find(event => event.eventName === selectedEventValue);

          if (eventObj) {
              eventObj.combinations = eventObj.combinations.filter(combo => !combo.fields.some(field => field.name === selectedFieldName));
              console.log(`Deleted field: ${selectedFieldName} from event: ${selectedEventValue}`);
          }
      });
  }

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

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

      let eventObj = ticketworkflowconditions.find(event => event.eventName === selectedEventValue);

      if (!eventObj) {
          eventObj = { eventName: selectedEventValue, combinations: [] };
          ticketworkflowconditions.push(eventObj);
      }

      let combination = eventObj.combinations.find(combo => combo.fields.some(field => field.name === selectedFieldName));

      if (!combination) {
          combination = { isEnabled: true, fields: [] };
          eventObj.combinations.push(combination);
      }

      // Find or create field in the combination
      let fieldObj = combination.fields.find(field => field.name === selectedFieldName);

      if (fieldObj) {
          fieldObj.value = selectedChoiceId;
      } else {
          combination.fields.push({ name: selectedFieldName, value: selectedChoiceId });
      }

      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
  );
}


in this isenabled true should for event dropdown only not for fields and choices