{# Show a success message if necessary #}
{# form.success only used if you don't redirect to another page after a successful submission #}
{% macro formSuccessMessage(form, message) %}
    {% if form.success %}
        <p class="Message Message--success js-successContainer">{{ message ?: 'Success!' }}</p>
    {% endif %}
{% endmacro %}

{##
 # Build the field label
 # field: (object) The form field object
 # position: (string) The position of the label. Either 'above' or 'below'
 #}
{% macro buildFieldDescription(field, position) %}
    {% if field.description %}
        {% set settingPosition = _core.theme.settings.formDescriptionPosition %}
        {% if position == 'above' %}
            {# See if the field label should be displayed above the field #}
            {% if settingPosition == 'above' or (settingPosition == 'belowExceptRadioCheckbox' and field.fieldType in ['checkbox', 'multiCheckbox', 'radio']) %}
                <div class="FormDescription FormDescription--withLabelMargin">{{ field.description }}</div>
            {% endif %}
        {% elseif position == 'below' %}
            {# See if the field description should be displayed below the field #}
            {% if settingPosition == 'below' or (settingPosition == 'belowExceptRadioCheckbox' and field.fieldType not in ['checkbox', 'multiCheckbox', 'radio']) %}
                <div class="FormDescription">{{ field.description }}</div>
            {% endif %}
        {% endif %}
    {% endif %}
{% endmacro %}

{# Build the grid form fields #}
{% macro buildGridFormFields(form) %}
    {% for field in form.fields %}
        {% if field.isFormField %}
            {{ _self.buildGridFieldRow(field) }}
        {% else %}
            {# Handle field groups separately as they have child fields to loop through #}
            {% if field.fieldType == "fieldGroup" %}
                {# Output the field group heading #}
                {{ field.tag }}
                {% for child in field.childFields %}
                    {% if child.isFormField %}
                        {{ _self.buildGridFieldRow(child) }}
                    {% else %}
                        {# The child field is not an actual form field or a field group. It could be an HTML, Content or Section Heading field. Just output the tag. #}
                        {{ child.tag }}
                    {% endif %}
                {% endfor %}
            {% else %}
                {# The field is not an actual form field or a field group. It could be an HTML, Content or Section Heading field. Just output the tag. #}
                {{ field.tag }}
            {% endif %}
        {% endif %}
    {% endfor %}
{% endmacro %}

{# Display regular form fields #}
{% macro buildGridFieldRow(field) %}
    {% if field.fieldType != "hidden" %}
        {% set field.class = field.class|replace({"error": "is-invalid"}) %}
        <div class="grid g-2-lg mb-2 nc-1 nc-2-lg">
            <div class="col-1-1 col-1-4-lg text-end-lg">
                {% set field.label.class = field.label.class ~ ' FormLabel' %}
                {% if field.isRequired %}
                    {% set field.required = true %}
                    {% set field.label.text = field.label.text ~ ' <span class="FormRequired">*</span>' %}
                {% endif %}
                {{ field.label.tag }}
            </div>
            {% if field.fieldType in ["checkbox", "radio", "multiCheckbox"] %}
                {% set field.groupId = random_letters() %}
            {% endif %}
            <div class="col-1-1 col-3-4-lg {{ field.groupId ?: '' }}">
                {{ _self.buildGridField(field) }}
            </div>
        </div>
    {% else %}
        {{ field.tag }}
    {% endif %}
{% endmacro %}

{# Build out each field #}
{% macro buildGridField(field) %}
    {# Display the field description above the field if necessary #}
    {% if field.type not in ['grid', 'repeatingGrid'] %}
        {{ _self.buildFieldDescription(field, 'above') }}
    {% endif %}

    {% if field.fieldType in ['email', 'number', 'password', 'text', 'url', 'tel'] %}
        {% set field.class = field.class ~ ' TextInput w-100' %}
        {{ field.tag }}
    {%  elseif field.fieldType in ['date','time','month'] %}
        {% set field.class = field.class ~ ' TextInput' %}
        {{ field.tag }}
    {% elseif field.fieldType == 'button' %}
        {% set field.class = field.class ~ ' Button' %}
        {{ field.tag }}
    {% elseif field.fieldType == 'textarea' %}
        {% if field.size == 'small' %}
            {% set field.rows = 2 %}
        {% elseif field.size == 'medium' %}
            {% set field.rows = 5 %}
        {% elseif field.size == 'large' %}
            {% set field.rows = 10 %}
        {% endif %}
        {% set field.class = field.class ~ ' TextInput w-100' %}
        {{ field.tag }}
    {% elseif field.fieldType == 'select' %}
        <div class="SelectInput w-100">
            {{ field.tag }}
        </div>
    {% elseif field.fieldType == 'radio' %}
        {% if field.config.separator == 'space' %}
            {% for option in field.options %}
                <label class="pr-2">{{ option.tagNoLabel }} {{ option.label }}</label>
            {% endfor %}
        {% else %}
            {{ field.tag|replace({"error": "is-invalid"}) }}
        {% endif %}
    {% elseif field.fieldType == 'repeatingGrid' || field.fieldType == 'grid' %}
        <div class="grid gx-2">
            {% for column in field.columns %}
                {% set class = 'col-1-' ~ loop.length  %}
                {% if column.class %}
                    {% if 'col-' in column.class %}
                        {% set class = column.class %}
                    {% else %}
                        {% set class = class ~ ' ' ~ column.class %}
                    {% endif %}
                {% endif %}
                {% set class = class ~ ' w-100' %}
                <div class="{{ class }}">
                    {% for child in column.childFields %}
                        {% if child.fieldType in ["radio", "multiCheckbox", "checkbox"] %}
                            {% set child.groupId = random_letters() %}
                        {% endif %}
                        <div class="mb-2 {{ child.groupId ?: '' }}">
                            {% set child.label.class = child.label.class ~ ' FormLabel FormLabel--block' %}
                            {% if child.isRequired %}
                                {% set child.required = true %}
                                {% set child.label.text = child.label.text ~ ' <span class="FormRequired">*</span>' %}
                            {% endif %}
                            {{ child.label.tag }}
                            {{ _self.buildGridField(child) }}
                        </div>
                    {% endfor %}
                </div>
            {% endfor %}
        </div>
    {% else %}
        {{ field.tag|replace({"error": "is-invalid"}) }}
    {% endif %}

    {# Display the field description below the field if necessary #}
    {{ _self.buildFieldDescription(field, 'below') }}
{% endmacro %}

{# Build the Label Above Field fields #}
{% macro buildLabelAboveFieldFields(form) %}
    {% for field in form.fields %}
        {% if field.fieldType == 'repeatingGrid' || field.fieldType == 'grid' %}
            <div class="grid gx-2">
                {% for column in field.columns %}
                    {% set class = 'col-1-1 col-sm-1-' ~ loop.length  %}
                    {% if column.class %}
                        {% if 'col-' in column.class %}
                            {% set class = column.class %}
                        {% else %}
                            {% set class = class ~ ' ' ~ column.class %}
                        {% endif %}
                    {% endif %}
                    {# {% set class = class ~ ' w-100' %} #}
                    <div class="{{ class }}">
                        {% for child in column.childFields %}
                            {{ _self.buildLabelAboveFieldField(child) }}
                        {% endfor %}
                    </div>
                {% endfor %}
            </div>
        {% elseif field.isFormField %}
            {{ _self.buildLabelAboveFieldField(field) }}
        {% else %}
            {# Handle field groups separately as they have child fields to loop through #}
            {% if field.fieldType == "fieldGroup" %}
                {% for child in field.childFields %}
                    {% if child.isFormField %}
                        {{ _self.buildLabelAboveFieldField(child) }}
                    {% else %}
                        {# The child field is not an actual form field or a field group. It could be an HTML, Content or Section Heading field. Just output the tag. #}
                        {{ child.tag }}
                    {% endif %}
                {% endfor %}
            {% else %}
                {# The field is not an actual form field or a field group. It could be an HTML, Content or Section Heading field. Just output the tag. #}
                {{ field.tag }}
            {% endif %}
        {% endif %}
    {% endfor %}
{% endmacro %}

{# Display regular form fields #}
{% macro buildLabelAboveFieldField(field) %}
    {% if field.fieldType != "hidden" %}
        {% set field.class = field.class|replace({"error": "is-invalid"}) %}
        {% if field.fieldType in ["checkbox", "radio", "multiCheckbox"] %}
            {% set field.groupId = random_letters() %}
        {% endif %}
        <div class="mb-2 {{ field.groupId ?: '' }}">
            {% set field.label.class = field.label.class ~ ' FormLabel FormLabel--block' %}
            {% if field.description and field.fieldType in ['checkbox', 'multiCheckbox', 'radio'] %}
                {% set field.label.class = field.label.class ~ ' FormLabel--mb0' %}
            {% endif %}
            {% if field.isRequired %}
                {% set field.required = true %}
                {% set field.label.text = field.label.text ~ ' <span class="FormRequired">*</span>' %}
            {% endif %}
            {% if field.fieldType != 'rating' %}
                {{ field.label.tag }}
            {% endif %}

            {# Display the field description above the field if necessary #}
            {{ _self.buildFieldDescription(field, 'above') }}

            {% if field.fieldType in ['email', 'number', 'password', 'text', 'url', 'tel'] %}
                {% set field.class = field.class ~ ' TextInput w-100' %}
                {{ field.tag }}
            {%  elseif field.fieldType in ['date','time','month'] %}
                {% set field.class = field.class ~ ' TextInput' %}
                {{ field.tag }}
            {% elseif field.fieldType == 'button' %}
                {% set field.class = field.class ~ ' Button' %}
                {{ field.tag }}
            {% elseif field.fieldType == 'textarea' %}
                {% if field.size == 'small' %}
                    {% set field.rows = 2 %}
                {% elseif field.size == 'medium' %}
                    {% set field.rows = 5 %}
                {% elseif field.size == 'large' %}
                    {% set field.rows = 10 %}
                {% endif %}
                {% set field.class = field.class ~ ' TextInput w-100' %}
                {{ field.tag }}
            {% elseif field.fieldType == 'select' %}
                <div class="SelectInput w-100">
                    {{ field.tag }}
                </div>
            {% elseif field.fieldType == 'radio' or field.fieldType == 'multiCheckbox' %}
                {% if field.config.separator == 'space' %}
                    {% for option in field.options %}
                        <label class="pr-2">{{ option.tagNoLabel }} {{ option.label }}</label>
                    {% endfor %}
                {% else %}
                    {{ field.tag|replace({"error": "is-invalid"}) }}
                {% endif %}
            {% elseif field.fieldType == 'rating' %}
                <div class="grid gx-2 nc-2">
                    <div class="col-1-2 col-2-3-md col-3-4-lg w-100">
                        {{ field.label.tag }}
                    </div>
                    <div class="col-1-2 col-1-3-md col-1-4-lg w-100">
                        <div class="flex justify-end-lg align-center-lg h-100 justify-start align-start mt-1 mt-0-lg">
                            {% for option in field.options %}
                                <label class="pr-2">{{ option.tagNoLabel }} {{ option.label }}</label>
                            {% endfor %}
                        </div>
                    </div>
                </div>
            {% else %}
                {{ field.tag|replace({"error": "is-invalid"}) }}
            {% endif %}
            {# Display the field description below the field if necessary #}
            {{ _self.buildFieldDescription(field, 'below') }}
        </div>
    {% else %}
        {{ field.tag }}
    {% endif %}
{% endmacro %}

{#
    Sets the error container
    form: (object) The Twig form variable
    message: (string) OPTIONAL A custom message to show above the error list.
#}
{% macro formErrorContainer(form, message) %}
    <div class="Message Message--failure mb-5 {% if form.errors is empty and form.paymentErrors is empty %} hidden{% endif %}">
        {% set errorMessage = form.paymentErrors is empty ? 'There was a problem with your submission. Please correct the issues below' : 'Could not process your payment' %}
        {% set errorMessage = message ? message : errorMessage %}
        <p>{{ errorMessage }}</p>
        <ul class="mb-0">
            {% for error in form.errors %}
                {% if error.message %}
                    <li>{{ error.message }}</li>
                {% elseif error.fieldName == 'ap-form-captcha' %}
                    {% if form.captcha.error %}
                        <li>Google reCAPTCHA error: {{ form.captcha.error }}</li>
                    {% elseif form.captcha.errorCode %}
                        <li>Google reCAPTCHA error: {{ form.captcha.errorCode }}</li>
                    {% endif %}
                {% endif %}
            {% endfor %}
            {% for error in form.paymentErrors %}
                <li>{{ error.message }}</li>
            {% endfor %}
        </ul>
    </div>
{% endmacro %}

{# Build the reCAPTCHA tag #}
{% macro captcha(form) %}
    {% if form.captcha.type == 'recaptchaV3' %}
        {# Recaptcha V3 #}
        {# Because there can be multiple reCAPTCHAs on the page, make the input class unique #}
        {% do form.captcha.makeInputUnique() %}
        {% if _page.hasJs('recaptchaV3') == false %}
            {# Include the hidden input tag, reCAPTCHA Javascript file and the Javascript promise function #}
            {{ form.captcha.tag }}
            {% do _page.registerJs('recaptchaV3') %}
        {% else %}
            {# Only output the hidden input tag as the reCAPTCHA Javascript file and the Javascript promise function have already been included on the page. #}
            {{ form.captcha.input.tag }}
        {% endif %}
    {% endif %}
{% endmacro %}

{#
    Form validation and submit handler Javascript
    form: (array) The form data
    formOverlayClass: (string) The class to use for the form overlay div
    filesToLoad: (array) Array of additional Javascript files to load
    submitHandler: (string) (optional) Name of a function to call after the form is validated and captcha has run.
            It is used to do additional processing on the form. Example is preparing Stripe payment data for submission

    Examples:
    Basic:
    {{ macros.formValidateHandlerJs(form) }}
    All parameters:
    {{ macros.formValidateHandlerJs(form, formOverlayClass, ['js/stripe.js'|theme_url], 'stripePayment.prepareToken') }}
    Skip filesToLoad
    {{ macros.formValidateHandlerJs(form, formOverlayClass, '', 'prepareStripe') }}
#}
{% macro formValidateHandlerJs(form, formOverlayClass, filesToLoad, submitHandler) %}
    {% import _self as macros %}

    {% set formOverlayClass = formOverlayClass ?: 'js-formOverlay' ~ random_string() %}
    <div class="FormOverlay {{ formOverlayClass }}"><div class="FormOverlay-text">Please wait&hellip;</div></div>

    {# Load for form Javascript if necessary. This holds the form validation library. #}
    {% if _page.hasJs('just-validate/just-validate.production.min.js'|theme_url) == false %}
        {% inlinejs %}
            loadjs.ready('main', {
                success: function() {
                    loadjs('{{ 'just-validate/just-validate.production.min.js'|theme_url }}', 'validate');
                }
            });
        {% endinlinejs %}
        {% do _page.registerJs('just-validate/just-validate.production.min.js'|theme_url) %}
    {% endif %}

    {% inlinejs %}
        {% if filesToLoad is iterable and filesToLoad|length > 0 %}
            loadjs.ready('validate', {
                success: function() {
                    loadjs([{% for file in filesToLoad %}{% if loop.first == false and loop.lsat == false %},{% endif %}'{{ file }}'{% endfor %}], 'formExtraFiles');
                }
            });
            loadjs.ready('formExtraFiles', {
        {% else %}
            loadjs.ready('validate', {
        {% endif %}
            success: function() {
                {# Handle event listener to revalidate fields when they've been previously invalidated. #}
                const inputListener = (e) => {
                    validator.revalidateField(`#${e.target.id}`).then(isValid => {
                        if (isValid) {
                            e.target.removeEventListener('input', inputListener);
                        }
                    });
                }

                {# Create validator instance #}
                const validator = new JustValidate('.{{ form.class }}');

                {# Add validation rules #}
                {% for field in form.fields %}
                    {{ macros.addValidationRule(field) }}
                {% endfor %}

                {# Add event listener to handle reCAPTCHA #}
                validator.onSuccess(e => {
                    {# Show the submission overlay #}
                    document.querySelector('.{{ formOverlayClass }}').style.display = 'block';

                    {# Disable the submit button #}
                    document.querySelector('.{{ form.class }} [type="submit"]').disabled = true;

                    {# Handle submission via either reCAPTCHA v3, a custom handler, or just a regular submission. #}
                    {% if form.captcha.type == 'recaptchaV3' %}
                        {{ form.captcha.script.function }}(grecaptcha, {
                            inputSelector: '.{{ form.captcha.input.class }}'
                        }).then(function() {
                            {% if submitHandler %}
                                {{ submitHandler }}(form);
                            {% else %}
                                document.querySelector('.{{ form.class }}').submit();
                            {% endif %}
                        }).catch(function(e) {
                            console.error(e);
                            document.querySelector('.{{ formOverlayClass }}').style.display = 'none';
                            document.querySelector('.{{ form.class }} [type="submit"]').disabled = false;
                        });
                    {% else %}
                        {% if submitHandler %}
                            {{ submitHandler }}(form);
                        {% else %}
                            document.querySelector('.{{ form.class }}').submit();
                        {% endif %}
                    {% endif %}
                });
            }
        });
    {% endinlinejs %}
{% endmacro %}

{% macro addValidationRule(field) %}
    {# Handle rules for field #}
    {% if field.rules|length > 0 and field.fieldType not in ["radio", "multiCheckbox", "checkbox"] %}
        {# Add rules for field to validator #}
        validator.addField('#{{ field.id }}', [
            {% for rule in field.rules %}
                {
                    rule: '{{ rule.type|camel }}',
                    errorMessage: '{{ rule.message }}',
                    {% if rule.type == 'min_length' %}
                        value: {{ rule.rule }}
                    {% endif %}
                },
            {% endfor %}
        ]);

        {# Validate field on blur #}
        document.querySelector('#{{ field.id }}').addEventListener('blur', () => {
            validator.revalidateField('#{{ field.id }}').then(isValid => {
                if (!isValid) {
                    document.querySelector('#{{ field.id }}').addEventListener('input', inputListener);
                }
            });
        });
    {% elseif field.isRequired and field.fieldType in ["radio", "multiCheckbox", "checkbox"] %}
        {# Get required text #}
        {% set reqText = "This field is required." %}
        {% for rule in field.rules %}
            {% if rule.type == "required" %}
                {% set reqText = rule.message %}
            {% endif %}
        {% endfor %}

        {# Add rules for field to validator #}
        validator.addRequiredGroup('.{{ field.groupId }}', '{{ reqText }}');
    {% endif %}

    {# Handle child fields #}
    {% if field.columns|length > 0 %}
        {% import _self as macros %}
        {% for column in field.columns %}
            {% if column.childFields|length > 0 %}
                {% for field in column.childFields %}
                    {{ macros.addValidationRule(field)}}
                {% endfor %}
            {% endif %}
        {% endfor %}
    {% elseif field.childFields|length > 0 %}
        {% import _self as macros %}
        {% for field in field.childFields %}
            {{ macros.addValidationRule(field)}}
        {% endfor %}
    {% endif %}
{% endmacro %}

{# Form fields required message #}
{% macro requiredMessage() %}
    {% if _core.theme.settings.formRequiredShowMessage == 'yes' %}
        <div class="FormRequired-message">{{ _core.theme.settings.formRequiredMessageText }}</div>
    {% endif %}
{% endmacro %}


{# Form button #}
{% macro formButton(buttonText, additionalClass) %}
    {% set buttonClass = 'Button' %}
    {% if _core.theme.settings.formButtonSize in ['sm', 'lg'] %}
        {% set buttonClass = buttonClass ~ ' Button--'  ~ _core.theme.settings.formButtonSize %}
    {% endif %}
    {% if _core.theme.settings.formButtonStyle in ['alt', 'alt2'] %}
        {% set buttonClass = buttonClass ~ ' Button--' ~ _core.theme.settings.formButtonStyle %}
    {% endif %}
    {% if _core.theme.settings.formButtonFullWidthSmallScreens == 'yes' %}
        {% set buttonClass = buttonClass ~ ' Button--smFull' %}
    {% endif %}
    <div class="FormButton"><button type="submit" class="{{ buttonClass }}{% if additionalClass %} {{ additionalClass}}{% endif %}">{{ buttonText }}</button></div>
{% endmacro %}
