"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/debug.ts
  var DEBUG_ENABLED = true;
  var EXTENSION_VERSION = "1.2.0";
  var DEBUG_SERVER_URL = `${BACKEND_URL}/debug/log`;
  var logQueue = [];
  var MAX_QUEUE_SIZE = 100;
  function sanitizeData(data) {
    if (!data) return null;
    try {
      const seen = /* @__PURE__ */ new WeakSet();
      const sanitized = JSON.parse(JSON.stringify(data, (_key, value) => {
        if (typeof value === "function") {
          return "[Function]";
        }
        if (typeof value === "string" && value.length > 1e3) {
          return value.substring(0, 1e3) + "...[truncated]";
        }
        if (typeof value === "object" && value !== null) {
          if (seen.has(value)) {
            return "[Circular]";
          }
          seen.add(value);
        }
        return value;
      }));
      const jsonStr = JSON.stringify(sanitized);
      if (jsonStr.length > 5e4) {
        return { error: "Data too large to log", size: jsonStr.length };
      }
      return sanitized;
    } catch (error) {
      const err = error;
      return { error: "Failed to sanitize data", errorMessage: err.message };
    }
  }
  async function sendLog(level, message, data = {}, source = "unknown") {
    if (!DEBUG_ENABLED) return;
    const logData = {
      level,
      message,
      data: sanitizeData(data),
      source,
      version: EXTENSION_VERSION,
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      url: typeof window !== "undefined" ? window.location?.href ?? "background" : "background",
      userAgent: typeof navigator !== "undefined" ? navigator.userAgent : "unknown"
    };
    try {
      const response = await fetch(DEBUG_SERVER_URL, {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(logData),
        signal: AbortSignal.timeout(2e3)
      });
      if (!response.ok) {
        throw new Error(`Server responded with ${response.status}`);
      }
      if (logQueue.length > 0) {
        await flushLogQueue();
      }
    } catch (_error) {
      logQueue.push(logData);
      if (logQueue.length > MAX_QUEUE_SIZE) {
        logQueue.shift();
      }
      console[level === "error" ? "error" : "log"](`[${level}] [${source}]`, message, data);
    }
  }
  async function flushLogQueue() {
    if (logQueue.length === 0) return;
    const logsToSend = [...logQueue];
    logQueue = [];
    for (const logData of logsToSend) {
      try {
        await fetch(DEBUG_SERVER_URL, {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify(logData),
          signal: AbortSignal.timeout(2e3)
        });
      } catch (_error) {
        logQueue.push(logData);
        if (logQueue.length > MAX_QUEUE_SIZE) {
          logQueue.shift();
        }
        break;
      }
    }
  }
  function logError(message, error, source = "unknown", additionalData = {}) {
    const err = error;
    const errorData = {
      ...additionalData,
      error: {
        name: err?.name,
        message: err?.message,
        stack: err?.stack
      }
    };
    void sendLog("error", message, errorData, source);
  }
  var debug = {
    ENABLED: DEBUG_ENABLED,
    log: (message, data = {}, source = "popup") => {
      void sendLog("info", message, data, source);
    },
    warn: (message, data = {}, source = "popup") => {
      void sendLog("warn", message, data, source);
    },
    error: (message, error, source = "popup", additionalData = {}) => {
      logError(message, error, source, additionalData);
    },
    debug: (message, data = {}, source = "popup") => {
      void sendLog("debug", message, data, source);
    },
    flush: () => flushLogQueue()
  };
  if (typeof window !== "undefined") {
    window.addEventListener("error", (event) => {
      debug.error("Window error", {
        message: event.message,
        filename: event.filename,
        lineno: event.lineno,
        colno: event.colno
      }, "window-error");
    });
    window.addEventListener("unhandledrejection", (event) => {
      debug.error("Unhandled promise rejection", event.reason, "promise-rejection");
    });
    window.debug = debug;
  }

  // src/extension/side-panel.ts
  var noAnalysisSection = document.getElementById("no-analysis");
  var loadingSection = document.getElementById("loading-section");
  var resultsSection = document.getElementById("results-section");
  var errorSection = document.getElementById("error-section");
  var resultsContent = document.getElementById("results-content");
  var errorMessage = document.getElementById("error-message");
  var articleTitle = document.getElementById("article-title");
  var articleWordcount = document.getElementById("article-wordcount");
  var articleUrl = document.getElementById("article-url");
  async function init() {
    debug.log("Side panel initializing", {}, "side-panel");
    const { theme } = await chrome.storage.local.get("theme");
    if (theme === "miss") {
      document.body.classList.add("theme-miss");
    }
    chrome.storage.onChanged.addListener((changes) => {
      if (changes.theme) {
        if (changes.theme.newValue === "miss") {
          document.body.classList.add("theme-miss");
        } else {
          document.body.classList.remove("theme-miss");
        }
      }
      if (changes.currentAnalysis) {
        debug.log("Analysis updated in storage", {}, "side-panel");
        loadCurrentAnalysis();
      }
      if (changes.analysisLoading) {
        if (changes.analysisLoading.newValue) {
          showLoading();
        }
      }
    });
    await loadCurrentAnalysis();
  }
  async function loadCurrentAnalysis() {
    try {
      const { currentAnalysis } = await chrome.storage.local.get("currentAnalysis");
      if (!currentAnalysis) {
        debug.log("No current analysis", {}, "side-panel");
        showNoAnalysis();
        return;
      }
      const analysis = currentAnalysis;
      debug.log("Loaded analysis from storage", {
        hasArticle: !!analysis.article,
        hasResult: !!analysis.result
      }, "side-panel");
      showAnalysis(analysis.article, analysis.result);
    } catch (error) {
      debug.error("Failed to load analysis", error, "side-panel");
      showError("Failed to load analysis");
    }
  }
  function showNoAnalysis() {
    hideAll();
    noAnalysisSection.classList.remove("hidden");
  }
  function showLoading() {
    hideAll();
    loadingSection.classList.remove("hidden");
  }
  function showAnalysis(article, result) {
    hideAll();
    resultsSection.classList.remove("hidden");
    articleTitle.textContent = article.title || "Untitled Article";
    articleWordcount.textContent = `${article.wordCount.toLocaleString()} words`;
    articleUrl.textContent = article.url;
    articleUrl.setAttribute("title", article.url);
    if (result.highlights && result.highlights.length > 0) {
      renderHighlights(result.highlights);
    } else if (result.rawResponse?.severity === "none") {
      resultsContent.innerHTML = `
      <div style="text-align: center; padding: 20px; color: var(--success);">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="width: 32px; height: 32px; margin-bottom: 12px;">
          <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
          <polyline points="22 4 12 14.01 9 11.01"></polyline>
        </svg>
        <p style="font-weight: 600; margin-bottom: 8px;">No Issues Found</p>
        <p style="font-size: 13px; color: var(--text-secondary);">This article appears to be logically sound.</p>
      </div>
    `;
    } else {
      resultsContent.innerHTML = `
      <div style="text-align: center; padding: 20px; color: var(--text-muted);">
        <p>Analysis completed but no highlights generated.</p>
      </div>
    `;
    }
    debug.log("Analysis displayed in side panel", {
      highlightCount: result.highlights?.length || 0
    }, "side-panel");
  }
  function renderHighlights(highlights) {
    let html = "";
    highlights.forEach((highlight, index) => {
      const itemId = `quote-${index}`;
      const severity = highlight.severity || "moderate";
      const _severityColor = {
        critical: "var(--error)",
        significant: "var(--warning)",
        moderate: "var(--accent)",
        minor: "var(--text-muted)"
      }[severity] || "var(--accent)";
      html += `
      <div class="result-item">
        <div class="result-item-content">
          <p class="result-explanation">${escapeHtml(highlight.explanation)}<span class="quote-toggle-icon" data-target="${itemId}">\u25BC</span></p>
          <div class="result-quote-wrapper" id="${itemId}">
            <blockquote class="result-quote">"${escapeHtml(highlight.quote)}"</blockquote>
          </div>
        </div>
      </div>
    `;
    });
    resultsContent.innerHTML = html;
  }
  function showError(message) {
    hideAll();
    errorSection.classList.remove("hidden");
    errorMessage.textContent = message;
  }
  function hideAll() {
    noAnalysisSection.classList.add("hidden");
    loadingSection.classList.add("hidden");
    resultsSection.classList.add("hidden");
    errorSection.classList.add("hidden");
  }
  function escapeHtml(text) {
    const div = document.createElement("div");
    div.textContent = text;
    return div.innerHTML;
  }
  document.addEventListener("click", (e) => {
    const target = e.target;
    const icon = target.closest(".quote-toggle-icon");
    if (icon) {
      const targetId = icon.getAttribute("data-target");
      if (targetId) {
        const wrapper = document.getElementById(targetId);
        if (wrapper) {
          wrapper.classList.toggle("expanded");
          icon.classList.toggle("expanded");
        }
      }
    }
  });
  init().catch((error) => {
    debug.error("Side panel initialization failed", error, "side-panel");
  });
})();
