(function() {
  'use strict'

  async function submit(assertion) {
    // as this is the last call we have to do a top-level request instead of AJAX
    const form = document.createElement("form");
    form.method = "POST";
    form.style.display = "none";
    addInput(form, "path", "/nevisfido/fido2/assertion/result")
    addInput(form, "id", assertion.id);
    addInput(form, "type", assertion.type);
    console.log("assertion response:", assertion.response);
    addInput(form, "response.clientDataJSON", assertion.response.clientDataJSON);
    addInput(form, "response.authenticatorData", assertion.response.authenticatorData);
    addInput(form, "response.signature", assertion.response.signature);
    addInput(form, "response.userHandle", assertion.response.userHandle);
    document.body.appendChild(form);
    form.submit();
  }

  function authenticate() {
    const hiddenField = document.querySelector("input[name='fido2_attestation_options']");
    if (hiddenField && hiddenField.value) {
        try {
            const options = JSON.parse(hiddenField.value);
            console.log("parsed attestation options:", JSON.stringify(options));

            SimpleWebAuthnBrowser.startAuthentication({ optionsJSON: options, useBrowserAutofill: true })
                .then(assertionResponse => {
                    console.log("Authentication successful:", JSON.stringify(assertionResponse));
                    submit(assertionResponse);
                })
                .catch(error => {
                    console.log(`Passkey autofill skipped: ${error}`);
                });
        } catch (error) {
            console.error("Error parsing fido2_attestation_options:", error);
        }
    } else {
        console.log("Passkey autofill is disabled.");
    }
  }
  authenticate();
})();
