const input = document.getElementById("serverUrl");
const saveBtn = document.getElementById("save");
const savedEl = document.getElementById("saved");

const DEFAULT_URL = "https://threads-tool.30cm.net";

chrome.storage.sync.get(["serverUrl"], ({ serverUrl }) => {
  input.value = serverUrl ?? DEFAULT_URL;
});

function originPatterns(origin) {
  const url = new URL(origin);
  const port = url.port ? `:${url.port}` : "";
  const origins = new Set([`${origin}/*`]);
  if (url.hostname === "localhost") {
    origins.add(`${url.protocol}//127.0.0.1${port}/*`);
  } else if (url.hostname === "127.0.0.1") {
    origins.add(`${url.protocol}//localhost${port}/*`);
  }
  return [...origins];
}

saveBtn.addEventListener("click", async () => {
  const value = input.value.trim();
  if (!value) return;

  let origin;
  try {
    origin = new URL(value).origin;
  } catch {
    savedEl.textContent = "網址格式不正確";
    savedEl.style.color = "#b45309";
    return;
  }

  await chrome.storage.sync.set({ serverUrl: origin });

  const patterns = originPatterns(origin);
  let granted = false;
  try {
    granted = await chrome.permissions.contains({ origins: patterns });
    if (!granted) {
      granted = await chrome.permissions.request({ origins: patterns });
    }
  } catch (e) {
    savedEl.textContent = `授權失敗：${e instanceof Error ? e.message : String(e)}`;
    savedEl.style.color = "#b45309";
    return;
  }

  if (!granted) {
    savedEl.textContent =
      "已儲存網址，但未授權存取該網站。請在彈窗按「允許」，否則巡樓頁無法偵測擴充。";
    savedEl.style.color = "#b45309";
    return;
  }

  try {
    try {
      await chrome.scripting.unregisterContentScripts({ ids: ["haixun-bridge"] });
    } catch {
      // ignore
    }
    await chrome.scripting.registerContentScripts([
      {
        id: "haixun-bridge",
        matches: patterns,
        js: ["content-haixun.js"],
        runAt: "document_start",
      },
    ]);

    const groups = await Promise.all(
      patterns.map((pattern) => chrome.tabs.query({ url: pattern })),
    );
    const seen = new Set();
    let injected = 0;
    for (const tab of groups.flat()) {
      if (!tab.id || seen.has(tab.id)) continue;
      seen.add(tab.id);
      try {
        await chrome.scripting.executeScript({
          target: { tabId: tab.id },
          files: ["content-haixun.js"],
        });
        injected += 1;
      } catch {
        // ignore restricted tabs
      }
    }
    savedEl.textContent = `已儲存：${origin}（已授權，注入 ${injected} 個分頁）。請回巡樓分頁按 F5。`;
    savedEl.style.color = "#166534";
  } catch (e) {
    savedEl.textContent = `注入失敗：${e instanceof Error ? e.message : String(e)}`;
    savedEl.style.color = "#b45309";
  }
});
