{% extends 'base.html.twig' %}
{% from 'coleccion/_macros.html.twig' import renderTabla, renderFiltros %}

{% block title %}Mi colección{% endblock %}

{% block body %}
<div class="container">

    <div class="page-header">
        <div>
            <h1 class="page-title">🎲 Mi colección</h1>
            {% if app.user.usuarioBgg %}
                <p class="page-subtitle">
                    BGG: <strong style="color:var(--color-primary)">{{ app.user.usuarioBgg }}</strong>
                </p>
            {% endif %}
        </div>
    </div>

    <div class="coleccion-sync-card">
        <p class="section-title">Sincronizar con BGG</p>
        <p style="color:var(--color-label-2);font-size:.875rem">
            Importa tu colección directamente desde BoardGameGeek.
        </p>
        <div class="coleccion-sync-row">
            <input type="text" id="bgg-username" class="form-control" placeholder="Tu usuario de BGG"
                   value="{{ app.user.usuarioBgg ?? '' }}" style="max-width:280px">
            <button type="button" id="btn-sync" class="btn btn-primary">🔄 Sincronizar</button>
        </div>
        <p id="sync-status" class="coleccion-sync-status" aria-live="polite"></p>
    </div>

    {% if miColeccion|length > 0 %}
        {{ renderFiltros('filtros-mia', 'tabla-mia') }}
        {{ renderTabla(miColeccion, 'tabla-mia', false) }}
    {% else %}
    <div class="empty-state">
        <span class="empty-icon" aria-hidden="true">🎲</span>
        <h3>Sin juegos todavía</h3>
        <p>Sincroniza tu colección de BGG para importar tus juegos.</p>
    </div>
    {% endif %}

</div>

{% include 'coleccion/_juego_modal.html.twig' %}
{% endblock %}

{% block javascripts %}
<script>
(function () {
    'use strict';

    /* ── Sincronizar BGG ─────────────────────────────────────────── */
    const btnSync   = document.getElementById('btn-sync');
    const inputBgg  = document.getElementById('bgg-username');
    const syncStatus = document.getElementById('sync-status');

    if (btnSync) {
        btnSync.addEventListener('click', async () => {
            const username = inputBgg.value.trim();
            if (!username) { syncStatus.textContent = 'Introduce tu usuario de BGG.'; return; }
            btnSync.disabled = true;
            syncStatus.textContent = 'Sincronizando…';
            try {
                const res  = await fetch('{{ path('app_coleccion_sincronizar') }}', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
                    body: JSON.stringify({ username }),
                });
                const data = await res.json();
                syncStatus.textContent = data.ok
                    ? '✓ Colección sincronizada. Recarga la página para ver tus juegos.'
                    : '✗ ' + (data.error ?? 'Error desconocido.');
                syncStatus.style.color = data.ok ? 'var(--color-success)' : 'var(--color-danger)';
            } catch { syncStatus.textContent = '✗ Error de red.'; syncStatus.style.color = 'var(--color-danger)'; }
            finally  { btnSync.disabled = false; }
        });
    }

    /* ── Filtros + Ordenación ────────────────────────────────────── */
    function initTabla(tableId, panelId) {
        const tabla  = document.getElementById(tableId);
        const panel  = document.getElementById(panelId);
        if (!tabla || !panel) return;

        const tbody       = tabla.querySelector('tbody');
        const totalRows   = tbody.querySelectorAll('tr.coleccion-row').length;
        const inputBuscar = panel.querySelector('.js-col-buscar');
        const btnLimpiar  = panel.querySelector('.js-col-limpiar');
        const contador    = panel.querySelector('.js-col-contador');

        let filtros       = { complejidad: [], duracion: [], jugadores: [] };
        let textoBusqueda = '';
        let sortCol       = null;
        let sortDir       = 'asc';

        function hayFiltros() {
            return filtros.complejidad.length > 0 || filtros.duracion.length > 0 ||
                   filtros.jugadores.length > 0    || textoBusqueda !== '';
        }

        function aplicarFiltros() {
            const activo = hayFiltros();
            btnLimpiar.style.display = activo ? 'inline-flex' : 'none';

            let visibles = 0;
            tbody.querySelectorAll('tr.coleccion-row').forEach(row => {
                const d = row.dataset;
                let ok  = true;

                if (textoBusqueda) {
                    const haystack = (d.nombre || '') + ' ' + (d.designers || '');
                    if (!haystack.includes(textoBusqueda)) ok = false;
                }

                if (ok && filtros.complejidad.length > 0) {
                    const peso = parseFloat(d.weight);
                    const edad = parseInt(d.age, 10);
                    let cumple = false;
                    filtros.complejidad.forEach(pill => {
                        const tipo = pill.dataset.complejidad;
                        if (tipo === 'infantil') {
                            if (!isNaN(edad) && edad > 0 && edad < 7) cumple = true;
                        } else if (!isNaN(peso)) {
                            if (peso >= parseFloat(pill.dataset.pesoMin) &&
                                peso <= parseFloat(pill.dataset.pesoMax)) cumple = true;
                        }
                    });
                    if (!cumple) ok = false;
                }

                if (ok && filtros.duracion.length > 0) {
                    const tiempo = parseInt(d.time, 10);
                    if (!isNaN(tiempo) && tiempo > 0) {
                        let cumple = false;
                        filtros.duracion.forEach(pill => {
                            const dMin = pill.dataset.durMin !== undefined ? parseInt(pill.dataset.durMin, 10) : 0;
                            const dMax = pill.dataset.durMax !== undefined ? parseInt(pill.dataset.durMax, 10) : Infinity;
                            if (tiempo >= dMin && tiempo <= dMax) cumple = true;
                        });
                        if (!cumple) ok = false;
                    }
                }

                if (ok && filtros.jugadores.length > 0) {
                    const jMin = parseInt(d.minJug, 10);
                    const jMax = parseInt(d.maxJug, 10);
                    if (!isNaN(jMin) && !isNaN(jMax) && jMin > 0 && jMax > 0) {
                        let cumple = false;
                        filtros.jugadores.forEach(pill => {
                            const fMin = parseInt(pill.dataset.jugMin, 10);
                            const fMax = pill.dataset.jugMax !== undefined ? parseInt(pill.dataset.jugMax, 10) : null;
                            if (fMax !== null) { if (jMax >= fMin && jMin <= fMax) cumple = true; }
                            else               { if (jMax >= fMin) cumple = true; }
                        });
                        if (!cumple) ok = false;
                    }
                }

                row.style.display = ok ? '' : 'none';
                if (ok) visibles++;
            });

            if (activo) {
                contador.textContent = `${visibles} de ${totalRows} juegos`;
                contador.style.display = 'block';
            } else {
                contador.style.display = 'none';
            }
        }

        function valorOrden(row, col) {
            const d = row.dataset;
            switch (col) {
                case 'nombre': return d.nombre || '';
                case 'rating': return parseFloat(d.rating) || 0;
                case 'weight': return parseFloat(d.weight) || 0;
                case 'time':   return parseInt(d.time,   10) || 0;
                case 'age':    return parseInt(d.age,    10) || 0;
                case 'jug':    return parseInt(d.minJug, 10) || 0;
                default:       return '';
            }
        }

        tabla.querySelectorAll('thead th.ct-sortable').forEach(th => {
            th.addEventListener('click', () => {
                const col  = th.dataset.col;
                const type = th.dataset.type;
                if (sortCol === col) { sortDir = sortDir === 'asc' ? 'desc' : 'asc'; }
                else                 { sortCol = col; sortDir = type === 'num' ? 'desc' : 'asc'; }

                tabla.querySelectorAll('thead th').forEach(t => {
                    t.classList.remove('ct-sort-asc', 'ct-sort-desc');
                    const ic = t.querySelector('.ct-sort-icon');
                    if (ic) ic.textContent = '⇅';
                });
                th.classList.add(sortDir === 'asc' ? 'ct-sort-asc' : 'ct-sort-desc');
                const ic = th.querySelector('.ct-sort-icon');
                if (ic) ic.textContent = sortDir === 'asc' ? '↑' : '↓';

                Array.from(tbody.querySelectorAll('tr.coleccion-row'))
                    .sort((a, b) => {
                        const va = valorOrden(a, col), vb = valorOrden(b, col);
                        const cmp = type === 'text' ? va.localeCompare(vb, 'es') : (va - vb);
                        return sortDir === 'asc' ? cmp : -cmp;
                    })
                    .forEach(row => tbody.appendChild(row));
            });
        });

        if (inputBuscar) {
            inputBuscar.addEventListener('input', () => {
                textoBusqueda = inputBuscar.value.toLowerCase();
                aplicarFiltros();
            });
        }

        panel.querySelectorAll('.c-pill[data-grupo]').forEach(pill => {
            pill.addEventListener('click', () => {
                const grupo = pill.dataset.grupo;
                const idx   = filtros[grupo].indexOf(pill);
                if (idx > -1) { pill.classList.remove('activa'); filtros[grupo].splice(idx, 1); }
                else          { pill.classList.add('activa');    filtros[grupo].push(pill); }
                aplicarFiltros();
            });
        });

        if (btnLimpiar) {
            btnLimpiar.addEventListener('click', () => {
                panel.querySelectorAll('.c-pill').forEach(p => p.classList.remove('activa'));
                filtros = { complejidad: [], duracion: [], jugadores: [] };
                if (inputBuscar) inputBuscar.value = '';
                textoBusqueda = '';
                aplicarFiltros();
            });
        }
    }

    initTabla('tabla-mia', 'filtros-mia');
}());
</script>
{% endblock %}
