"use strict";
(() => {
  // src/extension/config.ts
  if (false) {
    throw new Error("__BACKEND_URL__ must be defined at build time");
  }
  var BACKEND_URL = "https://sanitycheck-production.up.railway.app";

  // src/extension/messaging.ts
  function sendToContent(tabId, message) {
    return chrome.tabs.sendMessage(tabId, message);
  }

  // src/extension/background.ts
  var ongoingAnalyses = /* @__PURE__ */ new Map();
  chrome.runtime.onInstalled.addListener((details) => {
    chrome.contextMenus.create({
      id: "leave-feedback",
      title: "Leave feedback on this text",
      contexts: ["selection"]
    });
    console.log("SanityCheck: Context menu created");
    if (details.reason === "install") {
      chrome.tabs.create({ url: chrome.runtime.getURL("welcome.html") });
    }
  });
  chrome.contextMenus.onClicked.addListener((info, tab) => {
    if (info.menuItemId === "leave-feedback" && info.selectionText && tab?.id) {
      const message = {
        action: "showFeedbackDialog",
        selectedText: info.selectionText,
        url: tab.url ?? "",
        title: tab.title ?? ""
      };
      sendToContent(tab.id, message);
    }
  });
  chrome.runtime.onMessage.addListener((request, _sender, sendResponse) => {
    switch (request.action) {
      case "submitFeedback":
        submitFeedback(request.data).then((result) => sendResponse({ success: true, ...result })).catch((error) => sendResponse({ success: false, error: error.message }));
        return true;
      case "getBackendUrl":
        chrome.storage.local.get(["backendUrl"], (result) => {
          sendResponse({ url: result.backendUrl || BACKEND_URL });
        });
        return true;
      case "startAnalysis":
        startAnalysis(request.tabId, request.article).then(() => sendResponse({ success: true })).catch((error) => sendResponse({ success: false, error: error.message }));
        return true;
      case "getAnalysisStatus": {
        const status = ongoingAnalyses.get(request.url);
        sendResponse(status || { status: "none" });
        return true;
      }
      case "clearAnalysis":
        ongoingAnalyses.delete(request.url);
        sendResponse({ success: true });
        return true;
      default:
        return false;
    }
  });
  async function submitFeedback(data) {
    const response = await fetch(`${BACKEND_URL}/comments`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        url: data.url,
        title: data.title,
        textContent: data.articleText,
        selectedText: data.selectedText,
        commentText: data.commentText
      })
    });
    if (!response.ok) {
      throw new Error(`Failed to submit feedback: ${response.status}`);
    }
    return response.json();
  }
  async function startAnalysis(tabId, article) {
    const url = article.url;
    ongoingAnalyses.set(url, { status: "analyzing" });
    try {
      const response = await fetch(`${BACKEND_URL}/analyze`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          text: article.text
        })
      });
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`API error: ${response.status} - ${errorText}`);
      }
      const result = await response.json();
      const issues = result.issues || [];
      ongoingAnalyses.set(url, { status: "complete", parsed: result });
      try {
        const message = { action: "highlightIssues", issues };
        await sendToContent(tabId, message);
      } catch (_e) {
        console.log("Could not send highlights to tab (tab may have been closed)");
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : "Unknown error";
      ongoingAnalyses.set(url, { status: "error", error: errorMessage });
      console.error("Analysis error:", error);
    }
  }
})();
