{% extends "base.html" %}
{% load i18n %}

{% block content %}
<section class="py-5">
    <div class="container">
        <div class="mb-4">
            <a href="/" class="btn btn-outline-secondary btn-sm">
                <i class="fa-solid fa-arrow-left me-1"></i> {% trans "Back to Home" %}
            </a>
        </div>
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card shadow">
                    <div class="card-body p-5">
                        <h2 class="text-center mb-4">{% trans "Create your account" %}</h2>
                        
                        <form method="post" novalidate id="registrationForm">
                            {% csrf_token %}
                            
                            {% if form.non_field_errors %}
                                <div class="alert alert-danger">
                                    {% for error in form.non_field_errors %}
                                        {{ error }}
                                    {% endfor %}
                                </div>
                            {% endif %}

                            {% for field in form %}
                                {% if field.name == 'country_code' %}
                                    <div class="mb-3">
                                        <label class="form-label">{% trans "Phone Number" %}</label>
                                        <div class="input-group">
                                            <span class="input-group-text">+</span>
                                            <div class="flex-grow-0" style="min-width: 150px;">
                                                {{ form.country_code }}
                                            </div>
                                            {{ form.phone_number }}
                                        </div>
                                        {% if form.phone_number.errors or form.country_code.errors %}
                                            <div class="text-danger small">
                                                {% for error in form.country_code.errors %}{{ error }} {% endfor %}
                                                {% for error in form.phone_number.errors %}{{ error }} {% endfor %}
                                            </div>
                                        {% endif %}
                                        <div class="form-text text-muted small">{% trans "Select country and enter phone number." %}</div>
                                    </div>
                                {% elif field.name == 'phone_number' %}
                                    {# Handled above #}
                                {% elif field.name == 'otp_method' %}
                                    <div class="mb-3">
                                        <label class="form-label d-block">{{ field.label }}</label>
                                        <div class="btn-group w-100" role="group">
                                            {% for radio in field %}
                                                <input type="radio" class="btn-check" name="{{ field.name }}" id="{{ radio.id_for_label }}" value="{{ radio.data.value }}" {% if radio.data.selected %}checked{% endif %}>
                                                <label class="btn btn-outline-primary" for="{{ radio.id_for_label }}">
                                                    {% if radio.data.value == 'whatsapp' %}
                                                        <i class="fa-brands fa-whatsapp me-1"></i>
                                                    {% else %}
                                                        <i class="fa-solid fa-envelope me-1"></i>
                                                    {% endif %}
                                                    {{ radio.choice_label }}
                                                </label>
                                            {% endfor %}
                                        </div>
                                        {% if field.errors %}
                                            {% for error in field.errors %}
                                                <div class="text-danger small">{{ error }}</div>
                                            {% endfor %}
                                        {% endif %}
                                    </div>
                                {% elif field.name == 'subscription_plan' %}
                                    {% if subscription_enabled %}
                                        <div class="mb-3">
                                            <label class="form-label" for="{{ field.id_for_label }}">{{ field.label }}</label>
                                            {{ field }}
                                            {% if field.errors %}
                                                {% for error in field.errors %}
                                                    <div class="text-danger small">{{ error }}</div>
                                                {% endfor %}
                                            {% endif %}
                                        </div>
                                    {% endif %}
                                {% elif field.name == 'accept_terms' %}
                                    <div class="mb-3 form-check">
                                        {{ field }}
                                        <label class="form-check-label small" for="{{ field.id_for_label }}">
                                            {% trans "I have read and agree to the" %} 
                                            <a href="{% url 'terms_of_service' %}" target="_blank">{% trans "Terms of Service" %}</a> 
                                            {% trans "and" %} 
                                            <a href="{% url 'privacy_policy' %}" target="_blank">{% trans "Privacy Policy" %}</a>
                                        </label>
                                        {% if field.errors %}
                                            {% for error in field.errors %}
                                                <div class="text-danger small">{{ error }}</div>
                                            {% endfor %}
                                        {% endif %}
                                    </div>
                                {% else %}
                                    <div class="mb-3">
                                        <label class="form-label" for="{{ field.id_for_label }}">{{ field.label }}</label>
                                        {{ field }}
                                        {% if field.help_text %}
                                            <div class="form-text text-muted small">{{ field.help_text|safe }}</div>
                                        {% endif %}
                                        {% if field.errors %}
                                            {% for error in field.errors %}
                                                <div class="text-danger small">{{ error }}</div>
                                            {% endfor %}
                                        {% endif %}
                                    </div>
                                {% endif %}
                            {% endfor %}
                            
                            <button type="submit" class="btn btn-primary w-100 py-2 mt-3">{% trans "Register" %}</button>
                        </form>
                        <div class="text-center mt-3">
                            <p>{% trans "Already have an account?" %} <a href="{% url 'login' %}">{% trans "Login" %}</a></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

{% if subscription_enabled %}
<script>
    (function() {
        const fees = {{ fees_json|safe }};
        const monthlyLabel = "{% trans 'Monthly Plan' %}";
        const annualLabel = "{% trans 'Annual Plan' %}";

        function updateFees() {
            // Robustly find role and plan fields
            const roleField = document.querySelector('select[name="role"]') || document.getElementById('id_role');
            const planField = document.querySelector('select[name="subscription_plan"]') || document.getElementById('id_subscription_plan');
            
            if (!roleField || !planField) return;
            
            const currentRole = roleField.value;
            if (!currentRole) return;

            // Match role key (SHIPPER or TRUCK_OWNER)
            const roleKey = Object.keys(fees).find(k => k.toUpperCase() === currentRole.toUpperCase());
            const roleFees = fees[roleKey];
            
            if (roleFees) {
                // Update each option in the plan select
                Array.from(planField.options).forEach(option => {
                    if (option.value === 'MONTHLY') {
                        option.textContent = monthlyLabel + " (" + roleFees.MONTHLY + ")";
                    } else if (option.value === 'ANNUAL') {
                        option.textContent = annualLabel + " (" + roleFees.ANNUAL + ")";
                    }
                });
            }
        }

        // Initialize when DOM is ready
        document.addEventListener('DOMContentLoaded', function() {
            const roleField = document.querySelector('select[name="role"]') || document.getElementById('id_role');
            if (roleField) {
                roleField.addEventListener('change', updateFees);
            }
            
            // Run immediately
            updateFees();
            
            // Run after a short delay to catch any late rendering
            setTimeout(updateFees, 200);
            setTimeout(updateFees, 1000);
            
            // Pulse check: run every 2 seconds for the first 10 seconds 
            // to ensure it stays correct if any other scripts modify the DOM
            let count = 0;
            const interval = setInterval(() => {
                updateFees();
                if (++count > 5) clearInterval(interval);
            }, 2000);
        });

        // Fallback: listen for any change event on the form
        const form = document.getElementById('registrationForm');
        if (form) {
            form.addEventListener('change', function(e) {
                if (e.target && e.target.name === 'role') {
                    updateFees();
                }
            });
        }
    })();
</script>
{% endif %}

{% endblock %}