{% extends "wei/base.html" %}
{% comment %}
SPDX-License-Identifier: GPL-3.0-or-later
{% endcomment %}
{% load i18n %}
{% load crispy_forms_tags %}

{% block profile_content %}
<div class="card bg-light mb-3">
    <h3 class="card-header text-center">
        {{ title }}
    </h3>
    <div class="card-body">
        <form id="registration-form" method="post">
            {% csrf_token %}
            {{ form|crispy }}
            {{ membership_form|crispy }}
            <button class="btn btn-primary" type="submit">{% trans "Submit" %}</button>
        </form>
    </div>
</div>
{% endblock %}

{% block extrajavascript %}
<!-- intl-tel-input CSS/JS -->
<script>
(() => {
    const input = document.querySelector("input[name='emergency_contact_phone']");
    const form = document.querySelector("#registration-form");

    if (!input || !form || input.type === "hidden" || input.disabled || input.readOnly) {
        return;
    }

    const iti = window.intlTelInput(input, {
        initialCountry: "auto",
        nationalMode: false,
        autoPlaceholder: "off",
        geoIpLookup: callback => {
            fetch("https://ipapi.co/json")
                .then(res => res.json())
                .then(data => callback(data.country_code))
                .catch(() => callback("fr"));
        },
        loadUtils: () => import("https://cdn.jsdelivr.net/npm/intl-tel-input@25.5.2/build/js/utils.js"),
    });

    form.addEventListener("submit", function(e){
        if (!input.value.trim()) {
            return;
        }

        const number = iti.getNumber(intlTelInput.utils.numberFormat.E164);
        if (number) {
            input.value = number;
            form.submit();
        } else {
            e.preventDefault();
            input.focus();
        }
    });
})();
</script>

{% if not object.membership %}
<script>
    $(document).ready(function () {
        function refreshTeams() {
            let buses = [];
            $("input[name='bus']:checked").each(function (ignored) {
                buses.push($(this).parent().text().trim());
            });
            console.log(buses);
            $("input[name='team']").each(function () {
                let label = $(this).parent();
                $(this).parent().addClass('d-none');
                buses.forEach(function (bus) {
                    if (label.text().includes(bus))
                        label.removeClass('d-none');
                });
            });
        }

        $("input[name='bus']").change(refreshTeams);

        refreshTeams();
    });
</script>
{% endif %}
{% endblock %}