{#
Copyright 2021, 2022 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
#}

{% macro input(label, name, type="text", form_state=false, autocomplete=false, class="", inputmode="text", autocorrect=false, autocapitalize=false, disabled=false, required=false) %}
  {% if not form_state %}
    {% set form_state = {"errors": [], "fields": {}} %}
  {% endif %}

  {% set state = form_state.fields[name] | default({"errors": [], "value": ""}) %}

  <div class="flex flex-col cpd-field {{ class }}">
    <div class="cpd-label"{% if state.errors is not empty %} data-invalid{% endif %}>{{ label }}</div>
    <input name="{{ name }}"
      class="cpd-control"
      {% if state.errors is not empty %} data-invalid {% endif %}
      {% if state.value %} value="{{ state.value }}" {% endif %}
      type="{{ type }}"
      inputmode="{{ inputmode }}"
      {% if required %} required {% endif %}
      {% if disabled %} disabled {% endif %}
      {% if autocomplete %} autocomplete="{{ autocomplete }}" {% endif %} 
      {% if autocorrect %} autocorrect="{{ autocorrect }}" {% endif %}
      {% if autocapitalize %} autocapitalize="{{ autocapitalize }}" {% endif %} 
      />

    {% if state.errors is not empty %}
      {% for error in state.errors %}
        {% if error.kind != "unspecified" %}
          <div class="text-sm text-critical">
            {% if error.kind == "required" %}
              {{ _("mas.errors.field_required") }}
            {% elif error.kind == "exists" and name == "username" %}
              {{ _("mas.errors.username_taken") }}
            {% elif error.kind == "policy" %}
              {{ _("mas.errors.denied_policy", message=error.message) }}
            {% else %}
              {{ error.kind }}
            {% endif %}
          </div>
        {% endif %}
      {% endfor %}
    {% endif %}
  </div>
{% endmacro %}
