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

chrome.storage.sync.get(["serverUrl"], ({ serverUrl }) => {
  input.value = serverUrl ?? "http://localhost:5173";
});

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 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}/*`);
  }

  const granted = await chrome.permissions.request({ origins: [...origins] });
  if (granted) {
    try {
      await chrome.scripting.unregisterContentScripts({ ids: ["haixun-bridge"] });
    } catch {
      // ignore
    }
    await chrome.scripting.registerContentScripts([
      {
        id: "haixun-bridge",
        matches: [...origins].map((item) => item.replace(/\/\*$/, "/*")),
        js: ["content-haixun.js"],
        runAt: "document_start",
      },
    ]);
    const tabQueries = [...origins].map((pattern) => chrome.tabs.query({ url: pattern }));
    await Promise.all(tabQueries).then(async (groups) => {
      const tabs = groups.flat();
      const seen = new Set();
      for (const tab of tabs) {
        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"],
          });
        } catch {
          // ignore
        }
      }
    });
    savedEl.textContent = `已儲存：${origin}（已注入網頁橋接）`;
    savedEl.style.color = "#166534";
  } else {
    savedEl.textContent = "已儲存網址，但未授權存取該網站（同步時會再詢問）";
    savedEl.style.color = "#b45309";
  }
});