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

    const ticketworkflowContainer = document.getElementById('ticketworkflow-container');
    
    // Create an event container for each existing event
    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';

    // Create and attach the new dropdown set
    const newDropdownSet = await createEventDropdownSet(eventName);
    eventContainer.appendChild(newDropdownSet);
    
    ticketworkflowContainer.appendChild(eventContainer);
    
    // Initialize the dropdown with fieldMappings
    await initializeEventDropdown(eventContainer, 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(eventContainer, 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>
  `;
  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');

  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)) {
      await fieldschoosingvalues(
        eventSelect.value,
        fieldNameContainer,
        choicesContainer,
        buttonContainer,
        container,
        selectedFieldName,
        selectedChoices
      );
    }
  }

  eventSelect.addEventListener('fwChange', async function () {
    const selectedEventValue = eventSelect.value;

    // Clear previous selections
    fieldNameContainer.innerHTML = '';
    choicesContainer.innerHTML = '';
    buttonContainer.innerHTML = '';

    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 {
    const 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 &&
        field.required_for_agents
      );

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

      if (selectedFieldName && selectedChoices) {
        for (const choice of selectedChoices) {
          
          let eventObj = ticketworkflowconditions.find(event => event.eventName === selectedEventValue);
          if (!eventObj) {
            eventObj = { eventName: selectedEventValue, isEnabled: true, combinations: [] };
            ticketworkflowconditions.push(eventObj);
          }

          
          let combination = { fields: [{ name: selectedFieldName, value: choice }] };
          eventObj.combinations.push(combination);

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

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

    const eventObj = ticketworkflowconditions.find(event => event.eventName === selectedEventValue) || 
      { eventName: selectedEventValue, isEnabled: true, combinations: [] }; 

    let combination = { fields: [{ name: selectedFieldName, value: selectedChoiceId }] };
    eventObj.combinations.push(combination);

    if (!ticketworkflowconditions.includes(eventObj)) {
        ticketworkflowconditions.push(eventObj);
    }

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

  fieldschoosingvalues(
    container.querySelector('.event-name-dropdown').value,
    fieldNameContainer,
    choicesContainer,
    buttonContainer,
    container
  );
}



if i choose multiple fields and choices in same events make add that into one field and make tht as a combo and if i choose another dropdown with same event show as another combo