{% extends 'base.html.twig' %}

{% block title %}Notificaciones{% endblock %}

{% block body %}
<div class="container">
    <div class="page-header">
        <h1 class="page-title">Notificaciones</h1>
        {% if notificaciones|length > 0 %}
        <div class="page-actions">
            <button id="btn-leer-todas" class="btn btn--secondary">Marcar todas como leídas</button>
        </div>
        {% endif %}
    </div>

    {% if notificaciones|length > 0 %}
    <div class="notif-list">
        {% for notif in notificaciones %}
        <div class="notif-item{% if not notif.leida %} notif-item--unread{% endif %}" data-id="{{ notif.id }}">
            <div class="notif-icon">
                {% if notif.tipo == 'evento_nuevo' %}📅
                {% elseif notif.tipo == 'evento_confirmado' %}✅
                {% elseif notif.tipo == 'evento_cerrado' %}🔒
                {% elseif notif.tipo == 'invitacion' %}✉️
                {% else %}🔔
                {% endif %}
            </div>
            <div class="notif-content">
                {% if notif.url %}
                    <a href="{{ notif.url }}" class="notif-mensaje">{{ notif.mensaje }}</a>
                {% else %}
                    <span class="notif-mensaje">{{ notif.mensaje }}</span>
                {% endif %}
                <span class="notif-fecha">{{ notif.creadaEn|date('d/m/Y H:i') }}</span>
            </div>
            {% if not notif.leida %}
            <span class="notif-dot" aria-label="No leída"></span>
            {% endif %}
        </div>
        {% endfor %}
    </div>
    {% else %}
    <div class="empty-state">
        <span class="empty-icon" aria-hidden="true">🔔</span>
        <h3>Sin notificaciones</h3>
        <p>Aquí aparecerán los avisos de eventos, invitaciones y actividad del grupo.</p>
    </div>
    {% endif %}
</div>
{% endblock %}

{% block javascripts %}
<script>
(function () {
    const markRead = (id) =>
        fetch(`/notificaciones/${id}/leer`, { method: 'POST', headers: { 'X-Requested-With': 'XMLHttpRequest' } });

    document.querySelectorAll('.notif-item--unread .notif-mensaje').forEach(link => {
        link.addEventListener('click', () => {
            const id = link.closest('.notif-item').dataset.id;
            markRead(id);
        });
    });

    const btnTodas = document.getElementById('btn-leer-todas');
    if (btnTodas) {
        btnTodas.addEventListener('click', async () => {
            await fetch('/notificaciones/leer-todas', { method: 'POST', headers: { 'X-Requested-With': 'XMLHttpRequest' } });
            document.querySelectorAll('.notif-item--unread').forEach(el => {
                el.classList.remove('notif-item--unread');
                el.querySelector('.notif-dot')?.remove();
            });
            btnTodas.textContent = '✓ Todas leídas';
            btnTodas.disabled = true;
        });
    }
}());
</script>
{% endblock %}
