{#
  This template receives the following pieces of context in addition to the form:
#}
{% set title = title|default(_fsdomain("Sign In With A Passkey")) %}
{% extends "security/base.html" %}
{% from "security/_macros.html" import render_field_with_errors, render_field, render_field_errors, render_form_errors, prop_next, script_nonce %}

{% block head_scripts %}
  {{ super() }}
  <script {{ script_nonce() }} src="{{ url_for('.static', filename='js/webauthn.js') }}"></script>
  <script {{ script_nonce() }} src="{{ url_for('.static', filename='js/base64.js') }}"></script>
{% endblock head_scripts %}

{% block content %}
  {% include "security/_messages.html" %}
  {% if not is_secondary %}
    <h1>{{ _fsdomain("Sign In With a Passkey") }}</h1>
  {% else %}
    <h1>{{ _fsdomain("Use a Passkey as a Second Factor") }}</h1>
  {% endif %}
  {% if not credential_options %}
    <form action="{{ url_for_security('wan_signin') }}{{ prop_next() }}" method="post" name="wan_signin_form" id="wan-signin-form">
      {{ wan_signin_form.hidden_tag() }}
      {{ render_form_errors(wan_signin_form) }}
      {% if not is_secondary %}
        {{ render_field_with_errors(wan_signin_form.identity) }}
        {{ render_field_with_errors(wan_signin_form.remember) }}
      {% endif %}
      {{ render_field_errors(wan_signin_form.credential) }}
      {{ render_field_errors(wan_signin_form.csrf_token) }}
      {{ render_field(wan_signin_form.submit) }}
    </form>
  {% else %}
    <form action="{{ url_for_security('wan_signin_response', token=wan_state) }}{{ prop_next() }}" method="post" name="wan_signin_response_form" id="wan-signin-response-form">
      {{ wan_signin_response_form.hidden_tag() }}
      {{ render_field_errors(wan_signin_form.remember) }}
      {#  the following is important even though it is hidden - some browsers
          require an input focus field (such as Safari)
      #}
      {{ render_field(wan_signin_response_form.credential) }}
      <div id="wan-errors"></div>
    </form>
    <script {{ script_nonce() }} type="text/javascript">
      handleSignin('{{ credential_options|safe }}')
        .then((result) => {
          if (result.error_msg) {
            const error_element = document.getElementById("wan-errors");
            error_element.innerHTML = `<em>${result.error_msg}</em>`;
          } else {
            document.getElementById("credential").value = result.credential;
            {# We auto-submit this form - there is a Submit button on the
                form we could use - but there really isn't any reason to force the
                user to click yet another button
              #}
            document.forms["wan-signin-response-form"].submit();
          }
        });
    </script>
  {% endif %}
{% endblock content %}
