since, you have handled json data adding, same way i need to map existing value that you will get from loadexistingworkflowconditions

it has mapped event dropdown now need to mapp the toggle status and fields and choices 


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

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

  // Ensure containers exist
  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 (!togglecontainer) {
    togglecontainer = document.createElement('div');
    togglecontainer.classList.add('col-md-2', 'toggle-container');
    togglecontainer.style.marginLeft = 'auto';     
    togglecontainer.style.marginRight = '5px';     
    togglecontainer.style.marginTop = '30px';      
    container.appendChild(togglecontainer);
  }

  const toggleSwitch = document.createElement('fw-toggle');
  toggleSwitch.setAttribute('size', 'medium');
  toggleSwitch.setAttribute('checked', ''); // Initial checked state
  togglecontainer.appendChild(toggleSwitch);

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

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

  toggleSwitch.addEventListener('fwChange', (event) => {
    const isChecked = event.target.checked;
    updateDropdownAccessibility(isChecked);
    updateIsEnabledState(eventSelect.value, isChecked);
  });

  function updateDropdownAccessibility(isEnabled) {
    const dropdowns = container.querySelectorAll('.choices-dropdown, .field-name-dropdown, .event-name-dropdown');
    dropdowns.forEach(dropdown => {
      dropdown.disabled = !isEnabled;
    });
  }

  function updateIsEnabledState(selectedEventValue, isChecked) {
    if (!selectedEventValue) {
      console.error("Event is not selected.");
      return;
    }

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

    // Just update the 'isEnabled' state for existing combinations
    ticketworkflowconditions[selectedEventValue].combinations.forEach(combination => {
      combination.isEnabled = isChecked;
    });

    console.log(`Toggle for ${selectedEventValue} set to ${isChecked ? 'enabled' : 'disabled'}.`);
    console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
  }
}

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

        await getFieldnamesfrom1stapi(individualFieldContainer, fields, individualChoicesContainer, selectedEventValue, buttonContainer, container, selectedFieldName, selectedChoices);

      } 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) {
    showErrorToast("Select an event before proceeding.");
    return;
  }

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

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

  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);
    } else {
      showErrorToast('Field not found in Dropdown');
    }
  }

  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 {
      showErrorToast('Field not found in Dropdown');
    }
  });
}

async function showingitschoices(
  choicesContainer,
  selectedField,
  selectedEventValue,
  selectedFieldName,
  buttonContainer,
  container,
  fieldNameContainer,
  selectedChoices = null
) {
  // Clear previous choices
  choicesContainer.innerHTML = '';

  // Create the dropdown for choices
  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');

  // Add options to the dropdown from selectedField.choices
  selectedField.choices.forEach(choice => {
    const option = document.createElement('fw-select-option');
    option.setAttribute('value', choice.id);
    option.textContent = choice.value;
    choicesDropdown.appendChild(option);

    // Pre-select choices if selectedChoices array is provided
    if (selectedChoices && selectedChoices.includes(String(choice.id))) {
      option.setAttribute('selected', 'selected');
      console.log(`Pre-selected choice: ${choice.id} for field: ${selectedFieldName}`);
    }
  });

  // Append the dropdown to the container
  choicesContainer.appendChild(choicesDropdown);

  // Add an "Add" button to the button container
  const addButton = document.createElement('button');
  addButton.textContent = 'Add';
  addButton.classList.add('btn', 'btn-primary', 'mt-2');
  buttonContainer.appendChild(addButton);

  // Handle the "Add" button click
  addButton.addEventListener('click', () => {
    createAdditionalDropdowns(container);
  });

  // Event listener for when a choice is selected
  choicesDropdown.addEventListener('fwChange', (event) => {
    const selectedChoiceId = event.target.value;

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

    // Initialize ticketworkflowconditions for the selected event if not already present
    if (!ticketworkflowconditions[selectedEventValue]) {
      ticketworkflowconditions[selectedEventValue] = { combinations: [] };
    }

    // Get the existing combination or create a new one
    let combination = ticketworkflowconditions[selectedEventValue].combinations[0];
    if (!combination) {
      // If no existing combination, create a new one
      combination = { isEnabled: true, fields: {} };
      ticketworkflowconditions[selectedEventValue].combinations.push(combination);
    }

    // Update the existing combination's fields with the new field and choice
    combination.fields[selectedFieldName] = selectedChoiceId;

    console.log(`Updated event ${selectedEventValue} with field ${selectedFieldName} and choice ID ${selectedChoiceId}`);

    // Log the updated ticketworkflowconditions object
    console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
  });
}

function createAdditionalDropdowns(container) {
  // Create new containers for the additional sets
  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');

  // Add a "Delete" button to the button container
  const deleteButton = document.createElement('button');
  deleteButton.textContent = 'Delete';
  deleteButton.classList.add('btn', 'btn-danger', 'mt-2');
  buttonContainer.appendChild(deleteButton);

  // Append the new containers to the main container
  container.appendChild(fieldNameContainer);
  container.appendChild(choicesContainer);
  container.appendChild(buttonContainer);

  // Call fieldschoosingvalues to populate the new set of dropdowns
  fieldschoosingvalues(
    container.querySelector('.event-name-dropdown').value,
    fieldNameContainer,
    choicesContainer,
    buttonContainer,
    container
  );

  // Event listener to handle the "Delete" button click
  deleteButton.addEventListener('click', () => {
    fieldNameContainer.remove();
    choicesContainer.remove();
    buttonContainer.remove();
  });
}