const form = document.querySelector("#workspace-form");
const input = document.querySelector("#workspace-url");
const status = document.querySelector("#status");
const connect = document.querySelector("#connect");
const clear = document.querySelector("#clear");
const build = document.querySelector("#build");

function setStatus(message, isError = false) {
  status.textContent = message;
  status.classList.toggle("error", isError);
}

async function initialize() {
  try {
    const settings = await window.easyPenpot.getWorkspace();
    input.value = settings.workspaceUrl || "";
    build.textContent = `Version ${settings.version}`;
    input.focus();
  } catch {
    setStatus("The client settings are unavailable.", true);
  }
}

form.addEventListener("submit", async (event) => {
  event.preventDefault();
  connect.disabled = true;
  setStatus("");
  try {
    await window.easyPenpot.saveWorkspace(input.value);
  } catch (error) {
    setStatus(error?.message || "The workspace address could not be saved.", true);
    connect.disabled = false;
  }
});

clear.addEventListener("click", async () => {
  clear.disabled = true;
  try {
    await window.easyPenpot.clearWorkspace();
    input.value = "";
    setStatus("Saved address cleared.");
    input.focus();
  } catch {
    setStatus("The saved address could not be cleared.", true);
  } finally {
    clear.disabled = false;
  }
});

initialize();
