document.addEventListener("DOMContentLoaded", function() {
  const addIcon = document.getElementById("add-icon");
  const dropdownMenu = document.getElementById("dropdown-menu");
  const wordInput = document.getElementById("word-input");
  const numWordsInput = document.getElementById("num-words-input");
  const generateButton = document.getElementById("generate-button");
  const resultElement = document.getElementById("word-list");
  const resetButton = document.getElementById("reset");
  const saveButton = document.createElement("button");
  saveButton.id = "save-button";
  saveButton.textContent = "Save";
  resetButton.insertAdjacentElement("afterend", saveButton);
  const modal = document.getElementById("listModal");
  const modalBody = document.getElementById("modal-body");
  const createListButton = document.getElementById("create-list");
  const viewListButton = document.getElementById("view-list");
  const closeModalButton = document.getElementById("close-modal");
  const deleteAllButton = document.createElement("button");
  deleteAllButton.id = "delete-all";
  deleteAllButton.textContent = "Delete All";
  closeModalButton.insertAdjacentElement("afterend", deleteAllButton);

  // Store lists in local storage
  let lists = JSON.parse(localStorage.getItem('lists')) || [];
  let definitionMap = {};

  // Toggle dropdown menu visibility
  addIcon.addEventListener("click", function() {
      dropdownMenu.style.display = dropdownMenu.style.display === "block" ? "none" : "block";
  });

  // Hide the dropdown menu if the user clicks outside of it
  document.addEventListener("click", function(event) {
      if (!addIcon.contains(event.target) && !dropdownMenu.contains(event.target)) {
          dropdownMenu.style.display = "none";
      }
  });

  // Create List button click handler
  createListButton.addEventListener("click", function() {
      openCreateListModal();
  });

  // View List button click handler
  viewListButton.addEventListener("click", function() {
      openViewListModal();
  });

  // Close modal when the user clicks on Close button
  closeModalButton.addEventListener("click", function() {
      modal.style.display = "none";
  });

  // Close modal when the user clicks outside of the modal
  window.addEventListener("click", function(event) {
      if (event.target === modal) {
          modal.style.display = "none";
      }
  });

  // Create Flip Card
function createFlipCard(word) {
  const card = document.createElement('li');
  card.classList.add('flip-container');
  card.innerHTML = `
    <div class="flip-card">
      <div class="front">${word}</div>
      <div class="back">${definitionMap[word] || 'Definition not found'}</div>
    </div>
  `;

  card.addEventListener('click', () => {
    card.querySelector('.flip-card').classList.toggle('flipped');
  });

  return card;
}


  // Generate random words with definitions
  async function generateRandomWords() {
      resultElement.classList.remove("error");

      const words = wordInput.value.split(",").map(word => word.trim()).filter(word => word !== "");
      if (words.length === 0) {
          resultElement.classList.add("error");
          resultElement.innerHTML = "Please enter some words separated by commas.";
          return;
      }

      const numWords = Math.min(numWordsInput.value, words.length);
      let selectedWords = getRandomWords(words, numWords);

      resultElement.innerHTML = ''; // Clear previous results
      for (const word of selectedWords) {
          const definition = await fetchDefinition(word);
          definitionMap[word] = definition;
          resultElement.appendChild(createFlipCard(word));
      }
      updateWordCounter();
  }

  // Get random words from the list
  function getRandomWords(words, numWords) {
      const shuffled = words.sort(() => 0.5 - Math.random());
      return shuffled.slice(0, numWords);
  }

  // Fetch word definition from API
  async function fetchDefinition(word) {
      try {
          const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`);
          if (!response.ok) {
              if (response.status === 404) {
                  return "Definition not found.";
              }
              throw new Error("Network response was not ok.");
          }
          const data = await response.json();
          if (data && data[0] && data[0].meanings && data[0].meanings[0] && data[0].meanings[0].definitions && data[0].meanings[0].definitions[0]) {
              return data[0].meanings[0].definitions[0].definition;
          } else {
              return "Definition not found.";
          }
      } catch (error) {
          console.error("Error fetching definition:", error);
          return "Definition not found.";
      }
  }

  // Attach event listeners to buttons
  generateButton.addEventListener("click", generateRandomWords);
  resetButton.addEventListener("click", function() {
      resultElement.innerHTML = "";
      wordInput.value = "";
      numWordsInput.value = 1;
      updateWordCounter();
  });

  // Save button click handler
  saveButton.addEventListener("click", function() {
      const words = wordInput.value.split(",").map(word => word.trim()).filter(word => word !== "");
      if (words.length === 0) {
          alert("Please enter some words to save.");
          return;
      }
      const listName = prompt("Enter the name of the list:");
      if (listName) {
          lists.push({ name: listName, words });
          localStorage.setItem('lists', JSON.stringify(lists));
          alert(`List "${listName}" saved.`);
      } else {
          alert("List name cannot be empty.");
      }
  });

  // Function to open create list modal
  function openCreateListModal() {
      // Clear previous content of modal body
      modalBody.innerHTML = "";

      // Create input field and submit button for entering list name
      const inputField = document.createElement("input");
      inputField.setAttribute("type", "text");
      inputField.setAttribute("placeholder", "Enter the name of the list");
      inputField.style.marginRight = "10px";

      const submitButton = document.createElement("button");
      submitButton.textContent = "Create";
      submitButton.addEventListener("click", function() {
          const listName = inputField.value.trim();
          if (listName) {
              lists.push({ name: listName, words: [] });
              localStorage.setItem('lists', JSON.stringify(lists));
              modal.style.display = "none"; // Hide modal after creating list
              alert(`List "${listName}" created.`);
              inputField.value = ""; // Clear input field
              openViewListModal(); // After creating, open view list modal
          } else {
              alert("Please enter a valid list name.");
          }
      });

      const cancelButton = document.createElement("button");
      cancelButton.textContent = "Cancel";
      cancelButton.addEventListener("click", function() {
          modal.style.display = "none";
      });

      modalBody.appendChild(inputField);
      modalBody.appendChild(submitButton);
      modalBody.appendChild(cancelButton);

      modal.style.display = "block"; // Display modal
      dropdownMenu.style.display = "none"; // Hide dropdown menu
  }

  // Function to open view list modal
  function openViewListModal() {
      if (lists.length === 0) {
          modalBody.innerHTML = "<p>No lists available.</p>";
      } else {
          modalBody.innerHTML = ""; // Clear previous content

          lists.forEach((list, index) => {
              const listItem = document.createElement("div");
              listItem.className = "list-item";
              listItem.textContent = list.name;

              // Add view, open, and delete buttons for each list item
              const viewButton = document.createElement("button");
              viewButton.textContent = "View";
              viewButton.addEventListener("click", function() {
                  openWordListModal(index);
              });

              const openButton = document.createElement("button");
              openButton.textContent = "Open";
              openButton.addEventListener("click", function() {
                  openList(index);
              });

              const deleteButton = document.createElement("button");
              deleteButton.textContent = "Delete";
              deleteButton.addEventListener("click", function() {
                  lists.splice(index, 1);
                  localStorage.setItem('lists', JSON.stringify(lists));
                  openViewListModal(); // Refresh view after deleting
              });

              listItem.appendChild(viewButton);
              listItem.appendChild(openButton);
              listItem.appendChild(deleteButton);
              modalBody.appendChild(listItem);
          });
      }

      modal.style.display = "block"; // Display modal
      dropdownMenu.style.display = "none"; // Hide dropdown menu
  }

  // Function to open word list modal
  function openWordListModal(listIndex) {
      // Clear previous content of modal body
      modalBody.innerHTML = "";

      // Display list name
      const listName = document.createElement("h2");
      listName.textContent = lists[listIndex].name;
      modalBody.appendChild(listName);

      // Display words
      const wordList = document.createElement("ul");
      lists[listIndex].words.forEach(word => {
          const wordItem = document.createElement("li");
          wordItem.textContent = word;
          wordList.appendChild(wordItem);
      });
      modalBody.appendChild(wordList);

      // Add input field and button for adding words to the list
      const wordInputField = document.createElement("input");
      wordInputField.setAttribute("type", "text");
      wordInputField.setAttribute("placeholder", "Enter words separated by commas");
      wordInputField.style.marginRight = "10px";

      const addButton = document.createElement("button");
      addButton.textContent = "Add";
      addButton.addEventListener("click", function() {
          const words = wordInputField.value.split(",").map(word => word.trim());
          lists[listIndex].words.push(...words);
          localStorage.setItem('lists', JSON.stringify(lists));
          openWordListModal(listIndex); // Refresh view after adding words
      });

      const closeButton = document.createElement("button");
      closeButton.textContent = "Close";
      closeButton.addEventListener("click", function() {
          modal.style.display = "none";
      });

      modalBody.appendChild(wordInputField);
      modalBody.appendChild(addButton);
      modalBody.appendChild(closeButton);

      modal.style.display = "block"; // Display modal
  }

  // Function to open list and populate the main search bar
  function openList(listIndex) {
      wordInput.value = lists[listIndex].words.join(", ");
      modal.style.display = "none"; // Hide modal
  }

  // Delete all button click handler
  deleteAllButton.addEventListener("click", function() {
      if (confirm("Are you sure you want to delete all lists?")) {
          lists = [];
          localStorage.setItem('lists', JSON.stringify(lists));
          openViewListModal(); // Refresh view after deleting all lists
      }
  });

  // Function to update word counter
  function updateWordCounter() {
      const wordCount = wordInput.value.split(",").filter(word => word.trim() !== "").length;
      document.getElementById("word-counter").textContent = `${wordCount} words`;
  }

  // Event listener to update word counter when input changes
  wordInput.addEventListener("input", updateWordCounter);

  // Initial call to update word counter on page load
  updateWordCounter();
});