"use strict";
(() => {
  // src/background.ts
  chrome.runtime.onInstalled.addListener((details) => {
    if (details.reason === "install") {
      void chrome.tabs.create({
        url: chrome.runtime.getURL("welcome.html")
      });
    }
  });
  chrome.runtime.onMessage.addListener(
    (msg, _sender, sendResponse) => {
      if (msg.type === "openWelcome") {
        void chrome.tabs.create({ url: chrome.runtime.getURL("welcome.html") });
        sendResponse({ ok: true });
        return false;
      }
      if (msg.type === "solve") {
        handleSolve(msg.payload).then((result) => sendResponse({ ok: true, result })).catch((e) => sendResponse({ ok: false, error: e.message }));
        return true;
      }
      return false;
    }
  );
  async function handleSolve(payload) {
    const cfg = await chrome.storage.sync.get(["apiUrl", "licenseKey"]);
    const apiUrl = cfg["apiUrl"] ?? "https://api.statshelpr.com";
    const licenseKey = cfg["licenseKey"] ?? "";
    const res = await fetch(`${apiUrl}/api/solve`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        ...licenseKey ? { Authorization: `Bearer ${licenseKey}` } : {}
      },
      body: JSON.stringify(payload)
    });
    if (!res.ok) {
      const body = await res.text();
      throw new Error(`API ${res.status}: ${body.slice(0, 300)}`);
    }
    return await res.json();
  }
})();
