// Fetches manifest from member site    
async function fetchManifest(memberUrl) {
  try {
    const res = await fetch(`${memberUrl}/.well-known/webrings.json`, {mode: "cors"});
    if (res.ok) {
      const manifest = await res.json();
      console.log(manifest);
      return {
        result: "success",
        manifest,
        error: null
      };
    }
    return {
      result: "failure",
      manifest: null,
      error: "Could not fetch manifest"
    }
  } catch(e) {
    return {result: "error", error: e, manifest: null};  
  }
}

// Retrieves standing for member
async function fetchStanding(url) {
  try {
    const body = {
      url
    }
    const res = await fetch("/api/member/standing", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(body)
    });
    if (res.ok) {
      const standingResponse = await res.json();
      console.log(standingResponse);
      return {
        result: "success",
        standingResponse,
        error: null
      };
    }
    return {
      result: "failure",
      manifest: null,
      error: "Could not fetch standing"
    }
  } catch(e) {
    return {result: "error", error: e, standingResponse: null};  
  }
}

// Setup up Modals
document.querySelectorAll(".btn-validate").forEach(b => {
  const modal = b.parentElement.parentElement.querySelector("dialog");
  b.addEventListener("click", async () => {
    const memberUrl = modal.parentElement.id;
    modal.showModal();
    let manifestResult = await fetchManifest(memberUrl);
    const validationText = modal.querySelector(".validation-text");
    if (manifestResult.error) {
     validationText.innerText = manifestResult.error; 
     return;
    } else {
     validationText.innerText = "Successfully fetched manifest!";      // Keys match
     const memberKey = modal.querySelector(".validate-member-pubkey").innerText;
     if (memberKey !== manifestResult.manifest.manifest.keyset.keys[0].x) {
       validationText.innerText = "Key mismatch";
       modal.querySelector(".validate-result").innerText = "❗";
       return;
     }
     modal.querySelector(".validate-manifest-pubkey").innerText = manifestResult.manifest.manifest.keyset.keys[0].x;
     // Validate signature
     modal.querySelector(".validate-manifest-signature").innerText = manifestResult.manifest.signature;
     // TODO: Use in-browser validation once JWKS are deployed
     let validateResponse = await fetch("/api/member/validate", {
       method: "POST",
       headers: {
         "Content-Type": "application/json",
       },
       body: JSON.stringify(manifestResult.manifest)
     });
     if (!validateResponse.ok) {
       validationText.innerText = "Error requesting validation";
       return;
     }
     let validateJson = await validateResponse.json();
     console.log(validateJson);
     modal.querySelector(".validate-signature-verification").innerText = validateJson.result;
     if (validateJson.result === "success") {
       modal.querySelector(".validate-result").innerText = "✅";
       validationText.innerText = "Member Validated Successfully";
     } else {
       modal.querySelector(".validate-result").innerText = "❗";
       validationText.innerText = "Signature verification failed";
     }
     // On to Standing
     const standingRes = await fetchStanding(memberUrl); 
     console.log(standingRes);
     const standing = standingRes.standingResponse.standing;
     const voteSplit = standingRes.standingResponse.vote_split;
     const descriptions = standingRes.standingResponse.descriptions;
     // Populate fields
     const standingDiv = modal.querySelector(".standing-details");
     const standingHeader = standingDiv.querySelector("h4");
     const descriptionsList = standingDiv.querySelector(".vote-descriptions");
     standingHeader.querySelector("span").innerText = standing;
     // Populate vote split
     standingDiv.querySelector(".vote-split-good").innerText = `${voteSplit.good}`;
     standingDiv.querySelector(".vote-split-bad").innerText = `${voteSplit.bad}`;
     standingDiv.querySelector(".vote-split-neutral").innerText = `${voteSplit.neutral}`;
     // Populate descriptions
     const descriptionItems = descriptions.map(d => {
       const descriptionItem = document.createElement("li");
       descriptionItem.classList.add("vote-description-item");
       descriptionItem.innerText = d
       return descriptionItem;
     });
     descriptionsList.replaceChildren(...descriptionItems);
    }

  });
  modal.querySelector(".modal-close").addEventListener("click", () => {
    modal.close();
  })
})
