// ILoveMD Chrome Extension Background Service Worker (Manifest V3)

chrome.runtime.onInstalled.addListener(() => {
  // Create Context Menus for Right-Click Action
  chrome.contextMenus.create({
    id: "ilovemd_convert_page",
    title: "ILoveMD: Convert Page to Markdown",
    contexts: ["page"]
  });

  chrome.contextMenus.create({
    id: "ilovemd_convert_selection",
    title: "ILoveMD: Convert Selection to Markdown",
    contexts: ["selection"]
  });
});

// Handle Context Menu Clicks
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
  if (!tab || !tab.id) return;

  if (info.menuItemId === "ilovemd_convert_selection" && info.selectionText) {
    const selectedMd = `# Selection from ${tab.title || "Webpage"}\n\n${info.selectionText}`;
    await chrome.storage.local.set({ lastConvertedMd: selectedMd, lastTitle: tab.title || "Selection.md" });
    await chrome.action.openPopup();
  } else if (info.menuItemId === "ilovemd_convert_page") {
    try {
      await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        files: ["content.js"]
      });
    } catch (e) {
      console.error("Failed to execute content script", e);
    }
  }
});
