let ticketworkflowconditions = [];

async function loadExistingWorkflowConditions() {
  
  let workflowConditions = alldata.ticket_workflow_conditions;
  
  console.log("Mapping Data for Workflows:", workflowConditions);

  await addNewRule(null, workflowConditions); 
}

async function addNewRule(eventName, workflowConditions) {

   console.log("Existing Workflow Conditions:", workflowConditions);

  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 = 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>
  `;

  // Append the dropdown to the newDropdownSet
  newDropdownSet.querySelector('.event-name-dropdown').value = selectedEvent;

  // Handle the dropdown change event
  const eventSelect = newDropdownSet.querySelector('.event-name-dropdown');
  eventSelect.addEventListener('fwChange', async () => {
      const newEvent = eventSelect.value;

      // Reset ticketworkflowconditions for new event
      if (newEvent !== selectedEvent) {
          ticketworkflowconditions = { [newEvent]: { combinations: [{ isEnabled: true, fields: {} }] } };

          // Clear existing field-related containers
          newDropdownSet.querySelectorAll('.field-name-container, .choices-container, .button-container').forEach(container => container.remove());

          // Create containers for the fields, choices, and buttons
          const fieldNameContainer = document.createElement('div');
          fieldNameContainer.classList.add('col-md-2', 'field-name-container');
          newDropdownSet.appendChild(fieldNameContainer);

          const choicesContainer = document.createElement('div');
          choicesContainer.classList.add('col-md-2', 'choices-container');
          newDropdownSet.appendChild(choicesContainer);

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

          // Populate dropdowns with the newly selected event using the existing logic
          await fieldschoosingvalues(newEvent, fieldNameContainer, choicesContainer, buttonContainer, newDropdownSet);
          console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
      }
  });

  // Append the newDropdownSet to the eventContainer
  eventContainer.appendChild(newDropdownSet);
  // Finally, append the eventContainer to the main ticketworkflow container
  ticketworkflowContainer.appendChild(eventContainer);
}

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

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

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

          console.log(`Starting fieldschoosingvalues with selectedEventValue: ${selectedEventValue}`);

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

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

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

    // Set the initial selected field if provided
    if (selectedFieldName && field.name === selectedFieldName) {
      option.setAttribute('selected', 'selected');
    }
  });

  fieldNameContainer.appendChild(fieldDropdown);

  // Initial mapping of choices in case a field is already selected
  if (selectedFieldName) {
    const selectedField = fields.find(field => field.name === selectedFieldName);
    if (selectedField) {
      await showingitschoices(choicesContainer, selectedField, selectedEventValue, selectedFieldName, buttonContainer, container, fieldNameContainer, selectedChoices);

      // Ensure that ticketworkflowconditions structure is initialized for the event.
      if (!ticketworkflowconditions[selectedEventValue]) {
        ticketworkflowconditions[selectedEventValue] = { combinations: [] }; // Initialize if not present
      }

      // Get the latest combination or create a new one if none exists
      const combinationsArray = ticketworkflowconditions[selectedEventValue].combinations;
      let latestCombination;

      if (combinationsArray.length > 0) {
        // Get the latest combination
        latestCombination = combinationsArray[combinationsArray.length - 1];
      } else {
        // If no combination exists, create and push a new one
        latestCombination = { isEnabled: true, fields: {} };
        combinationsArray.push(latestCombination);
      }

      // Update the selected field in the latest combination's fields
      // Ensure previous values are preserved
      latestCombination.fields[selectedFieldName] = selectedChoices ? selectedChoices[0] : null;

      console.log(`Updated ticketworkflowconditions with mapped fields: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
    } else {
      console.error('Field not found in Dropdown');
    }
  }

  // Update logic for field change event
  fieldDropdown.addEventListener('fwChange', async (event) => {
    const newSelectedFieldName = event.target.value;
    choicesContainer.innerHTML = '';

    const newSelectedField = fields.find(field => field.name === newSelectedFieldName);
    if (newSelectedField) {
      await showingitschoices(choicesContainer, newSelectedField, selectedEventValue, newSelectedFieldName, buttonContainer, container, fieldNameContainer);

      // Get the latest combination for the selected event
      const latestCombination = ticketworkflowconditions[selectedEventValue].combinations[ticketworkflowconditions[selectedEventValue].combinations.length - 1];

      // Update JSON with newly selected field and choice in the latest combination
      const choiceValue = choicesContainer.querySelector('.choices-dropdown')?.value || null;
      if (latestCombination) {
        latestCombination.fields[newSelectedFieldName] = choiceValue; // Add to the latest combination fields
      } else {
        console.error("No latest combination found for updating fields.");
      }

      console.log(`Field changed: ${newSelectedFieldName}, Choice: ${choiceValue}`);
      console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
    } else {
      console.error('Field not found in Dropdown');
    }
  });



}

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

  // Check if the button has already been added
  if (!buttonContainer.querySelector('.btn-primary')) {
    const addButton = document.createElement('button');
    addButton.textContent = 'Add';
    addButton.classList.add('btn', 'btn-primary', 'mt-2');
    buttonContainer.appendChild(addButton);

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

  choicesDropdown.addEventListener('fwChange', (event) => {
    const selectedChoiceId = event.target.value;
  
    // Ensure the event is initialized in ticketworkflowconditions
    if (!ticketworkflowconditions[selectedEventValue]) {
      ticketworkflowconditions[selectedEventValue] = { combinations: [{ isEnabled: true, fields: {} }] };
    }
  
    // Get the latest combination
    const latestCombination = ticketworkflowconditions[selectedEventValue].combinations[
      ticketworkflowconditions[selectedEventValue].combinations.length - 1
    ];
  
    // Update the field's value in the latest combination as a key-value pair
    latestCombination.fields[selectedFieldName] = selectedChoiceId;
  
    console.log(`Updated JSON with field: ${selectedFieldName}, choice: ${selectedChoiceId}`);
    console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
  });
  
}

on choosing choices dropdown, the json should like this


[
  {
    "eventName": "TicketCreate",
    "isEnabled": true,
    "fields": {
      "status": "3"
    }
  }
  ]