{% extends "tienda/base.html" %}
{% load static %}

{% block content %}
<div class="row mt-4">
    <div class="col-12">
        <h2>{% if direccion %}Editar Dirección{% else %}Nueva Dirección{% endif %}</h2>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="{% url 'portal_usuario' %}">Portal de Usuario</a></li>
                <li class="breadcrumb-item"><a href="{% url 'direcciones_usuario' %}">Direcciones</a></li>
                <li class="breadcrumb-item active">{% if direccion %}Editar{% else %}Nueva{% endif %}</li>
            </ol>
        </nav>
    </div>
</div>

<div class="row mt-4">
    <div class="col-md-8 col-lg-6">
        <div class="card">
            <div class="card-body">
                <form method="POST">
                    {% csrf_token %}
                    {{ form.as_p }}
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-primary">{% if direccion %}Actualizar{% else %}Crear{% endif %} Dirección</button>
                        <a href="{% url 'direcciones_usuario' %}" class="btn btn-secondary">Cancelar</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    (function () {
        const cityInput = document.getElementById('city');
        const form = cityInput ? cityInput.form : null;

        if (!cityInput || !form) {
            return;
        }

        const almeriaTowns = new Set([
            {% for town in almeria_municipalities %}
                "{{ town|escapejs }}",
            {% endfor %}
        ].map(normalizeTown));

        function normalizeTown(value) {
            return (value || '')
                .normalize('NFD')
                .replace(/[\u0300-\u036f]/g, '')
                .replace(/[^a-zA-Z0-9\s-]/g, '')
                .replace(/-/g, ' ')
                .toLowerCase()
                .trim()
                .replace(/\s+/g, ' ')
                .replace(/^(la|los)\s+/, '');
        }

        function validateTown() {
            const normalized = normalizeTown(cityInput.value);

            if (!normalized) {
                cityInput.setCustomValidity('');
                cityInput.classList.remove('is-invalid');
                return;
            }

            const isValid = almeriaTowns.has(normalized);

            if (isValid) {
                cityInput.setCustomValidity('');
                cityInput.classList.remove('is-invalid');
            } else {
                cityInput.setCustomValidity('El pueblo/ciudad debe pertenecer a la provincia de Almería.');
                cityInput.classList.add('is-invalid');
            }
        }

        cityInput.addEventListener('input', validateTown);
        cityInput.addEventListener('blur', validateTown);
        form.addEventListener('submit', function () {
            validateTown();
        });

        validateTown();
    })();
</script>

{% endblock %}
