document.addEventListener("DOMContentLoaded", () => {
  // Default menu items
  const defaultMenuItems = [
    {
      id: "improveMail",
      title: "Improve Email",
      prompt:
        "Improve the following email. Do not add any personal comments, only show the text as output:",
      model: "gpt-4o",
    },
    {
      id: "improveText",
      title: "Improve Text",
      prompt:
        "Improve the following text without making it much longer or shorter than it already is. Do not add any personal comments, only show the text as output:",
      model: "gpt-4o",
    },
    {
      id: "seoText",
      title: "Create an SEO Text",
      prompt:
        "You are the world’s best SEO text author. Write an SEO-optimized text of 400–500 words based on the following content. Identify the main keyword and integrate it with a keyword density of 2–3%. Structure the text with HTML elements (h1, h2, h3, p). Highlight the keyword with the strong tag. Only output the HTML code, without HTML, head, or body tags, and without comments. The output should appear as plain text, not in a code block. Here is the relevant text/keyword:",
      model: "gpt-4o",
    },
    {
      id: "explainMe",
      title: "Explain Text",
      prompt:
        "Explain the following text to me, summarize it briefly and in a readable way. Do not add any personal comments, only show the text as output:",
      model: "gpt-4o",
    },
    {
      id: "fixCode",
      title: "Fix Code",
      prompt:
        "Improve or fix the following code snippet. Provide the corrected code without adding any personal comments. Only output the corrected code, but as text and not as code field:",
      model: "gpt-4o",
    },
  ];

  // DOM Elements
  const menuItemsContainer = document.getElementById("menuItems");
  const addMenuItemBtn = document.getElementById("addMenuItem");
  const saveSettingsBtn = document.getElementById("saveSettings");
  const resetSettingsBtn = document.getElementById("resetSettings");
  const menuItemTemplate = document.getElementById("menuItemTemplate");

  // Load settings from storage
  function loadSettings() {
    chrome.storage.sync.get(["menuItems"], (result) => {
      let menuItems = result.menuItems || defaultMenuItems;
      renderMenuItems(menuItems);
    });
  }

  // Save settings to storage
  function saveSettings() {
    const menuItems = [];
    const menuItemElements = document.querySelectorAll(".menu-item");

    menuItemElements.forEach((item) => {
      const id = item.querySelector(".menu-id").value.trim();
      const title = item.querySelector(".menu-title").value.trim();
      const prompt = item.querySelector(".menu-prompt").value.trim();
      const model = item.querySelector(".menu-model").value;

      if (id && title && prompt) {
        menuItems.push({
          id,
          title,
          prompt,
          model,
        });
      }
    });

    chrome.storage.sync.set({ menuItems }, () => {
      // Update context menus
      chrome.runtime.sendMessage({ action: "updateContextMenus" });

      // Show save confirmation
      const saveBtn = document.getElementById("saveSettings");
      const originalText = saveBtn.textContent;
      saveBtn.textContent = "Saved!";
      saveBtn.disabled = true;

      setTimeout(() => {
        saveBtn.textContent = originalText;
        saveBtn.disabled = false;
      }, 1500);
    });
  }

  // Reset settings to default
  function resetSettings() {
    if (confirm("Are you sure you want to reset all settings to default?")) {
      chrome.storage.sync.set({ menuItems: defaultMenuItems }, () => {
        renderMenuItems(defaultMenuItems);
        chrome.runtime.sendMessage({ action: "updateContextMenus" });
      });
    }
  }

  // Render menu items in the UI
  function renderMenuItems(menuItems) {
    menuItemsContainer.innerHTML = "";

    menuItems.forEach((item, index) => {
      const menuItemElement = createMenuItemElement(item);
      menuItemsContainer.appendChild(menuItemElement);
    });
  }

  // Create a menu item element
  function createMenuItemElement(item = {}) {
    const fragment = document.importNode(menuItemTemplate.content, true);
    const menuItem = fragment.querySelector(".menu-item");

    // Set values if provided
    const titleElement = menuItem.querySelector(".menu-item-title");
    const idInput = menuItem.querySelector(".menu-id");
    const titleInput = menuItem.querySelector(".menu-title");
    const promptInput = menuItem.querySelector(".menu-prompt");
    const modelSelect = menuItem.querySelector(".menu-model");

    if (item.id) {
      idInput.value = item.id;
      titleElement.textContent = item.title || "Menu Item";
    }

    if (item.title) titleInput.value = item.title;
    if (item.prompt) promptInput.value = item.prompt;
    if (item.model) modelSelect.value = item.model;

    // Toggle expand/collapse
    const toggleBtn = menuItem.querySelector(".menu-item-header");
    toggleBtn.addEventListener("click", () => {
      menuItem.classList.toggle("expanded");
      toggleBtn.querySelector(".toggle-btn").textContent =
        menuItem.classList.contains("expanded") ? "▲" : "▼";
    });

    // Delete button
    const deleteBtn = menuItem.querySelector(".delete-menu-item");
    deleteBtn.addEventListener("click", () => {
      if (confirm("Are you sure you want to delete this menu item?")) {
        menuItem.remove();
      }
    });

    // Update title when changed
    titleInput.addEventListener("input", () => {
      titleElement.textContent = titleInput.value || "Menu Item";
    });

    return menuItem;
  }

  // Add new menu item
  function addMenuItem() {
    const newItem = createMenuItemElement();
    menuItemsContainer.appendChild(newItem);

    // Expand the new item and scroll to it
    newItem.classList.add("expanded");
    newItem.querySelector(".toggle-btn").textContent = "▲";
    newItem.scrollIntoView({ behavior: "smooth" });
  }

  // Event listeners
  addMenuItemBtn.addEventListener("click", addMenuItem);
  saveSettingsBtn.addEventListener("click", saveSettings);
  resetSettingsBtn.addEventListener("click", resetSettings);

  // Initialize
  loadSettings();
});
