"use strict";
(() => {
  // src/popup.ts
  var DEFAULT_OPACITY = 0.2;
  var STORAGE_KEY_FILES = "statshelpr.files";
  var FILE_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
  var MAX_FILE_BYTES = 5 * 1024 * 1024;
  var MAX_TOTAL_BYTES = 8 * 1024 * 1024;
  var apiUrlInput = document.getElementById("apiUrl");
  var licenseKeyInput = document.getElementById("licenseKey");
  var opacityInput = document.getElementById("buttonOpacity");
  var opacityValueEl = document.getElementById("opacityValue");
  var saveBtn = document.getElementById("save");
  var statusEl = document.getElementById("status");
  var statusDot = document.getElementById("status-dot");
  var metaEl = document.getElementById("meta");
  var dropzone = document.getElementById("dropzone");
  var fileInput = document.getElementById("file-input");
  var filesList = document.getElementById("files-list");
  var filesEmpty = document.getElementById("files-empty");
  var dataFiles = [];
  chrome.storage.sync.get(["apiUrl", "licenseKey", "buttonOpacity"], (cfg) => {
    apiUrlInput.value = cfg.apiUrl ?? "https://api.statshelpr.com";
    licenseKeyInput.value = cfg.licenseKey ?? "";
    const opacity = typeof cfg.buttonOpacity === "number" ? cfg.buttonOpacity : DEFAULT_OPACITY;
    if (opacityInput) opacityInput.value = String(opacity);
    if (opacityValueEl) opacityValueEl.textContent = opacity.toFixed(2);
    void pingHealth(apiUrlInput.value);
  });
  opacityInput?.addEventListener("input", () => {
    if (!opacityValueEl) return;
    const v = Number(opacityInput.value);
    opacityValueEl.textContent = Number.isFinite(v) ? v.toFixed(2) : String(opacityInput.value);
  });
  saveBtn.addEventListener("click", () => {
    const apiUrl = apiUrlInput.value.trim().replace(/\/$/, "");
    const licenseKey = licenseKeyInput.value.trim();
    const rawOpacity = opacityInput ? Number(opacityInput.value) : DEFAULT_OPACITY;
    const buttonOpacity = Number.isFinite(rawOpacity) ? Math.min(1, Math.max(0.05, rawOpacity)) : DEFAULT_OPACITY;
    chrome.storage.sync.set({ apiUrl, licenseKey, buttonOpacity }, () => {
      statusEl.textContent = "saved";
      statusEl.className = "status ok";
      setTimeout(() => {
        statusEl.textContent = "";
        statusEl.className = "status";
      }, 2e3);
      void pingHealth(apiUrl);
    });
  });
  async function pingHealth(apiUrl) {
    setDot("checking\u2026", "");
    metaEl.style.display = "none";
    if (!apiUrl) return setDot("not set", "err");
    try {
      const ctrl = new AbortController();
      const timer = setTimeout(() => ctrl.abort(), 4e3);
      const res = await fetch(`${apiUrl.replace(/\/$/, "")}/api/health`, {
        signal: ctrl.signal
      });
      clearTimeout(timer);
      if (!res.ok) return setDot(`API ${res.status}`, "err");
      const data = await res.json();
      const kimiReady = data.kimiConfigured ?? data.moonshotConfigured ?? false;
      if (!kimiReady) {
        setDot("api key missing", "warn");
      } else {
        setDot("ready", "ok");
      }
      renderMeta(data);
    } catch {
      setDot("offline", "err");
    }
  }
  function setDot(label, kind) {
    statusDot.textContent = label;
    statusDot.className = `dot${kind ? ` ${kind}` : ""}`;
  }
  function renderMeta(data) {
    while (metaEl.firstChild) metaEl.removeChild(metaEl.firstChild);
    const kimiReady = data.kimiConfigured ?? data.moonshotConfigured ?? false;
    const rows = [
      ["version", data.version ?? "\u2014", ""],
      ["kimi", kimiReady ? "ready" : "not set", kimiReady ? "ok" : "warn"],
      ["r sandbox", data.sandboxConfigured ? "ready" : "not set", data.sandboxConfigured ? "ok" : ""],
      ["license", data.lemonsqueezyConfigured ? "gated" : "open", data.lemonsqueezyConfigured ? "ok" : ""]
    ];
    for (const [k, v, kind] of rows) {
      const row = document.createElement("div");
      const b = document.createElement("b");
      b.textContent = k;
      row.appendChild(b);
      const val = document.createElement("span");
      val.className = `v${kind ? ` ${kind}` : ""}`;
      val.textContent = v;
      row.appendChild(val);
      metaEl.appendChild(row);
    }
    metaEl.style.display = "";
  }
  document.getElementById("open-tutorial")?.addEventListener("click", (e) => {
    e.preventDefault();
    void chrome.runtime.sendMessage({ type: "openWelcome" });
    window.close();
  });
  void loadFiles().then(() => renderFilesList());
  dropzone.addEventListener("click", () => fileInput.click());
  fileInput.addEventListener("change", async () => {
    if (fileInput.files) await ingestFiles([...fileInput.files]);
    fileInput.value = "";
  });
  dropzone.addEventListener("dragover", (e) => {
    e.preventDefault();
    dropzone.classList.add("drag-over");
  });
  dropzone.addEventListener("dragleave", () => dropzone.classList.remove("drag-over"));
  dropzone.addEventListener("drop", async (e) => {
    e.preventDefault();
    dropzone.classList.remove("drag-over");
    if (e.dataTransfer?.files) await ingestFiles([...e.dataTransfer.files]);
  });
  async function ingestFiles(files) {
    let warnedSize = false;
    for (const f of files) {
      if (f.size > MAX_FILE_BYTES) {
        if (!warnedSize) {
          flashStatus(`${f.name} is too large (>5MB)`, "err");
          warnedSize = true;
        }
        continue;
      }
      const text = await f.text();
      dataFiles = dataFiles.filter((d) => d.filename !== f.name);
      dataFiles.push({
        filename: f.name,
        content: text,
        size: text.length,
        addedAt: Date.now()
      });
    }
    let total = dataFiles.reduce((sum, d) => sum + d.size, 0);
    while (total > MAX_TOTAL_BYTES && dataFiles.length > 0) {
      const oldest = dataFiles.reduce((a, b) => a.addedAt < b.addedAt ? a : b);
      dataFiles = dataFiles.filter((d) => d !== oldest);
      total -= oldest.size;
    }
    await saveFiles();
    renderFilesList();
  }
  function renderFilesList() {
    while (filesList.firstChild) filesList.removeChild(filesList.firstChild);
    if (dataFiles.length === 0) {
      filesEmpty.style.display = "";
      return;
    }
    filesEmpty.style.display = "none";
    for (const f of dataFiles) {
      const row = document.createElement("div");
      row.className = "row";
      const name = document.createElement("span");
      name.className = "name";
      name.textContent = f.filename;
      name.title = f.filename;
      const size = document.createElement("span");
      size.className = "size";
      size.textContent = `${(f.size / 1024).toFixed(1)} kb`;
      const rm = document.createElement("button");
      rm.className = "remove";
      rm.textContent = "\xD7";
      rm.title = "remove";
      rm.addEventListener("click", async () => {
        dataFiles = dataFiles.filter((d) => d.filename !== f.filename);
        await saveFiles();
        renderFilesList();
      });
      row.appendChild(name);
      row.appendChild(size);
      row.appendChild(rm);
      filesList.appendChild(row);
    }
  }
  async function loadFiles() {
    const r = await chrome.storage.local.get(STORAGE_KEY_FILES);
    const stored = r[STORAGE_KEY_FILES] ?? [];
    const now = Date.now();
    dataFiles = stored.filter((f) => now - f.addedAt < FILE_TTL_MS);
    if (dataFiles.length !== stored.length) await saveFiles();
  }
  async function saveFiles() {
    await chrome.storage.local.set({ [STORAGE_KEY_FILES]: dataFiles });
  }
  function flashStatus(msg, kind) {
    statusEl.textContent = msg;
    statusEl.className = `status ${kind}`;
    setTimeout(() => {
      statusEl.textContent = "";
      statusEl.className = "status";
    }, 2400);
  }
})();
