"use strict";
(() => {
  // src/shared/colors.ts
  var baseColors = {
    // Status colors (same in both themes)
    error: "#ef4444",
    errorSubtle: "rgba(239, 68, 68, 0.12)",
    success: "#10b981",
    successSubtle: "rgba(16, 185, 129, 0.12)",
    warning: "#f59e0b",
    warningSubtle: "rgba(245, 158, 11, 0.12)",
    // Severity colors (same in both themes)
    severityCritical: "#ef4444",
    severitySignificant: "#eab308",
    severityMinor: "#737373"
  };
  var colors = {
    ...baseColors,
    // Backgrounds
    bgPrimary: "#0f1117",
    bgSecondary: "#1a1d27",
    bgTertiary: "#242936",
    bgHover: "#2d3344",
    // Text
    textPrimary: "#f0f2f5",
    textSecondary: "#9ca3b0",
    textMuted: "#6b7280",
    // Accent (blue)
    accent: "#60a5fa",
    accentHover: "#93c5fd",
    accentSubtle: "rgba(96, 165, 250, 0.12)",
    // Borders
    border: "rgba(255, 255, 255, 0.08)",
    borderStrong: "rgba(255, 255, 255, 0.12)",
    // Highlight colors (for reasoning gaps)
    highlightCritical: "rgba(239, 68, 68, 0.25)",
    highlightCriticalHover: "rgba(239, 68, 68, 0.4)",
    highlightSignificant: "rgba(234, 179, 8, 0.25)",
    highlightSignificantHover: "rgba(234, 179, 8, 0.4)",
    highlightMinor: "rgba(115, 115, 115, 0.25)",
    highlightMinorHover: "rgba(115, 115, 115, 0.4)",
    highlightDefault: "rgba(96, 165, 250, 0.25)",
    highlightDefaultHover: "rgba(96, 165, 250, 0.4)",
    severityDefault: "#60a5fa"
  };
  var missColors = {
    ...baseColors,
    // Backgrounds (purple-tinted dark)
    bgPrimary: "#1a1520",
    bgSecondary: "#231d2b",
    bgTertiary: "#2d2638",
    bgHover: "#3a3245",
    // Text (lavender-tinted)
    textPrimary: "#f5f0fa",
    textSecondary: "#c4b8d4",
    textMuted: "#8b7fa3",
    // Accent (purple)
    accent: "#c084fc",
    accentHover: "#d8b4fe",
    accentSubtle: "rgba(192, 132, 252, 0.12)",
    // Borders (purple-tinted)
    border: "rgba(192, 132, 252, 0.15)",
    borderStrong: "rgba(192, 132, 252, 0.25)",
    // Highlight colors (purple-shifted for theme consistency)
    highlightCritical: "rgba(239, 68, 68, 0.25)",
    highlightCriticalHover: "rgba(239, 68, 68, 0.4)",
    highlightSignificant: "rgba(234, 179, 8, 0.25)",
    highlightSignificantHover: "rgba(234, 179, 8, 0.4)",
    highlightMinor: "rgba(139, 127, 163, 0.25)",
    highlightMinorHover: "rgba(139, 127, 163, 0.4)",
    highlightDefault: "rgba(192, 132, 252, 0.25)",
    highlightDefaultHover: "rgba(192, 132, 252, 0.4)",
    severityDefault: "#c084fc"
  };
  function generateCssVariables(theme) {
    return `
  --bg-primary: ${theme.bgPrimary};
  --bg-secondary: ${theme.bgSecondary};
  --bg-tertiary: ${theme.bgTertiary};
  --bg-hover: ${theme.bgHover};
  --text-primary: ${theme.textPrimary};
  --text-secondary: ${theme.textSecondary};
  --text-muted: ${theme.textMuted};
  --accent: ${theme.accent};
  --accent-hover: ${theme.accentHover};
  --accent-subtle: ${theme.accentSubtle};
  --error: ${theme.error};
  --error-subtle: ${theme.errorSubtle};
  --success: ${theme.success};
  --success-subtle: ${theme.successSubtle};
  --warning: ${theme.warning};
  --warning-subtle: ${theme.warningSubtle};
  --border: ${theme.border};
  --border-strong: ${theme.borderStrong};
  --severity-critical: ${theme.severityCritical};
  --severity-significant: ${theme.severitySignificant};
  --severity-minor: ${theme.severityMinor};`;
  }
  var cssVariables = `
:root {
${generateCssVariables(colors)}
  --shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
  --radius-sm: 6px;
  --radius: 10px;
  --radius-lg: 14px;
}
`;
  var missCssVariables = `
body.theme-miss {
${generateCssVariables(missColors)}
}
`;
  function missBackgroundCss(imagePath) {
    return `
body.theme-miss {
  background: 
    linear-gradient(
      to bottom,
      rgba(26, 21, 32, 0.85) 0%,
      rgba(26, 21, 32, 0.75) 50%,
      rgba(26, 21, 32, 0.9) 100%
    ),
    url('${imagePath}');
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
}
`;
  }
  var themeCssVariables = cssVariables + missCssVariables + missBackgroundCss("/static/missinfo_bg.jpg");
  var themeCssVariablesExtension = cssVariables + missCssVariables + missBackgroundCss("icons/missinfo_bg.jpg");

  // src/shared/highlight-styles.ts
  var highlightCSS = `
/* ===== CSS Custom Highlight API Styles ===== */
::highlight(logic-checker-critical) {
  background-color: ${colors.highlightCritical};
}

::highlight(logic-checker-significant) {
  background-color: ${colors.highlightSignificant};
}

::highlight(logic-checker-minor) {
  background-color: ${colors.highlightMinor};
}

::highlight(logic-checker-default) {
  background-color: ${colors.highlightDefault};
}

/* ===== Fallback: Span-based Highlight Styles ===== */
.logic-checker-highlight {
  cursor: help;
  position: relative;
  transition: background 0.2s ease;
  border-radius: 2px;
  padding: 1px 2px;
}

.logic-checker-highlight.critical,
.logic-checker-highlight[data-importance="critical"] {
  background: linear-gradient(to bottom, ${colors.highlightCritical} 0%, rgba(239, 68, 68, 0.15) 100%);
}

.logic-checker-highlight.critical:hover,
.logic-checker-highlight[data-importance="critical"]:hover {
  background: ${colors.highlightCriticalHover};
}

.logic-checker-highlight.significant,
.logic-checker-highlight[data-importance="significant"] {
  background: linear-gradient(to bottom, ${colors.highlightSignificant} 0%, rgba(234, 179, 8, 0.15) 100%);
}

.logic-checker-highlight.significant:hover,
.logic-checker-highlight[data-importance="significant"]:hover {
  background: ${colors.highlightSignificantHover};
}

.logic-checker-highlight.minor,
.logic-checker-highlight[data-importance="minor"] {
  background: linear-gradient(to bottom, ${colors.highlightMinor} 0%, rgba(115, 115, 115, 0.15) 100%);
}

.logic-checker-highlight.minor:hover,
.logic-checker-highlight[data-importance="minor"]:hover {
  background: ${colors.highlightMinorHover};
}

.logic-checker-highlight:not(.critical):not(.significant):not(.minor):not([data-importance]) {
  background: linear-gradient(to bottom, ${colors.highlightDefault} 0%, rgba(96, 165, 250, 0.15) 100%);
}

.logic-checker-highlight:not(.critical):not(.significant):not(.minor):not([data-importance]):hover {
  background: ${colors.highlightDefaultHover};
}
`;
  var tooltipCSS = `
.logic-checker-tooltip {
  position: fixed;
  z-index: 2147483647;
  width: max-content;
  max-width: 400px;
  min-width: 280px;
  background: linear-gradient(135deg, #1a1a1a 0%, #0d0d0d 100%);
  border: 1px solid;
  border-radius: 8px;
  padding: 12px 14px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  font-size: 13px;
  line-height: 1.5;
  color: #f5f5f5;
  pointer-events: none;
  opacity: 0;
  transform: translateY(8px);
  transition: opacity 0.2s ease, transform 0.2s ease;
}

.logic-checker-tooltip.critical {
  border-color: ${colors.severityCritical};
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(239, 68, 68, 0.2);
}

.logic-checker-tooltip.significant {
  border-color: ${colors.severitySignificant};
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(234, 179, 8, 0.2);
}

.logic-checker-tooltip.minor {
  border-color: ${colors.severityMinor};
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(115, 115, 115, 0.2);
}

.logic-checker-tooltip:not(.critical):not(.significant):not(.minor) {
  border-color: ${colors.severityDefault};
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(96, 165, 250, 0.2);
}

.logic-checker-tooltip.visible {
  opacity: 1;
  transform: translateY(0);
}

.logic-checker-tooltip-header {
  margin-bottom: 6px;
}

.logic-checker-tooltip-badge {
  display: inline-block;
  color: #000;
  font-size: 10px;
  font-weight: 600;
  padding: 2px 8px;
  border-radius: 10px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.logic-checker-tooltip.critical .logic-checker-tooltip-badge {
  background: ${colors.severityCritical};
  color: white;
}

.logic-checker-tooltip.significant .logic-checker-tooltip-badge {
  background: ${colors.severitySignificant};
}

.logic-checker-tooltip.minor .logic-checker-tooltip-badge {
  background: ${colors.severityMinor};
  color: white;
}

.logic-checker-tooltip:not(.critical):not(.significant):not(.minor) .logic-checker-tooltip-badge {
  background: ${colors.severityDefault};
}

.logic-checker-tooltip-explanation {
  color: #d4d4d4;
}
`;
  var contentStyles = highlightCSS + "\n" + tooltipCSS;
  var demoHighlightCSS = `
.demo-highlight {
  cursor: help;
  position: relative;
  background: linear-gradient(to bottom, ${colors.highlightSignificant} 0%, rgba(234, 179, 8, 0.15) 100%);
  border-radius: 2px;
  padding: 1px 2px;
  transition: background 0.2s ease;
}

.demo-highlight:hover {
  background: ${colors.highlightSignificantHover};
}

.demo-highlight.critical {
  background: linear-gradient(to bottom, ${colors.highlightCritical} 0%, rgba(239, 68, 68, 0.15) 100%);
}

.demo-highlight.critical:hover {
  background: ${colors.highlightCriticalHover};
}

.demo-highlight.minor {
  background: linear-gradient(to bottom, ${colors.highlightMinor} 0%, rgba(115, 115, 115, 0.15) 100%);
}

.demo-highlight.minor:hover {
  background: ${colors.highlightMinorHover};
}

.demo-tooltip {
  position: absolute;
  z-index: 1000;
  width: max-content;
  max-width: 400px;
  min-width: 280px;
  background: linear-gradient(135deg, #1a1a1a 0%, #0d0d0d 100%);
  border: 1px solid ${colors.severitySignificant};
  border-radius: 8px;
  padding: 12px 14px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(234, 179, 8, 0.2);
  font-size: 13px;
  line-height: 1.5;
  color: #f5f5f5;
  pointer-events: none;
  opacity: 0;
  transform: translateY(8px);
  transition: opacity 0.2s ease, transform 0.2s ease;
  left: 0;
  top: 100%;
  margin-top: 8px;
}

.demo-highlight:hover .demo-tooltip {
  opacity: 1;
  transform: translateY(0);
}

.demo-tooltip-header {
  margin-bottom: 6px;
}

.demo-tooltip-badge {
  display: inline-block;
  background: ${colors.severitySignificant};
  color: #000;
  font-size: 10px;
  font-weight: 600;
  padding: 2px 8px;
  border-radius: 10px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.demo-tooltip-explanation {
  color: #d4d4d4;
}
`;

  // src/shared/kawaii.ts
  function makeKawaii(text) {
    if (!text) return text;
    let result = text;
    result = result.replace(/\.(\s+|$)/g, (match, space) => {
      if (Math.random() < 0.6) {
        return "~" + space;
      }
      return match;
    });
    const loveWords = ["good", "great", "excellent", "helpful", "useful", "important", "nice", "correct", "right", "valid"];
    loveWords.forEach((word) => {
      const regex = new RegExp(`\\b${word}\\b`, "gi");
      result = result.replace(regex, (match) => {
        if (Math.random() < 0.4) {
          return match + " <3";
        }
        return match;
      });
    });
    if (result.length > 30) {
      result = result.replace(/([.!?])(\s+)/g, (match, punct, space) => {
        if (Math.random() < 0.5) {
          const kawaiis = ["uwu", "owo", ">w<", "nya~"];
          const chosen = kawaiis[Math.floor(Math.random() * kawaiis.length)];
          return punct + " " + chosen + space;
        }
        return match;
      });
    }
    result = result.replace(/([.!?])(\s+)/g, (match, punct, space) => {
      if (Math.random() < 0.25) {
        return punct + " \u2728" + space;
      }
      return match;
    });
    if (Math.random() < 0.3) {
      const emoticons = [" (\u25D5\u203F\u25D5)", " (\xB4\u2200\uFF40)", " (\u0E51\u2022\u0300\u03C9\u2022\u0301\u0E51)", " (\u25E1\u203F\u25E1)", " (\uFF61\u25D5\u203F\u25D5\uFF61)"];
      const chosen = emoticons[Math.floor(Math.random() * emoticons.length)];
      result = result.replace(/([.!?])(\s*)$/, "$1" + chosen + "$2");
    }
    result = result.replace(/it is important to note/gi, (match) => Math.random() < 0.7 ? "just so you know~" : match);
    result = result.replace(/it should be noted/gi, (match) => Math.random() < 0.7 ? "heads up~" : match);
    result = result.replace(/it is worth noting/gi, (match) => Math.random() < 0.7 ? "worth mentioning~" : match);
    result = result.replace(/this suggests/gi, (match) => Math.random() < 0.6 ? "this kinda suggests" : match);
    result = result.replace(/this indicates/gi, (match) => Math.random() < 0.6 ? "this kinda indicates" : match);
    result = result.replace(/\bhowever\b/gi, (match, offset) => offset > 0 && Math.random() < 0.7 ? "but" : match);
    result = result.replace(/\bfurthermore\b/gi, (match) => Math.random() < 0.6 ? "also~" : match);
    result = result.replace(/\btherefore\b/gi, (match) => Math.random() < 0.6 ? "so" : match);
    result = result.replace(/\bmoreover\b/gi, (match) => Math.random() < 0.5 ? "plus~" : match);
    result = result.replace(/\bconsequently\b/gi, (match) => Math.random() < 0.5 ? "so" : match);
    result = result.replace(/\bnevertheless\b/gi, (match) => Math.random() < 0.5 ? "but still~" : match);
    if (Math.random() < 0.2) {
      const kawaiiPhrases = [" uwu", " owo", " nya~", " >w<", " (\xB4\uFF61\u2022 \u1D55 \u2022\uFF61`) \u2661"];
      const chosen = kawaiiPhrases[Math.floor(Math.random() * kawaiiPhrases.length)];
      const words = result.split(" ");
      if (words.length > 3 && chosen) {
        const insertAt = Math.floor(words.length / 2) + Math.floor(Math.random() * 3) - 1;
        if (words[insertAt]) {
          words[insertAt] += chosen;
          result = words.join(" ");
        }
      }
    }
    return result;
  }

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

  // 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/popup.ts
  var settingsBtn = document.getElementById("settings-btn");
  var logoThemeToggle = document.getElementById("logo-theme-toggle");
  var pageStatus = document.getElementById("page-status");
  var actionSection = document.getElementById("action-section");
  var analyzeBtn = document.getElementById("analyze-btn");
  var articleActionsSection = document.getElementById("article-actions-section");
  var articleDetectedIcon = document.getElementById("article-detected-icon");
  var articleWordcountDisplay = document.getElementById("article-wordcount-display");
  var openSidepanelBtn = document.getElementById("open-sidepanel-btn");
  var loadingSection = document.getElementById("loading-section");
  var resultsSection = document.getElementById("results-section");
  var resultsContent = document.getElementById("results-content");
  var errorSection = document.getElementById("error-section");
  var errorMessage = document.getElementById("error-message");
  var articleTextSection = document.getElementById("article-text-section");
  var articleTextContent = document.getElementById("article-text-content");
  var closeArticleTextBtn = document.getElementById("close-article-text");
  var currentArticle = null;
  var currentTabId = null;
  var statusPollInterval = null;
  document.addEventListener("DOMContentLoaded", () => {
    void init();
  });
  async function init() {
    try {
      chrome.storage.local.get(["theme"], (result) => {
        if (result.theme === "miss") {
          document.body.classList.add("theme-miss");
          document.title = "Miss Information";
        } else {
          document.body.classList.remove("theme-miss");
          document.title = "SanityCheck";
        }
      });
      chrome.storage.onChanged.addListener((changes, areaName) => {
        if (areaName === "local" && changes.theme) {
          if (changes.theme.newValue === "miss") {
            document.body.classList.add("theme-miss");
            document.title = "Miss Information";
          } else {
            document.body.classList.remove("theme-miss");
            document.title = "SanityCheck";
          }
        }
      });
      const DEBUG_ENABLED2 = typeof window.debug !== "undefined";
      const debugIndicator = document.getElementById("debug-indicator");
      if (DEBUG_ENABLED2 && debugIndicator) {
        debugIndicator.classList.remove("hidden");
      } else if (debugIndicator) {
        debugIndicator.classList.add("hidden");
      }
      debug.log("Popup initialized", { timestamp: (/* @__PURE__ */ new Date()).toISOString() }, "popup-init");
      await checkCurrentPage();
      settingsBtn.addEventListener("click", openSettings);
      logoThemeToggle.addEventListener("click", toggleTheme);
      analyzeBtn.addEventListener("click", () => {
        void analyzeArticle();
      });
      openSidepanelBtn.addEventListener("click", () => {
        void openSidePanel();
      });
      pageStatus.addEventListener("click", toggleArticleText);
      closeArticleTextBtn.addEventListener("click", hideArticleText);
      debug.log("Initialization complete", {}, "popup-init");
    } catch (error) {
      debug.error("Initialization failed", error, "popup-init");
    }
  }
  window.addEventListener("unload", () => {
    if (statusPollInterval) {
      clearInterval(statusPollInterval);
    }
  });
  function openSettings() {
    void chrome.tabs.create({ url: chrome.runtime.getURL("settings.html") });
  }
  function toggleTheme() {
    const body = document.body;
    const isCurrentlyMiss = body.classList.contains("theme-miss");
    const newTheme = isCurrentlyMiss ? "sanity" : "miss";
    logoThemeToggle.classList.add("pulse");
    setTimeout(() => logoThemeToggle.classList.remove("pulse"), 400);
    if (isCurrentlyMiss) {
      body.classList.remove("theme-miss");
      document.title = "SanityCheck";
    } else {
      body.classList.add("theme-miss");
      document.title = "Miss Information";
    }
    chrome.storage.local.set({ theme: newTheme }, () => {
      debug.log("Theme toggled", { newTheme }, "theme-toggle");
    });
  }
  async function openSidePanel() {
    try {
      if (chrome.sidePanel) {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        if (tab?.windowId) {
          await chrome.sidePanel.open({ windowId: tab.windowId });
          debug.log("Side panel opened", { windowId: tab.windowId }, "popup");
        } else {
          await chrome.sidePanel.open({});
          debug.log("Side panel opened (fallback)", {}, "popup");
        }
      } else {
        debug.warn("Side panel API not available", {}, "popup");
      }
    } catch (error) {
      debug.error("Failed to open side panel", error, "popup");
    }
  }
  async function checkCurrentPage() {
    try {
      debug.log("Checking current page", {}, "popup-check-page");
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      if (!tab || !tab.id) {
        showError("Cannot access this tab");
        return;
      }
      currentTabId = tab.id;
      debug.log("Tab info retrieved", {
        tabId: tab.id,
        url: tab.url,
        title: tab.title
      }, "popup-check-page");
      try {
        await chrome.scripting.executeScript({
          target: { tabId: tab.id },
          files: ["content.js"]
        });
        debug.log("Content script injected", {}, "popup-check-page");
      } catch (injectError) {
        debug.warn("Content script injection failed (may already be injected)", { error: injectError }, "popup-check-page");
      }
      debug.log("Sending extractArticle message", {}, "popup-check-page");
      const response = await sendToContent(tab.id, { action: "extractArticle" });
      debug.log("Received article extraction response", {
        hasResponse: !!response,
        isArticle: response?.isArticle,
        wordCount: response?.wordCount,
        confidence: response?.confidence
      }, "popup-check-page");
      if (response && response.isArticle) {
        currentArticle = response;
        debug.log("Article detected", {
          wordCount: response.wordCount,
          confidence: response.confidence,
          title: response.title
        }, "popup-check-page");
        showArticleDetected(response);
        await checkAnalysisStatus(tab.url ?? "");
      } else if (response) {
        debug.log("Not an article page", {
          wordCount: response.wordCount,
          confidence: response.confidence
        }, "popup-check-page");
        showNotArticle(response);
        if (response.wordCount > 100) {
          currentArticle = response;
          await checkAnalysisStatus(tab.url ?? "");
        }
      } else {
        debug.warn("No response from content script", {}, "popup-check-page");
        showError("Could not analyze this page");
      }
    } catch (error) {
      debug.error("Error checking page", error, "popup-check-page", {
        tabId: currentTabId
      });
      showError("Cannot analyze this page. Try refreshing and reopening the extension.");
    }
  }
  async function checkAnalysisStatus(url) {
    const status = await sendToBackground({ action: "getAnalysisStatus", url });
    debug.log("Analysis status check", { status }, "popup-status");
    if (status.status === "analyzing") {
      showLoading();
      startStatusPolling(url);
      return;
    }
    if (status.status === "complete" && status.parsed) {
      displayResults(status.parsed);
      if (status.parsed.issues && status.parsed.issues.length > 0) {
        await sendHighlightsToPage(status.parsed.issues);
      }
      return;
    }
    if (status.status === "error") {
      showError(status.error ?? "Analysis failed");
      actionSection.classList.remove("hidden");
      return;
    }
    const cached = await chrome.storage.local.get([`analysis_${url}`]);
    const cachedAnalysis = cached[`analysis_${url}`];
    if (cachedAnalysis) {
      displayResults(cachedAnalysis);
      if (cachedAnalysis.issues && cachedAnalysis.issues.length > 0) {
        await sendHighlightsToPage(cachedAnalysis.issues);
      }
    }
  }
  function startStatusPolling(url) {
    statusPollInterval = setInterval(() => {
      void (async () => {
        try {
          const status = await sendToBackground({ action: "getAnalysisStatus", url });
          if (status.status === "complete") {
            if (statusPollInterval) clearInterval(statusPollInterval);
            statusPollInterval = null;
            loadingSection.classList.add("hidden");
            if (status.parsed) {
              displayResults(status.parsed);
              if (status.parsed.issues && status.parsed.issues.length > 0) {
                await sendHighlightsToPage(status.parsed.issues);
              }
            }
          } else if (status.status === "error") {
            if (statusPollInterval) clearInterval(statusPollInterval);
            statusPollInterval = null;
            loadingSection.classList.add("hidden");
            showError(status.error ?? "Analysis failed");
            actionSection.classList.remove("hidden");
          }
        } catch (_e) {
        }
      })();
    }, 500);
  }
  function showLoading() {
    hideError();
    actionSection.classList.add("hidden");
    loadingSection.classList.remove("hidden");
    resultsSection.classList.add("hidden");
    chrome.storage.local.set({ analysisLoading: true }).catch(() => {
    });
  }
  function showArticleDetected(article) {
    pageStatus.classList.add("hidden");
    articleActionsSection.classList.remove("hidden");
    articleWordcountDisplay.textContent = `${article.wordCount.toLocaleString()} words`;
    articleDetectedIcon.onclick = () => {
      toggleArticleText();
    };
    actionSection.classList.remove("hidden");
    debug.log("Article detected UI updated", {
      wordCount: article.wordCount,
      hasText: !!article.text
    }, "popup-ui");
  }
  function showNotArticle(info) {
    const statusIcon = pageStatus.querySelector(".status-icon");
    const statusText = pageStatus.querySelector(".status-text");
    const viewHint = pageStatus.querySelector(".view-text-hint");
    if (statusIcon) {
      statusIcon.innerHTML = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg>`;
    }
    if (statusText) {
      statusText.innerHTML = `
      <strong>Not an article page</strong><br>
      <span style="color: var(--text-muted); font-size: 12px;">This appears to be a different type of page</span>
    `;
    }
    if (info && info.wordCount > 100) {
      currentArticle = info;
      actionSection.classList.remove("hidden");
      analyzeBtn.innerHTML = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"></path><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"></path></svg> Analyze Anyway`;
      if (viewHint) {
        viewHint.classList.remove("hidden");
      }
      pageStatus.classList.add("clickable");
    } else {
      if (viewHint) {
        viewHint.classList.add("hidden");
      }
      pageStatus.classList.remove("clickable");
    }
  }
  function showError(message) {
    errorSection.classList.remove("hidden");
    errorMessage.textContent = message;
  }
  function hideError() {
    errorSection.classList.add("hidden");
  }
  async function analyzeArticle() {
    if (!currentArticle) {
      debug.warn("Analyze called but no article available", {}, "popup-analyze");
      return;
    }
    debug.log("Starting article analysis", {
      wordCount: currentArticle.wordCount,
      title: currentArticle.title,
      url: currentArticle.url
    }, "popup-analyze");
    showLoading();
    if (!currentTabId) {
      showError("No tab available");
      return;
    }
    try {
      const response = await sendToBackground({
        action: "startAnalysis",
        tabId: currentTabId,
        article: currentArticle
      });
      if (!response.success) {
        throw new Error(response.error ?? "Failed to start analysis");
      }
      debug.log("Analysis started in background", {}, "popup-analyze");
      startStatusPolling(currentArticle.url);
    } catch (error) {
      const err = error;
      debug.error("Failed to start analysis", error, "popup-analyze");
      showError(err.message ?? "Failed to start analysis");
      actionSection.classList.remove("hidden");
      loadingSection.classList.add("hidden");
    }
  }
  async function sendHighlightsToPage(issues) {
    if (!currentTabId) {
      debug.warn("Cannot send highlights: no tab ID", {}, "popup-highlights");
      return;
    }
    debug.log("Sending highlights to content script", {
      issueCount: issues.length,
      tabId: currentTabId
    }, "popup-highlights");
    try {
      await sendToContent(currentTabId, {
        action: "highlightIssues",
        issues
      });
      debug.log("Highlights sent successfully", {}, "popup-highlights");
    } catch (error) {
      debug.error("Failed to send highlights", error, "popup-highlights", {
        tabId: currentTabId,
        issueCount: issues.length
      });
    }
  }
  function displayResults(parsed) {
    if (currentArticle) {
      chrome.storage.local.set({
        currentAnalysis: {
          article: currentArticle,
          result: {
            highlights: parsed.issues?.map((issue) => ({
              quote: issue.quote,
              explanation: issue.gap || issue.why_it_doesnt_follow || issue.explanation || "",
              severity: issue.severity || issue.importance,
              category: issue.category || issue.type
            })) || [],
            rawResponse: {
              severity: parsed.severity
            }
          },
          timestamp: Date.now()
        }
      }).catch((error) => {
        debug.error("Failed to store analysis", error, "popup");
      });
    }
    if (articleActionsSection) {
      articleActionsSection.classList.remove("hidden");
    }
    resultsSection.classList.remove("hidden");
    loadingSection.classList.add("hidden");
    actionSection.classList.add("hidden");
    if (parsed.rawText) {
      resultsContent.innerHTML = `
      <div style="color: var(--warning); margin-bottom: 12px;">
        Could not parse structured response
      </div>
      <div style="white-space: pre-wrap; font-size: 12px;">${escapeHtml(parsed.rawText)}</div>
    `;
      return;
    }
    if (!parsed.issues || parsed.issues.length === 0) {
      resultsContent.innerHTML = `
      <div class="no-fallacies">
        <div class="checkmark"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg></div>
        <strong>No significant issues found</strong>
        <p style="color: var(--text-muted); margin-top: 8px;">${escapeHtml(addKawaiiToText(parsed.summary ?? parsed.overall_assessment ?? "The article appears to be logically sound."))}</p>
      </div>
    `;
      return;
    }
    let html = "";
    html += `
    <div class="analysis-summary">
      <div class="summary-header">
        <span class="issue-count">${parsed.issues.length} issue${parsed.issues.length !== 1 ? "s" : ""} found</span>
        <span class="severity-badge ${parsed.severity ?? "none"}">${parsed.severity ?? "unknown"}</span>
      </div>
      ${parsed.summary ?? parsed.overall_assessment ? `<p style="color: var(--text-secondary); font-size: 12px; line-height: 1.6;">${escapeHtml(addKawaiiToText(parsed.summary ?? parsed.overall_assessment ?? ""))}</p>` : ""}
      <p style="color: var(--text-muted); margin-top: 10px; font-size: 11px;">Issues are highlighted in the article. Hover to see details.</p>
    </div>
  `;
    if (parsed.central_argument_analysis?.central_logical_gap) {
      html += `
      <div class="central-gap-box">
        <div class="central-gap-header">
          Central Logical Gap
        </div>
        <div class="central-gap-content">
          ${escapeHtml(addKawaiiToText(parsed.central_argument_analysis.central_logical_gap))}
        </div>
      </div>
    `;
    }
    const sortedIssues = [...parsed.issues].sort((a, b) => {
      const order = { critical: 0, significant: 1, minor: 2 };
      return (order[a.importance ?? "minor"] ?? 2) - (order[b.importance ?? "minor"] ?? 2);
    });
    sortedIssues.forEach((issue, index) => {
      const importanceClass = issue.importance ?? "minor";
      const gap = issue.gap ?? issue.why_it_doesnt_follow ?? issue.explanation ?? "";
      html += `
      <div class="fallacy-item ${importanceClass}" data-issue-index="${index}">
        <div class="fallacy-header">
          <span class="importance-badge ${importanceClass}">${issue.importance ?? "issue"}</span>
        </div>
        ${issue.quote ? `<div class="fallacy-quote">"${escapeHtml(issue.quote.substring(0, 150))}${issue.quote.length > 150 ? "..." : ""}"</div>` : ""}
        ${gap ? `<div class="fallacy-gap-simple">${escapeHtml(addKawaiiToText(gap))}</div>` : ""}
      </div>
    `;
    });
    resultsContent.innerHTML = html;
  }
  function escapeHtml(text) {
    if (!text) return "";
    const div = document.createElement("div");
    div.textContent = text;
    return div.innerHTML;
  }
  function addKawaiiToText(text) {
    if (!text) return text;
    if (!document.body.classList.contains("theme-miss")) {
      return text;
    }
    return makeKawaii(text);
  }
  function toggleArticleText() {
    if (!currentArticle || !currentArticle.text) {
      debug.warn("No article text to display", {}, "popup-article-text");
      return;
    }
    if (articleTextSection.classList.contains("hidden")) {
      showArticleText();
    } else {
      hideArticleText();
    }
  }
  function showArticleText() {
    if (!currentArticle || !currentArticle.text) {
      debug.warn("Cannot show article text: no article available", {}, "popup-article-text");
      return;
    }
    debug.log("Showing article text", {
      textLength: currentArticle.text.length,
      wordCount: currentArticle.wordCount,
      title: currentArticle.title
    }, "popup-article-text");
    const header = articleTextSection.querySelector("h3");
    if (header && currentArticle.title) {
      header.textContent = `Extracted Article: ${currentArticle.title}`;
    }
    articleTextContent.textContent = currentArticle.text;
    articleTextSection.classList.remove("hidden");
    articleTextSection.scrollIntoView({ behavior: "smooth", block: "start" });
  }
  function hideArticleText() {
    debug.log("Hiding article text", {}, "popup-article-text");
    articleTextSection.classList.add("hidden");
  }
})();
