// Prism Translate — popup logic.
import { LANGS, langName } from "../lib/storage.js";
import { mountBrand } from "../lib/brand.js";

const $ = (id) => document.getElementById(id);
let state = null;
let active = false;

function sendBg(msg) {
  return new Promise((resolve) => chrome.runtime.sendMessage(msg, (r) => resolve(r || { ok: false })));
}

function fillLangs(sel, value) {
  sel.innerHTML = "";
  LANGS.filter((l) => l.code !== "auto").forEach((l) => {
    const o = document.createElement("option");
    o.value = l.code;
    o.textContent = l.name;
    if (l.code === value) o.selected = true;
    sel.appendChild(o);
  });
}

async function init() {
  const r = await sendBg({ cmd: "getState" });
  if (!r.ok) return;
  state = r;
  const s = state.settings;

  document.documentElement.setAttribute("data-theme", s.theme || "dark");
  mountBrand();

  fillLangs($("targetLang"), s.targetLang);

  $("scenario").innerHTML = "";
  state.prompts.forEach((p) => {
    const o = document.createElement("option");
    o.value = p.id;
    o.textContent = p.name + (p.builtin ? "" : " · 自定义");
    if (p.id === s.scenario) o.selected = true;
    $("scenario").appendChild(o);
  });

  $("provider").innerHTML = "";
  const enabled = state.providers.filter((p) => p.enabled);
  if (!enabled.length) {
    const o = document.createElement("option");
    o.textContent = "（未配置）";
    $("provider").appendChild(o);
  }
  state.providers.forEach((p) => {
    const o = document.createElement("option");
    o.value = p.id;
    o.textContent = `${p.name} · ${p.model}` + (p.enabled ? "" : "（停用）");
    if (p.id === (s.defaultProvider || enabled[0]?.id)) o.selected = true;
    o.disabled = !p.enabled;
    $("provider").appendChild(o);
  });

  $("displayStyle").value = s.displayStyle || "underline";

  // warn if no key
  const def = state.providers.find((p) => p.id === ($("provider").value)) || enabled[0];
  if (!enabled.length || !def?.apiKey) {
    const w = $("warn");
    w.hidden = false;
    w.innerHTML = '⚠ 尚未配置可用的翻译服务，请先 <a id="goconf">打开工作台填写 API Key</a>';
    w.querySelector("#goconf").addEventListener("click", openOptions);
  }

  renderUsage();

  // sync toggle label with whether the current tab is already translated
  const tab = await activeTab();
  if (tab?.id) {
    chrome.tabs.sendMessage(tab.id, { cmd: "ping" }, (r) => {
      if (chrome.runtime.lastError) return; // no content script on this page
      if (r && r.active) setToggle(true);
    });
  }
}

function renderUsage() {
  const u = state.usage || {};
  let req = 0, inTok = 0, outTok = 0, cost = 0;
  Object.values(u).forEach((x) => {
    req += x.requests || 0;
    inTok += x.inputTokens || 0;
    outTok += x.outputTokens || 0;
    cost += x.cost || 0;
  });
  const fmt = (n) => n.toLocaleString("en-US");
  $("usage").innerHTML =
    `<span>累计请求 <b>${fmt(req)}</b></span>` +
    `<span>Tokens <b>${fmt(inTok + outTok)}</b></span>` +
    `<span>预估成本 <b>$${cost.toFixed(cost < 1 ? 4 : 2)}</b></span>`;
}

function activeTab() {
  return new Promise((resolve) => chrome.tabs.query({ active: true, currentWindow: true }, (t) => resolve(t[0])));
}

async function setToggle(on) {
  active = on;
  const btn = $("toggle");
  btn.classList.toggle("active", on);
  btn.querySelector(".bt-label").textContent = on ? "还原原文" : "翻译此页面";
  btn.querySelector(".bt-icon").textContent = on ? "↺" : "⇄";
}

$("toggle").addEventListener("click", async () => {
  const tab = await activeTab();
  if (!tab?.id) return;
  const cmd = active ? "restore" : "translate";
  const r = await new Promise((res) => chrome.tabs.sendMessage(tab.id, { cmd }, (x) => {
    if (chrome.runtime.lastError) res({ ok: false });
    else res(x || { ok: false });
  }));
  if (r.ok) setToggle(cmd === "translate");
  else {
    // content script missing (e.g. chrome:// page or freshly installed)
    await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ["content/content.js"] }).catch(() => {});
    chrome.tabs.sendMessage(tab.id, { cmd: "translate" }, () => void chrome.runtime.lastError);
    setToggle(true);
  }
  window.close();
});

async function saveSettingsPatch(patch) {
  state.settings = { ...state.settings, ...patch };
  await sendBg({ cmd: "saveSettings", settings: state.settings });
}

$("targetLang").addEventListener("change", (e) => saveSettingsPatch({ targetLang: e.target.value }));
$("scenario").addEventListener("change", (e) => saveSettingsPatch({ scenario: e.target.value }));
$("provider").addEventListener("change", (e) => saveSettingsPatch({ defaultProvider: e.target.value }));
$("displayStyle").addEventListener("change", (e) => saveSettingsPatch({ displayStyle: e.target.value }));

$("theme").addEventListener("click", async () => {
  const next = (state.settings.theme === "light") ? "dark" : "light";
  document.documentElement.setAttribute("data-theme", next);
  await saveSettingsPatch({ theme: next });
});

function openOptions() {
  chrome.runtime.openOptionsPage();
  window.close();
}
$("workstation").addEventListener("click", openOptions);
$("pdf").addEventListener("click", () => { chrome.tabs.create({ url: chrome.runtime.getURL("pdf/viewer.html") }); window.close(); });
$("image").addEventListener("click", () => { chrome.tabs.create({ url: chrome.runtime.getURL("ocr/image-ocr.html") }); window.close(); });

init();
