document.querySelector("#validate").addEventListener("click", async (e) => {
  const url = window.location.href;
  const manifestRes = await fetch(".well-known/webring.json");
  const manifestJson = await manifestRes.json();
  const manifest = manifestJson.manifest;
  const resDiv = document.querySelector(".validator-result");
  if (window.location.href !== manifest.url) {
    if (confirm("Invalid validation origin. Continue?")) {
      const ringUrls = Object.keys(manifest.rings);
      for (const r of ringUrls) {
        // Validate
        const validateRes = await fetch(
          `${r}/api/member/validate`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json"
            },
            body: JSON.stringify(manifestJson)
          }
        );
        if (validateRes.ok) {
          // Container for each Ring result
          const ringResultDiv = document.createElement("div");
          ringResultDiv.classList.add("ring-result");
          // Header
          const ringHeader = document.createElement("h2");
          ringHeader.classList.add("ring-header");
          ringHeader.innerText = r;
          ringResultDiv.appendChild(ringHeader);
          // Votes
          const voteDiv = document.createElement("div");
          voteDiv.classList.add("votes-container");

          // Get member standing
          const standingRes = await fetch(
            `${r}/api/member/standing`,
            {
              method: "POST",
              headers: {
                "Content-Type": "application/json"
              },
              body: JSON.stringify({url: manifest.url})
            }
          );
          const standingJson = await standingRes.json();
          const standingBlock = document.createElement("pre");
          standingBlock.innerText = JSON.stringify(standingJson);
          voteDiv.appendChild(standingBlock);
          ringResultDiv.appendChild(voteDiv);
          resDiv.appendChild(ringResultDiv);
        }
      }
    };
  }
});

