{% extends 'tournaments/base.html' %}

{% block head_title %}{{ tournament.display_name }} : Informations{% endblock %}
{% block first_title %}{{ tournament.event.display_name }}{% endblock %}
{% block second_title %}{{ tournament.display_name }}{% endblock %}
{% block meta_desc %}Enregistrez-vous au {{ tournament.display_name }}. Choisissez votre partenaire et inscrivez-vous ou mettez vous en liste d'attente pour participer au tournoi!{% endblock %}
{% block meta_keywords %}enregistrement{% endblock %}

{% block content %}
{% load static %}
{% load tz %}

<nav class="margin10">
<a href="{% url 'tournament-info' tournament.id %}" class="topmargin5">Informations</a>
</nav>

<div class="grid-x">
    <div class="cell medium-6 large-6 padding10">
        <h1 class="club padding10">Inscription : {{ tournament.display_name }} {{ tournament.get_federal_age_category_display}}</h1 >
        <div class="bubble">
            <div class="semibold">{{ tournament.local_start_date_formatted }}</div>
            <div class="semibold">{{ tournament.event.club.name }}</div>
            {% if tournament.has_club_address %}
            <div>{{ tournament.event.club.address }}</div>
            <div>{{ tournament.event.club.city_zipcode }}</div>
            {% endif %}

            <hr/>
            {% if registration_successful %}
              <p class="topblock">Merci, l'inscription a bien été envoyée au juge-arbitre.</p>
              {% if registration_paid %}
                <p><strong>✅ Votre paiement a bien été effectué et enregistré.</strong></p>
              {% endif %}
              <p style="text-align: justify;">
                  Un email de confirmation a été envoyé à l'adresse associée à votre compte Padel Club ({{ user.email }}). Pensez à vérifier vos spams si vous ne recevez pas l'email. En cas de problème, contactez le juge-arbitre.
              </p>
            {% else %}
                {% if not registration_successful %}
                    <div class="info-box topblock">
                        <p>Votre session d'inscription est active. Complétez le formulaire dans le délai accordé pour confirmer votre participation et garantir votre place.</p>
                        {% if not cart_data.is_cart_expired %}
                                <p class="semibold highlight">Votre session d'inscription expirera le {{ cart_data.expiry|date:"d/m/Y à H:i" }}</p>
                                <p>Temps restant: <span id="countdown" data-expiry="{{ cart_data.expiry|date:'U' }}">{{ cart_data.expiry|timeuntil }}</span></p>
                        {% else %}
                            <p class="alert alert-danger">
                            Votre session d'inscription a expiré. Veuillez recommencer le processus d'inscription. Votre place n'est plus garantie.
                            </p>
                        {% endif %}
                    </div>
                {% endif %}

                {% if team_form.errors %}
                <div>
                    {% for field in team_form %}
                        {% if field.errors %}
                            {% for error in field.errors %}
                            <div class="alert">{{ field.label }} : {{ error }}</div>
                            {% endfor %}
                        {% endif %}
                    {% endfor %}
                </div>
                {% endif %}

                {% if messages %}
                <div class="messages">
                    {% for message in messages %}
                    <div class="alert {% if message.tags %}alert-{{ message.tags }}{% endif %}">
                        {{ message }}
                    </div>
                    {% endfor %}
                </div>
                {% endif %}

                <form method="post">
                    {% csrf_token %}

                    <!-- Team Registration Form -->
                    <div>
                        <p>
                        <div class="semibold">
                            Informations de contact
                        </div>
                        </p>
                        {% if team_form.non_field_errors %}
                            {% for error in team_form.non_field_errors %}
                                <p>{{ error }}</p>
                            {% endfor %}
                        {% endif %}

                        {{ team_form.as_p }}  <!-- Render team registration form fields here -->
                    </div>

                    <!-- Show players added to the team only if there are players added -->
                    {% if current_players %}
                    <p>
                    <div class="semibold">
                        Constitution de votre équipe
                    </div>
                    </p>
                    <ul>
                        {% for player in current_players %}
                            <li>
                                <div>
                                    {{ player.first_name }} {{ player.last_name }}{% if player.licence_id %} ({{ player.licence_id }}){% endif %}
                                </div>
                                <div>
                                    {{ player.club_name }}{% if player.club_member %} | Membre du club{% endif %}{% if player.club_member and tournament.club_member_fee_deduction %} | Tarif réduit{% endif %}
                                </div>
                                <div>
                                    {{ player.email }}
                                </div>
                                <div>
                                    Classement à ce jour : {% if player.rank %}{{ player.rank }}{% if player.computed_rank and player.rank != player.computed_rank %} ({{ player.computed_rank }}){% endif %}{% else %}Non classé ({{ player.computed_rank }}){% endif %}
                                </div>
                                {% if not forloop.first %}
                                <div>
                                    <button type="submit" name="remove_player" class="btn small-button">
                                        modifier
                                    </button>
                                </div>
                                {% endif %}
                            </li>
                        {% endfor %}
                    </ul>
                    {% endif %}

                    <!-- Add Player Form -->
                    {% if current_players|length < 2 %}
                    <div>
                        {% if current_players|length == 1 %}
                        <div class="semibold">
                        Inscrivez votre partenaire
                        </div>
                        {% endif %}
                        {% if current_players|length == 0 and add_player_form.user_without_licence and tournament.license_is_required %}
                        <div class="semibold">
                        Une licence est obligatoire pour vous inscrire :
                        </div>
                        {% endif %}

                        {% if tournament.license_is_required %}
                        {{ add_player_form.licence_id.label_tag }}
                        {{ add_player_form.licence_id }}
                        {% endif %}
                        {% if add_player_form.first_tournament or add_player_form.user_without_licence or tournament.license_is_required is False %}
                            {% if not add_player_form.user_without_licence and tournament.license_is_required is True %}
                            <div class="semibold">
                                Padel Club n'a pas trouvé votre partenaire, il se peut qu'il s'agisse de son premier tournoi. Contacter le juge-arbitre après l'inscription si ce n'est pas le cas.
                            </div>
                            <div class="semibold">
                                Précisez les informations du joueur :
                            </div>
                            {% endif %}

                            {% if not add_player_form.user_without_licence %}
                            {{ add_player_form.first_name.label_tag }}
                            {{ add_player_form.first_name }}
                            {{ add_player_form.last_name.label_tag }}
                            {{ add_player_form.last_name }}
                            {% endif %}
                            {% if tournament.license_is_required is False %}
                            {{ add_player_form.licence_id.label_tag }}
                            {% if tournament.license_is_required is False %}(facultatif){% endif %}
                            {{ add_player_form.licence_id }}
                            {% endif %}
                        {% endif %}

                        <button type="submit" name="add_player" class="rounded-button">
                            {% if add_player_form.user_without_licence %}
                                Confirmer
                            {% else %}
                                {% if current_players|length == 0 %}
                                    Confirmer
                                {% else %}
                                    Ajouter un partenaire
                                {% endif %}
                            {% endif %}
                        </button>
                    </div>
                    {% endif %}

                    <!-- Show players added to the team only if there are players added -->
                    {% if current_players|length >= tournament.minimum_player_per_team %}
                    <div class="margin10">
                    </div>
                    <div class="semibold margin10">
                    {% if cart_data.waiting_list_position == 1 %}
                        Tournoi complet, {{ cart_data.waiting_list_position }} équipe en liste d'attente actuellement.
                    {% elif cart_data.waiting_list_position > 1 %}
                        Tournoi complet, {{ cart_data.waiting_list_position }} équipes en liste d'attente actuellement.
                    {% elif cart_data.waiting_list_position == 0 %}
                        Tournoi complet, vous seriez la première équipe en liste d'attente.
                    {% endif %}
                    </div>

                    <div>
                        {% if tournament.should_request_payment and cart_data.waiting_list_position < 0 %}
                            <div class="semibold">
                                Confirmer votre inscription en payant immédiatement :
                            </div>
                            <button type="submit" name="proceed_to_payment" class="rounded-button">
                                Procéder au paiement de {{ cart_data.team_fee_from_cart_players_formatted }}
                            </button>
                        {% endif %}
                        {% if tournament.should_request_payment is False or tournament.online_payment_is_mandatory is False or cart_data.waiting_list_position >= 0 %}
                            {% if tournament.should_request_payment and cart_data.waiting_list_position < 0 %}
                            <div class="semibold topmargin20">
                                Ou confirmer votre inscription et payer sur place le jour du tournoi :
                            </div>
                            {% endif %}
                        <button type="submit" name="register_team" class="rounded-button">
                            {% if cart_data.waiting_list_position < 0 %}
                                Confirmer l'inscription
                            {% else %}
                                Se mettre en liste d'attente
                            {% endif %}
                        </button>
                        {% endif %}
                    </div>
                    {% endif %}
                </form>
            {% endif %}
        </div>
    </div>
</div>

<script>
// Safe countdown script with no automatic reloads
document.addEventListener('DOMContentLoaded', function() {
    // Get the countdown element
    const countdownElement = document.getElementById('countdown');
    if (!countdownElement) return;

    // Only proceed with countdown if cart is not expired according to backend
    const cartExpiredDiv = document.querySelector('.alert-danger');
    if (cartExpiredDiv && cartExpiredDiv.textContent.includes('expiré')) {
        // Cart is already expired according to backend, don't set up countdown
        return;
    }

    // Get the expiry date from the data attribute (Unix timestamp)
    const expiryTimestamp = countdownElement.getAttribute('data-expiry');
    if (!expiryTimestamp) return;

    // Convert Unix timestamp to Date object
    const expiryDate = new Date(parseInt(expiryTimestamp) * 1000);

    // Function to update countdown text
    function updateCountdown() {
        const now = new Date();
        let timeRemaining = Math.max(0, Math.floor((expiryDate - now) / 1000)); // in seconds

        if (timeRemaining <= 0) {
            countdownElement.textContent = "Expiré";

            // Set a flag in localStorage to prevent infinite reload
            if (!localStorage.getItem('cartExpired')) {
                localStorage.setItem('cartExpired', 'true');
                // Reload once when expired
                window.location.reload();
            }
            return;
        }

        // Calculate days, hours, minutes, seconds
        const days = Math.floor(timeRemaining / 86400);
        timeRemaining %= 86400;
        const hours = Math.floor(timeRemaining / 3600);
        timeRemaining %= 3600;
        const minutes = Math.floor(timeRemaining / 60);
        const seconds = timeRemaining % 60;

        // Format the countdown text - ALWAYS include seconds
        let countdownText = '';
        if (days > 0) {
            countdownText += `${days} jour${days > 1 ? 's' : ''}, `;
        }
        if (hours > 0 || days > 0) {
            countdownText += `${hours} heure${hours > 1 ? 's' : ''}, `;
        }
        if (minutes > 0 || hours > 0 || days > 0) {
            countdownText += `${minutes} minute${minutes > 1 ? 's' : ''}, `;
        }
        countdownText += `${seconds} seconde${seconds > 1 ? 's' : ''}`;

        countdownElement.textContent = countdownText;
    }

    // Clear previous expiry flag when starting a new countdown
    localStorage.removeItem('cartExpired');

    // Update immediately
    updateCountdown();

    // Update every second
    const countdownInterval = setInterval(updateCountdown, 1000);

    // Clean up interval when page unloads
    window.addEventListener('unload', function() {
        clearInterval(countdownInterval);
    });
});
</script>
{% endblock %}
