<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}BFBG{% endblock %} — Board Friend Group</title>
    <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 128 128%22><text y=%221.2em%22 font-size=%2296%22>🎲</text></svg>">
    {% block stylesheets %}
        <link rel="stylesheet" href="{{ asset('styles/app.css') }}">
    {% endblock %}
</head>
<body>

{% if app.user %}
<header class="site-header">
    <nav class="nav-container">
        <a href="{{ path('app_dashboard') }}" class="nav-logo">🎲 BFBG</a>

        <ul class="nav-links">
            <li><a href="{{ path('app_dashboard') }}" class="nav-link">Inicio</a></li>
            <li><a href="{{ path('app_evento_index') }}" class="nav-link">Eventos</a></li>
            <li><a href="{{ path('app_coleccion_index') }}" class="nav-link">Catálogo del grupo</a></li>
            <li><a href="{{ path('app_coleccion_personal') }}" class="nav-link">Mi colección</a></li>
            <li><a href="{{ path('app_grupo_index') }}" class="nav-link">Grupos</a></li>
        </ul>

        {% if app.user %}
        {% set _grupo = grupo_activo() %}
        <a href="{{ path('app_grupo_index') }}"
           class="nav-grupo-badge{% if not _grupo %} nav-grupo-badge--empty{% endif %}"
           title="{{ _grupo ? 'Grupo activo: ' ~ _grupo.nombre : 'Sin grupo activo' }}">
            <span class="nav-grupo-dot" aria-hidden="true"></span>
            <span class="nav-grupo-nombre">{{ _grupo ? _grupo.nombre : 'Sin grupo' }}</span>
        </a>
        {% endif %}

        {% if app.user %}
        {% set _notif = notificaciones_data() %}
        <div class="nav-notif">
            <button class="notif-bell-btn" id="notifBellBtn" aria-expanded="false" aria-haspopup="true"
                    aria-label="Notificaciones{% if _notif.unread > 0 %} ({{ _notif.unread }} sin leer){% endif %}">
                🔔
                {% if _notif.unread > 0 %}
                <span class="notif-badge" id="notifBadge">{{ _notif.unread }}</span>
                {% endif %}
            </button>
            <div class="notif-dropdown-panel" id="notifDropdown" hidden>
                <div class="notif-dropdown-header">
                    <span>Notificaciones</span>
                    {% if _notif.unread > 0 %}
                    <button class="notif-mark-all" id="notifMarkAll">Marcar todas leídas</button>
                    {% endif %}
                </div>
                {% if _notif.recent|length > 0 %}
                <ul class="notif-dropdown-list">
                    {% for notif in _notif.recent %}
                    <li class="notif-dd-item{% if not notif.leida %} notif-dd-item--unread{% endif %}"
                        data-id="{{ notif.id }}" data-url="{{ notif.url ?? '' }}">
                        <span class="notif-dd-icon">
                            {% if notif.tipo == 'evento_nuevo' %}📅
                            {% elseif notif.tipo == 'evento_confirmado' %}✅
                            {% elseif notif.tipo == 'evento_cerrado' %}🔒
                            {% elseif notif.tipo == 'invitacion' %}✉️
                            {% else %}🔔{% endif %}
                        </span>
                        <span class="notif-dd-texto">{{ notif.mensaje }}</span>
                    </li>
                    {% endfor %}
                </ul>
                {% else %}
                <p class="notif-dropdown-empty">Sin notificaciones recientes.</p>
                {% endif %}
                <a href="{{ path('app_notificacion_index') }}" class="notif-dropdown-ver-todas">Ver todas</a>
            </div>
        </div>
        {% endif %}

        <button class="nav-hamburger" id="navHamburger" aria-expanded="false" aria-controls="navMobileDrawer" aria-label="Menú de navegación">
            <svg class="icon-hamburger" width="18" height="14" viewBox="0 0 18 14" fill="currentColor" aria-hidden="true">
                <rect width="18" height="2" rx="1"/>
                <rect y="6" width="18" height="2" rx="1"/>
                <rect y="12" width="18" height="2" rx="1"/>
            </svg>
            <svg class="icon-close" width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true">
                <line x1="1" y1="1" x2="13" y2="13"/>
                <line x1="13" y1="1" x2="1" y2="13"/>
            </svg>
        </button>

        <div class="nav-user">
            <button class="user-menu-toggle" aria-expanded="false" aria-haspopup="true" id="userMenuBtn">
                {% if app.user.avatar %}
                    <img src="{{ asset('uploads/avatars/' ~ app.user.avatar) }}" alt="Avatar" class="user-avatar-small">
                {% else %}
                    <span class="user-avatar-initials-sm" aria-hidden="true">{{ app.user.nombre|first|upper }}</span>
                {% endif %}
                <span>{{ app.user.nombre }}</span>
                <span class="username-tag">{{ app.user.usernameTag }}</span>
                <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor" aria-hidden="true">
                    <path d="M2 4l4 4 4-4"/>
                </svg>
            </button>

            <div class="user-dropdown" id="userDropdown" hidden>
                <a href="{{ path('app_perfil_index') }}" class="dropdown-item">Perfil</a>
                {% if is_granted('ROLE_ADMIN') %}
                    <a href="{{ path('app_admin_dashboard') }}" class="dropdown-item">Administración</a>
                {% endif %}
                <div class="dropdown-divider"></div>
                <form method="post" action="{{ path('app_logout') }}">
                    <input type="hidden" name="_csrf_token" value="{{ csrf_token('logout') }}">
                    <button type="submit" class="dropdown-item dropdown-item--danger">Cerrar sesión</button>
                </form>
            </div>
        </div>
    </nav>

    <div class="nav-mobile-drawer" id="navMobileDrawer" aria-hidden="true">
        <ul class="nav-mobile-links">
            <li><a href="{{ path('app_dashboard') }}" class="nav-mobile-link">Inicio</a></li>
            <li><a href="{{ path('app_evento_index') }}" class="nav-mobile-link">Eventos</a></li>
            <li><a href="{{ path('app_coleccion_index') }}" class="nav-mobile-link">Catálogo del grupo</a></li>
            <li><a href="{{ path('app_coleccion_personal') }}" class="nav-mobile-link">Mi colección</a></li>
            <li><a href="{{ path('app_grupo_index') }}" class="nav-mobile-link">Grupos</a></li>
        </ul>
        <a href="{{ path('app_grupo_index') }}"
           class="nav-grupo-badge nav-mobile-grupo{% if not _grupo %} nav-grupo-badge--empty{% endif %}"
           title="{{ _grupo ? 'Grupo activo: ' ~ _grupo.nombre : 'Sin grupo activo' }}">
            <span class="nav-grupo-dot" aria-hidden="true"></span>
            <span class="nav-grupo-nombre">{{ _grupo ? _grupo.nombre : 'Sin grupo' }}</span>
        </a>
    </div>
</header>
{% endif %}

{% block flash_messages %}
    {% for type, messages in app.flashes %}
        {% for message in messages %}
            <div class="toast toast--{{ type }}" role="alert" aria-live="assertive">
                {{ message }}
                <button class="toast-close" aria-label="Cerrar">×</button>
            </div>
        {% endfor %}
    {% endfor %}
{% endblock %}

<main class="main-content">
    {% block body %}{% endblock %}
</main>

<script>
(function () {
    // User menu toggle
    const btn = document.getElementById('userMenuBtn');
    const dropdown = document.getElementById('userDropdown');
    if (btn && dropdown) {
        btn.addEventListener('click', () => {
            const open = btn.getAttribute('aria-expanded') === 'true';
            btn.setAttribute('aria-expanded', String(!open));
            dropdown.hidden = open;
        });
        document.addEventListener('click', (e) => {
            if (!btn.contains(e.target) && !dropdown.contains(e.target)) {
                btn.setAttribute('aria-expanded', 'false');
                dropdown.hidden = true;
            }
        });
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                btn.setAttribute('aria-expanded', 'false');
                dropdown.hidden = true;
            }
        });
    }

    // Hamburger menu
    const hamburger = document.getElementById('navHamburger');
    const drawer = document.getElementById('navMobileDrawer');
    if (hamburger && drawer) {
        const openDrawer = () => {
            hamburger.setAttribute('aria-expanded', 'true');
            drawer.classList.add('open');
            drawer.setAttribute('aria-hidden', 'false');
        };
        const closeDrawer = () => {
            hamburger.setAttribute('aria-expanded', 'false');
            drawer.classList.remove('open');
            drawer.setAttribute('aria-hidden', 'true');
        };
        hamburger.addEventListener('click', (e) => {
            e.stopPropagation();
            hamburger.getAttribute('aria-expanded') === 'true' ? closeDrawer() : openDrawer();
        });
        document.addEventListener('click', (e) => {
            if (!drawer.contains(e.target) && !hamburger.contains(e.target)) closeDrawer();
        });
        document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeDrawer(); });
        drawer.querySelectorAll('.nav-mobile-link, .nav-mobile-grupo').forEach(
            (link) => link.addEventListener('click', closeDrawer)
        );
    }

    // Notification bell
    const bellBtn = document.getElementById('notifBellBtn');
    const notifPanel = document.getElementById('notifDropdown');
    if (bellBtn && notifPanel) {
        bellBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            const open = bellBtn.getAttribute('aria-expanded') === 'true';
            bellBtn.setAttribute('aria-expanded', String(!open));
            notifPanel.hidden = open;
        });
        document.addEventListener('click', (e) => {
            if (!bellBtn.contains(e.target) && !notifPanel.contains(e.target)) {
                bellBtn.setAttribute('aria-expanded', 'false');
                notifPanel.hidden = true;
            }
        });

        notifPanel.querySelectorAll('.notif-dd-item').forEach(item => {
            item.addEventListener('click', async () => {
                const id = item.dataset.id;
                const url = item.dataset.url;
                if (item.classList.contains('notif-dd-item--unread')) {
                    await fetch(`/notificaciones/${id}/leer`, { method: 'POST' });
                    item.classList.remove('notif-dd-item--unread');
                    const badge = document.getElementById('notifBadge');
                    if (badge) {
                        const n = parseInt(badge.textContent) - 1;
                        n > 0 ? (badge.textContent = n) : badge.remove();
                    }
                }
                if (url) window.location.href = url;
            });
        });

        const markAll = document.getElementById('notifMarkAll');
        if (markAll) {
            markAll.addEventListener('click', async () => {
                await fetch('/notificaciones/leer-todas', { method: 'POST' });
                notifPanel.querySelectorAll('.notif-dd-item--unread').forEach(el => el.classList.remove('notif-dd-item--unread'));
                document.getElementById('notifBadge')?.remove();
                markAll.remove();
            });
        }
    }

    // Toast auto-dismiss
    document.querySelectorAll('.toast').forEach((toast) => {
        const close = toast.querySelector('.toast-close');
        if (close) close.addEventListener('click', () => toast.remove());
        setTimeout(() => toast.remove(), 5000);
    });
})();
</script>

{% block javascripts %}{% endblock %}
</body>
</html>
