async function initializeEventDropdown(container, obj, ruleIndex) {
  console.log("container, obj, ruleIndex", container, obj, ruleIndex);

  const eventSelect = container.querySelector('.event-name-dropdown');
  const selectedEventValue = eventSelect.value;

  console.log(`initializeEventDropdown - Initial selected event: ${selectedEventValue}`);

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

  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 = '-20px';
    container.appendChild(buttonContainer);
  }

  if (!toggleContainer) {
    toggleContainer = document.createElement('div');
    toggleContainer.classList.add('col-md-2', 'toggle-container');
    toggleContainer.style.position = 'absolute';
    toggleContainer.style.right = '5px';
    container.style.position = 'relative';
    container.appendChild(toggleContainer);
  }

  toggleContainer.style.display = 'flex';
  toggleContainer.style.flexDirection = 'column';
  toggleContainer.style.alignItems = 'center';

  const toggleSwitch = document.createElement('fw-toggle');
  toggleSwitch.setAttribute('size', 'medium');
  toggleSwitch.checked = obj ? obj.checked : true;
  toggleContainer.appendChild(toggleSwitch);

  const deleteButton = document.createElement('fw-button');
  deleteButton.textContent = 'Delete Event';
  deleteButton.setAttribute('color', 'danger');
  deleteButton.style.marginTop = '25px';
  toggleContainer.appendChild(deleteButton);

  console.log("obj", obj);

  if (obj && obj.event.combination.length > 0) {
    const fields = obj.event.combination;
    for (let index = 0; index < fields.length; index++) {
      const element = fields[index];
      for (const [fieldName, fieldValue] of Object.entries(element)) {
        await fieldschoosingvalues(
          selectedEventValue,
          fieldNameContainer,
          choicesContainer,
          buttonContainer,
          container,
          fieldName,
          [fieldValue],
          obj,
          ruleIndex,
          index
        );
      }
    }
  }

  updateDropdownAccessibility(toggleSwitch.checked);

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

  deleteButton.addEventListener('click', () => {
    console.log("Delete Event button clicked.");

    const eventContainer = container.closest('.event-container');
    if (eventContainer) {
      const modal = document.getElementById('composition');
      if (modal) {
        modal.setAttribute('is-open', 'true');
        modal.querySelector('fw-modal-title').innerHTML = `<span>Delete Event</span>`;
        modal.querySelector('fw-modal-content').innerHTML = `
          <span>Are you sure you want to delete this event?</span>
        `;

        modal.addEventListener(
          'fwSubmit',
          () => {
            eventContainer.remove();
            console.log("Event container successfully removed from DOM.");

            if (Array.isArray(ticketworkflowconditions)) {
              ticketworkflowconditions.splice(ruleIndex, 1);
              console.log(`Event at index ${ruleIndex} successfully removed from ticketworkflowconditions array.`);
            } else if (ticketworkflowconditions[ruleIndex]) {
              delete ticketworkflowconditions[ruleIndex];
              console.log(`Event at index ${ruleIndex} successfully removed from ticketworkflowconditions object.`);
            }

            console.log("Updated ticketworkflowconditions:", JSON.stringify(ticketworkflowconditions, null, 2));
            showSuccessToast("Event successfully deleted!");
            modal.removeAttribute('is-open');
          },
          { once: true }
        );
      }
    }
  });

  function updateIsEnabledState(selectedEventValue, isChecked) {
    if (!selectedEventValue) {
      console.error("Event is not selected.");
      return;
    }
    let data = {
      ...ticketworkflowconditions[ruleIndex]
    };
    ticketworkflowconditions[ruleIndex] = {
      ...data,
      checked: isChecked
    };

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

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

    const buttonContainers = container.querySelectorAll('.button-container');
    buttonContainers.forEach(buttonContainer => {
      const buttons = buttonContainer.querySelectorAll('button, fw-button');
      buttons.forEach(button => {
        button.disabled = !isChecked;
      });
    });
  }
}

async function fieldschoosingvalues(
  selectedEventValue,
  fieldNameContainer,
  choicesContainer,
  buttonContainer,
  container,
  selectedFieldName = null,
  selectedChoices = null, obj, ruleIndex, fieldIndex) {
  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.name !== "ticket_type"
        // field.required_for_agents
      );

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

      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, obj, ruleIndex, fieldIndex);
      } else {
        await getFieldnamesfrom1stapi(
          fieldNameContainer,
          fields,
          choicesContainer,
          selectedEventValue,
          buttonContainer, container, null, null, obj, ruleIndex, fieldIndex);
      }
    } 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,
  obj,
  ruleIndex,
  fieldIndex
) {
  if (!selectedEventValue) {
    console.error("Select an event before proceeding.");
    return;
  }

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

  const selectedFields = Array.from(container.querySelectorAll('.field-name-dropdown'))
    .map((dropdown) => dropdown.value)
    .filter((value) => value);

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

      if (selectedFieldName && field.name === selectedFieldName) {
        option.setAttribute('selected', 'selected');
      }
    });


  fieldNameContainer.appendChild(fieldDropdown);

  // Create the buttons
  const deleteButton = document.createElement('fw-button');
  deleteButton.setAttribute('size', 'icon');
  deleteButton.classList.add('delete-button');
  deleteButton.innerHTML = '<fw-icon name="delete" size="20" color="white"></fw-icon>';

  const deleteButtonWrapper = document.createElement('div');
  deleteButtonWrapper.classList.add('delete-button-container', 'mt-5');
  deleteButtonWrapper.appendChild(deleteButton);
  buttonContainer.appendChild(deleteButtonWrapper);

  const existingAddButton = container.querySelector('.add-button');
  if (existingAddButton) {
    existingAddButton.remove();
  }

  const addButton = document.createElement('fw-button');
  addButton.setAttribute('size', 'icon');
  addButton.classList.add('add-button');
  addButton.innerHTML = '<fw-icon name="plus" size="20" color="white"></fw-icon>';
  addButton.style.marginTop = '16px';
  addButton.disabled = true; // Initially disable the Add button

  if (fieldIndex === container.querySelectorAll('.field-name-dropdown').length - 1) {
    // const buttonWrapper = document.createElement('div');
    // buttonWrapper.classList.add('button-wrapper');
    // buttonWrapper.appendChild(addButton);
    buttonContainer.appendChild(addButton);

    // buttonContainer.appendChild(buttonWrapper);
  }

addButton.addEventListener("click", () => {
  console.log(ticketworkflowconditions[ruleIndex].event);
  const newIndex = ticketworkflowconditions[ruleIndex].event.combination.length;
  createAdditionalDropdowns(container, obj, ruleIndex, newIndex);

  // Dynamically update Add Button visibility after adding a dropdown
  checkAddButtonVisibility();
});



// Delete Button Logics
deleteButton.addEventListener("click", () => {
  console.log(`Delete button clicked for mapping at index ${fieldIndex}`);

  // Get modal
  const modal = document.getElementById("composition");
  if (modal) {
    modal.setAttribute("is-open", "true");
    modal.querySelector("fw-modal-title").innerHTML = `<span>Delete Mapping</span>`;
    modal.querySelector("fw-modal-content").innerHTML = `
      <span>Are you sure you want to delete this field mapping?</span>
    `;

    // Add event listener for the modal's "Yes" (submit) button
    modal.addEventListener(
      "fwSubmit",
      () => {        
        if (fieldIndex === 0) {
          console.log("Resetting the first field and clearing its choices.");

          fieldDropdown.value = ""; 
          fieldDropdown.setAttribute("placeholder", "Choose a field");
          fieldDropdown.disabled = false;

          choicesContainer.innerHTML = '<br><br><br><div class="temporary style" style="margin-bottom: 9px;"></div>';
          choicesContainer.style.display = "block"; 
          
          const findRule = ticketworkflowconditions[ruleIndex];
          if (findRule) {
            const combination = findRule.event.combination;
            combination[fieldIndex] = { field: null }; 

            ticketworkflowconditions[ruleIndex] = {
              ...findRule,
              event: { ...findRule.event, combination },
            };
          }

          modal.removeAttribute("is-open");          
          checkAddButtonVisibility();
          return;
        }

        // For other fields, perform DELETE logic
        const findRule = ticketworkflowconditions[ruleIndex];
        if (findRule) {
          const currentDropdowns = container.querySelectorAll(".field-name-dropdown");
          const currentDropdownIndex = Array.from(currentDropdowns).indexOf(fieldDropdown);

          if (currentDropdownIndex !== -1) {
            const combination = findRule.event.combination;
            combination.splice(currentDropdownIndex, 1); // Remove the combination at the correct index

            ticketworkflowconditions[ruleIndex] = {
              ...findRule,
              event: { ...findRule.event, combination },
            };
          }
        }

        // UI Cleanup: Remove field dropdown, choices, and delete button
        fieldNameContainer.removeChild(fieldDropdown);
        choicesContainer.innerHTML = ""; // Clear the choices container
        buttonContainer.removeChild(deleteButtonWrapper);

        modal.removeAttribute("is-open"); // Close the modal

        // Dynamically recheck Add Button visibility after a field is deleted
        checkAddButtonVisibility();
      },
      { once: true } // Listener should execute only once
    );

    modal.querySelector("fw-modal-footer").addEventListener(
      "fwClose",
      () => {
        modal.removeAttribute("is-open"); // Close modal
        console.log("Delete operation was cancelled.");
      },
      { once: true }
    );
  } else {
    console.error("Modal element with ID 'composition' not found.");
  }
});



// // Field Dropdown Handling
// fieldDropdown.addEventListener("fwChange", async (event) => {
//   const newSelectedFieldName = event.target.value;

//   // choicesContainer.innerHTML = ""; // Clear previous choices

//   const newSelectedField = fields.find((field) => field.name === newSelectedFieldName);
//   if (newSelectedField) {
//     const findRule = ticketworkflowconditions[ruleIndex];
//     if (findRule) {
//       const combination = findRule.event.combination;

//       const newKeyValue = { [newSelectedFieldName]: null };
//       combination.splice(fieldIndex, 1, newKeyValue);

//       if (combination) {
//         console.log(`Field changed. Updated backend:`, ticketworkflowconditions);
//       }
//     }

//     await showingitschoices(
//       choicesContainer,
//       newSelectedField,
//       selectedEventValue,
//       newSelectedFieldName,
//       buttonContainer,
//       container,
//       fieldNameContainer,
//       null,
//       obj,
//       ruleIndex,
//       fieldIndex
//     );

//     console.log(`Field changed to: ${newSelectedFieldName}`);
//   } else {
//     // console.error("Field not found in the Dropdown");
//   }

//   // Check Add Button visibility dynamically when a dropdown value changes
//   checkAddButtonVisibility();
// });



fieldDropdown.addEventListener("fwChange", async (event) => {
  const newSelectedFieldName = event.target.value;

  const newSelectedField = fields.find((field) => field.name === newSelectedFieldName);
  if (newSelectedField) {
    const findRule = ticketworkflowconditions[ruleIndex];
    if (findRule) {
      const combination = findRule.event.combination;

      // Update backend with the new key-value format
      const newKeyValue = { [newSelectedFieldName]: [] }; // Initialize with an empty array
      combination.splice(fieldIndex, 1, newKeyValue);

      console.log(`Field changed. Updated backend:`, JSON.stringify(ticketworkflowconditions, null, 2));
    }

    // Show choices for the selected field
    await showingitschoices(
      choicesContainer,
      newSelectedField,
      selectedEventValue,
      newSelectedFieldName,
      buttonContainer,
      container,
      fieldNameContainer,
      null,
      obj,
      ruleIndex,
      fieldIndex
    );

    console.log(`Field changed to: ${newSelectedFieldName}`);
  } else {
    console.error("Field not found in the Dropdown");
  }

  // Check Add Button visibility dynamically when a dropdown value changes
  checkAddButtonVisibility();
});




// Function to Check Add Button Visibility
function checkAddButtonVisibility() {
  const dropdowns = container.querySelectorAll(".field-name-dropdown");
  const selectedFieldValues = Array.from(dropdowns)
    .map((dropdown) => dropdown.value)
    .filter((value) => value !== ""); 

  const areAllFieldsSelected = selectedFieldValues.length >= fields.length;

  const lastDropdownWrapper =
    dropdowns.length > 0
      ? dropdowns[dropdowns.length - 1].closest(".button-container")
      : null;

  // If all fields are selected, remove the Add Button
  if (areAllFieldsSelected) {
    console.log("All fields are selected. Hiding Add Button.");
    if (addButton.parentNode) {
      addButton.parentNode.appendChild(addButton);
      addButton.disabled = false; 
      // addButton.style.visibility = "hidden";
    }
  } else {
    console.log("Fields are still available. Add Button will be shown.");
    
    if (dropdowns.length > 0 && lastDropdownWrapper) {
      if (!lastDropdownWrapper.contains(addButton)) {
        lastDropdownWrapper.appendChild(addButton); 
        addButton.style.visibility = "visible";
      }
    }

    addButton.disabled = false; 
  }

  
}





if (selectedFieldName) {
  console.log(`Existing mapping detected for field: ${selectedFieldName}`);

  const selectedField = fields.find((field) => field.name === selectedFieldName);
  if (selectedField) {
    console.log(`Field: ${selectedField.label} (${selectedField.name}) is being preloaded with existing choices.`);

    await showingitschoices(
      choicesContainer,
      selectedField,
      selectedEventValue,
      selectedFieldName,
      buttonContainer,
      container,
      fieldNameContainer,
      selectedChoices,
      obj,
      ruleIndex,
      fieldIndex
    );

    const findRule = ticketworkflowconditions[ruleIndex];
    const combination = findRule.combination;
    const newKeyValue = { [selectedFieldName]: selectedChoices ? selectedChoices[0] : null };
    combination.splice(fieldIndex, 1, newKeyValue);
    ticketworkflowconditions[ruleIndex] = { ...findRule, combination };

    console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
  } else {
    console.error(`Field not found in Dropdown for existing mapping: ${selectedFieldName}`);
  }
}

}

async function showingitschoices(
  choicesContainer,
  selectedField,
  selectedEventValue,
  selectedFieldName,
  buttonContainer,
  container,
  fieldNameContainer,
  selectedChoices = null,
  obj,
  ruleIndex,
  fieldIndex
) {
  choicesContainer.innerHTML = '';

  console.log("Existing Choices Values:", selectedChoices);

  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 multiple options');
  choicesDropdown.setAttribute('multiple', 'true');

  // // Map choices and pre-select based on selectedChoices
  // selectedField.choices.forEach((choice) => {
  //   const option = document.createElement('fw-select-option');
  //   option.setAttribute('value', choice.id);
  //   option.textContent = choice.value;

  //   // // Check if this choice is in the selectedChoices array
  //   // if (selectedChoices && selectedChoices.includes(String(choice.id))) {
  //   //   option.setAttribute('selected', 'true');
  //   //   console.log(`Existing value mapped: ${choice.value} (ID: ${choice.id}) for field: ${selectedFieldName}`);
  //   // }

  //   choicesDropdown.appendChild(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);
console.log(`Dropdown added to choicesContainer.`);
















  choicesContainer.appendChild(choicesDropdown);

  // Event listener for fwChange to update JSON with selected choices
  choicesDropdown.addEventListener('fwChange', (event) => {
    const selectedChoiceIds = Array.isArray(event.target.value) ? event.target.value : [event.target.value];

    const findRule = ticketworkflowconditions[ruleIndex];
    const combination = findRule.event.combination;
    const newKeyValue = { [selectedFieldName]: selectedChoiceIds.length ? selectedChoiceIds : null };
    combination.splice(fieldIndex, 1, newKeyValue);

    console.log(`Updated JSON with field: ${selectedFieldName}, choices: ${selectedChoiceIds}`);
    console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
  });
}


function createAdditionalDropdowns(container, obj, ruleIndex, fieldIndex, fields) {
  const fieldNameContainer = document.createElement('div');
  fieldNameContainer.classList.add('col-md-2', 'field-name-container', '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');
  buttonContainer.style.marginTop = '-23px';

  container.appendChild(fieldNameContainer);
  container.appendChild(choicesContainer);
  container.appendChild(buttonContainer);

  fieldschoosingvalues(
    container.querySelector('.event-name-dropdown').value,
    fieldNameContainer,
    choicesContainer,
    buttonContainer,
    container,
    null,
    null,
    obj,
    ruleIndex,
    fieldIndex,
    fields
  );



}





in this, make sure selectedChoices should be handled as arrray not as object