const syncBtn = document.getElementById("sync");
const statusEl = document.getElementById("status");

function setStatus(text, isError = false) {
  statusEl.textContent = text;
  statusEl.style.color = isError ? "#b45309" : "#166534";
}

syncBtn.addEventListener("click", async () => {
  syncBtn.disabled = true;
  setStatus("同步中…");

  try {
    const { serverUrl } = await chrome.storage.sync.get(["serverUrl"]);
    const response = await chrome.runtime.sendMessage({
      action: "sync",
      serverUrl,
      apiVersion: "go-v1",
    });

    if (!response) {
      throw new Error(
        chrome.runtime.lastError?.message ??
          "擴充背景程序無回應。請到 chrome://extensions 重新載入擴充"
      );
    }

    if (response.success !== false && response.valid !== false) {
      setStatus(
        response.username
          ? `成功：@${response.username}\n${response.message ?? ""}`
          : response.message ?? "同步成功"
      );
    } else {
      setStatus(response.message ?? "同步失敗", true);
    }
  } catch (error) {
    setStatus(error instanceof Error ? error.message : "同步失敗", true);
  } finally {
    syncBtn.disabled = false;
  }
});