const endpointInput = document.getElementById("endpoint");
const tokenInput = document.getElementById("token");
const connectButton = document.getElementById("connect");
const statusBox = document.getElementById("status");

function setStatus(value) {
  statusBox.textContent = typeof value === "string"
    ? value
    : JSON.stringify(value, null, 2);
}

function refreshStatus() {
  chrome.runtime.sendMessage({ action: "dipclaw:relayStatus" }, (response) => {
    if (chrome.runtime.lastError) {
      setStatus(chrome.runtime.lastError.message);
      return;
    }
    setStatus(response && response.status ? response.status : response);
  });
}

connectButton.addEventListener("click", () => {
  const extensionWebSocketUrl = endpointInput.value.trim();
  const token = tokenInput.value.trim();
  connectButton.disabled = true;
  setStatus("Connecting...");
  chrome.runtime.sendMessage({
    action: "dipclaw:relayConnect",
    relay: {
      extensionWebSocketUrl,
      ...(token ? { token } : {})
    }
  }, (response) => {
    connectButton.disabled = false;
    if (chrome.runtime.lastError) {
      setStatus(chrome.runtime.lastError.message);
      return;
    }
    setStatus(response && response.ok ? response.status : response);
  });
});

refreshStatus();
