{% extends "base.html.j2" %}
{% from "decor.html.j2" import category_marker, motif_divider, page_badge %}

{% block title %}{{ t.fauna_title | default(site.fauna_label) }}{% endblock %}

{% block extra_styles %}
/* ── Showcase: reusable card-grid layout (showcase-* prefix) ── */

.showcase-header {
    display: flex;
    align-items: baseline;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 0.5rem;
    margin-bottom: 0.25rem;
    position: relative;
    padding-left: 1.5rem;
}
.showcase-header::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0.15em;
    width: 4px;
    height: 48px;
    background: var(--td-color-primary);
    border-radius: 2px;
}
.showcase-header h1 { margin: 0; }
.showcase-header .subtitle { margin: 0; }

.showcase-controls {
    background: var(--td-color-surface);
    padding: 1rem;
    border-radius: var(--td-radius);
    border: 1px solid var(--td-color-border);
    margin-bottom: 1rem;
    box-shadow: var(--td-shadow-sm);
}
.showcase-controls .search-row {
    display: flex;
    gap: 0.5rem;
    flex-wrap: wrap;
}
.showcase-controls .search-input {
    border-radius: 999px;
}
.showcase-controls .filter-select {
    border-radius: 999px;
}
.showcase-stats {
    margin-top: 0.5rem;
    font-size: 0.85rem;
    color: var(--td-color-text-muted);
}
.showcase-hint {
    text-align: center;
    color: var(--td-color-text-muted);
    font-size: 0.85rem;
    margin-bottom: 1rem;
}

/* Section (category group) */
.showcase-section {
    margin-bottom: 1.5rem;
}
.showcase-section.hidden { display: none; }

.showcase-section-header {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem 1rem;
    background: var(--td-color-bg-light);
    border-radius: 999px;
    cursor: pointer;
    user-select: none;
    margin-bottom: 0.75rem;
    transition: background 0.15s;
}
.showcase-section-header:hover {
    background: var(--td-color-accent-light);
}
.showcase-section-header .chevron {
    font-size: 0.75rem;
    transition: transform 0.2s;
    color: var(--td-color-primary);
}
.showcase-section-header.collapsed .chevron {
    transform: rotate(-90deg);
}
.showcase-section-header .section-title {
    font-weight: 600;
    color: var(--td-color-primary);
    font-size: 0.95rem;
}
.showcase-section-header .section-count {
    font-size: 0.8rem;
    color: var(--td-color-text-muted);
    margin-left: auto;
}

/* Card grid */
.showcase-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(170px, 1fr));
    gap: 0.75rem;
}
.showcase-section-header.collapsed + .showcase-grid {
    display: none;
}

/* Card */
.showcase-card {
    background: var(--td-color-surface);
    border-radius: var(--td-radius);
    border: 2px solid transparent;
    overflow: hidden;
    cursor: pointer;
    transition: box-shadow 0.2s, border-color 0.2s;
    box-shadow: 0 1px 3px rgba(0,0,0,0.08);
}
.showcase-card:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.12);
}
.showcase-card.active {
    border-color: var(--td-color-primary);
}
.showcase-card.hidden { display: none; }

.showcase-card-img {
    width: 100px;
    height: 100px;
    object-fit: cover;
    display: block;
    background: var(--td-color-bg-light);
    border-radius: 50%;
    margin: 1rem auto 0;
}
.showcase-card-placeholder {
    width: 100px;
    height: 100px;
    background: var(--td-color-bg-light);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2.5rem;
    color: var(--td-color-border-dark);
    border-radius: 50%;
    margin: 1rem auto 0;
}

.showcase-card-body {
    padding: 0.5rem 0.6rem;
}
.showcase-card-body .card-name {
    font-weight: 600;
    font-size: 0.9rem;
    color: var(--td-color-primary);
    line-height: 1.3;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.showcase-card-body .card-sub {
    font-size: 0.8rem;
    color: var(--td-color-text-muted);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* Inline detail panel (spans full grid width) */
.showcase-detail {
    grid-column: 1 / -1;
    background: var(--td-color-surface);
    border: 2px solid var(--td-color-primary);
    border-radius: var(--td-radius);
    padding: 1.5rem;
    position: relative;
    margin: 0.25rem 0 0.5rem 0;
    animation: showcase-detail-in 0.2s ease-out;
    box-shadow: var(--td-shadow-md);
}
@keyframes showcase-detail-in {
    from { opacity: 0; transform: translateY(-8px); }
    to   { opacity: 1; transform: translateY(0); }
}
.showcase-detail-layout {
    display: flex;
    gap: 1.5rem;
    align-items: flex-start;
}
.showcase-detail-img {
    width: 250px;
    min-width: 250px;
    max-height: 300px;
    object-fit: cover;
    border-radius: var(--td-radius);
    background: var(--td-color-bg-light);
}
.showcase-detail-placeholder {
    width: 250px;
    min-width: 250px;
    height: 200px;
    background: var(--td-color-bg-light);
    border-radius: var(--td-radius);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 4rem;
    color: var(--td-color-border-dark);
}
.showcase-detail-info {
    flex: 1;
    min-width: 0;
}
.showcase-detail-info h3 {
    margin: 0 0 0.25rem 0;
    font-size: 1.35rem;
    color: var(--td-color-primary);
}
.showcase-detail-info .detail-portuguese {
    font-size: 1rem;
    color: var(--td-color-text-muted);
    margin-bottom: 0.5rem;
}
.showcase-detail-info .detail-scientific {
    font-style: italic;
    color: var(--td-color-text-muted);
    font-size: 0.95rem;
    margin-bottom: 0.5rem;
}
.showcase-detail-info .detail-field {
    font-size: 0.9rem;
    color: var(--td-color-text-secondary);
    margin-bottom: 0.3rem;
}
.showcase-detail-info .detail-field strong {
    color: var(--td-color-primary);
}
.showcase-detail-info .detail-tag {
    display: inline-block;
    font-size: 0.8rem;
    background: var(--td-color-accent-light);
    color: var(--td-color-accent-muted);
    padding: 0.2rem 0.75rem;
    border-radius: 999px;
    margin-top: 0.35rem;
    margin-bottom: 0.35rem;
}
.showcase-detail-info .detail-info-text {
    margin-top: 0.5rem;
    padding: 0.5rem;
    background: var(--td-color-warning-bg);
    border-radius: var(--td-radius);
    font-size: 0.9rem;
    color: var(--td-color-text-muted);
}
.showcase-detail-links {
    margin-top: 0.75rem;
    display: flex;
    gap: 0.75rem;
    flex-wrap: wrap;
}
.showcase-detail-links a {
    font-size: 0.85rem;
    color: var(--td-color-primary);
    text-decoration: none;
}
.showcase-detail-links a:hover {
    text-decoration: underline;
}
.showcase-detail-close {
    position: absolute;
    top: 0.5rem;
    right: 0.75rem;
    background: none;
    border: none;
    font-size: 1.4rem;
    cursor: pointer;
    color: var(--td-color-text-muted);
    line-height: 1;
    padding: 0.25rem;
}
.showcase-detail-close:hover {
    color: var(--td-color-text);
}

/* No results */
.showcase-no-results {
    padding: 3rem;
    text-align: center;
    color: var(--td-color-text-muted);
}
.showcase-no-results h2 {
    margin: 0 0 0.5rem 0;
    color: var(--td-color-text-muted);
}

/* Tablet */
@media (max-width: 900px) and (min-width: 701px) {
    .showcase-grid {
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    }
    .showcase-detail-layout {
        gap: 1rem;
    }
    .showcase-detail-img,
    .showcase-detail-placeholder {
        width: 160px;
        min-width: 140px;
    }
}
/* Mobile */
@media (max-width: 700px) {
    .showcase-grid {
        grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    }
    .showcase-card-img,
    .showcase-card-placeholder {
        height: 120px;
    }
    .showcase-detail-layout {
        flex-direction: column;
    }
    .showcase-detail-img,
    .showcase-detail-placeholder {
        width: 100%;
        min-width: 0;
        max-height: 220px;
    }
    .showcase-controls .search-row {
        flex-direction: column;
    }
    .showcase-controls .search-row .search-input,
    .showcase-controls .search-row .filter-select {
        width: 100%;
    }
}
{% endblock %}

{% block content %}
    <header>
        <h1>{{ category_marker(intensity=intensity) }} {{ t.fauna_title | default(site.fauna_label) }} {{ page_badge(badge_type=theme.page_badge|default("moiety")) }}</h1>
        <p class="subtitle">{{ meta.description }} &mdash; {{ data | length }} {{ t.species_label | default('espécies') }}</p>
    </header>

    <div class="showcase-controls">
        <div class="search-row">
            <input type="text" id="showcase-search" class="search-input"
                   placeholder="{{ t.fauna_search_placeholder | default('Pesquisar...') }}"
                   autocomplete="off"
                   aria-label="{{ t.search_label | default('Pesquisar') }}">
            <select id="showcase-filter" class="filter-select"
                    aria-label="{{ t.filter_label | default('Filtrar resultados') }}">
                <option value="">{{ t.fauna_filter_all | default('Todas as categorias') }}</option>
                {% set categories = [] %}
                {% for item in data %}
                    {% if item.classification_indigenous and item.classification_indigenous not in categories %}
                        {% set _ = categories.append(item.classification_indigenous) %}
                    {% endif %}
                {% endfor %}
                {% for cat in categories | sort %}
                <option value="{{ cat }}">{{ cat }}</option>
                {% endfor %}
            </select>
        </div>
        <div class="showcase-stats" id="showcase-stats" aria-live="polite"></div>
    </div>

    {{ motif_divider(intensity=intensity) }}

    <p class="showcase-hint" id="showcase-hint">{{ t.fauna_select_hint | default('Clique em um animal para ver os detalhes') }}</p>

    <div id="showcase-container"></div>

    <div class="showcase-no-results" id="showcase-no-results" style="display:none">
        <h2>{{ t.fauna_no_results | default('Nenhum resultado') }}</h2>
        <p>{{ t.fauna_no_results_hint | default('Tente um nome diferente ou altere o filtro') }}</p>
    </div>
{% endblock %}

{% block scripts %}
    <script>
    (function() {
        var T = {{ t | tojson }};
        var ALL_DATA = {{ data | tojson }};
        var UNCATEGORIZED_LABEL = T.fauna_category_uncategorized || 'Sem classificação';

        var container = document.getElementById('showcase-container');
        var searchInput = document.getElementById('showcase-search');
        var filterSelect = document.getElementById('showcase-filter');
        var statsEl = document.getElementById('showcase-stats');
        var noResultsEl = document.getElementById('showcase-no-results');
        var hintEl = document.getElementById('showcase-hint');

        var activeDetailEntry = null;
        var activeDetailEl = null;
        var activeCardEl = null;

        // ── Helpers ──

        function escapeHtml(text) {
            if (!text) return '';
            var d = document.createElement('div');
            d.textContent = text;
            return d.innerHTML;
        }

        function normalize(s) {
            return (s || '').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '');
        }

        // ── Group & sort ──

        function groupByCategory(entries) {
            var groups = {};
            for (var i = 0; i < entries.length; i++) {
                var e = entries[i];
                var cat = e.classification_indigenous || '__uncategorized__';
                if (!groups[cat]) groups[cat] = [];
                groups[cat].push(e);
            }
            var sorted = Object.keys(groups).filter(function(k) { return k !== '__uncategorized__'; }).sort();
            if (groups['__uncategorized__']) sorted.push('__uncategorized__');
            return sorted.map(function(k) {
                // Sort entries within group by name_indigenous
                groups[k].sort(function(a, b) {
                    return (a.name_indigenous || '').localeCompare(b.name_indigenous || '');
                });
                return { category: k, label: k === '__uncategorized__' ? UNCATEGORIZED_LABEL : k, entries: groups[k] };
            });
        }

        // ── Render ──

        function renderAll() {
            var groups = groupByCategory(ALL_DATA);
            container.innerHTML = '';
            for (var g = 0; g < groups.length; g++) {
                var group = groups[g];
                var section = document.createElement('div');
                section.className = 'showcase-section';
                section.setAttribute('data-category', group.category);

                // Section header
                var header = document.createElement('div');
                header.className = 'showcase-section-header';
                header.innerHTML = '<span class="chevron">&#9662;</span>' +
                    '<span class="section-title">' + escapeHtml(group.label) + '</span>' +
                    '<span class="section-count" data-total="' + group.entries.length + '">' + group.entries.length + '</span>';
                header.addEventListener('click', toggleSection);
                section.appendChild(header);

                // Card grid
                var grid = document.createElement('div');
                grid.className = 'showcase-grid';
                for (var i = 0; i < group.entries.length; i++) {
                    grid.appendChild(renderCard(group.entries[i]));
                }
                section.appendChild(grid);
                container.appendChild(section);
            }
            updateStats();
        }

        function renderCard(entry) {
            var card = document.createElement('div');
            card.className = 'showcase-card';
            card.setAttribute('data-id', entry.id);

            if (entry.pic_link) {
                var img = document.createElement('img');
                img.className = 'showcase-card-img';
                img.src = '../' + entry.pic_link;
                img.alt = entry.name_indigenous || '';
                img.loading = 'lazy';
                img.onerror = function() {
                    var ph = document.createElement('div');
                    ph.className = 'showcase-card-placeholder';
                    ph.textContent = '\uD83D\uDC3E';
                    this.replaceWith(ph);
                };
                card.appendChild(img);
            } else {
                var ph = document.createElement('div');
                ph.className = 'showcase-card-placeholder';
                ph.textContent = '\uD83D\uDC3E';
                card.appendChild(ph);
            }

            var body = document.createElement('div');
            body.className = 'showcase-card-body';
            body.innerHTML = '<div class="card-name">' + escapeHtml(entry.name_indigenous) + '</div>' +
                (entry.name_portuguese ? '<div class="card-sub">' + escapeHtml(entry.name_portuguese) + '</div>' : '');
            card.appendChild(body);

            card.addEventListener('click', function() {
                onCardClick(entry, card);
            });

            return card;
        }

        // ── Detail panel ──

        function onCardClick(entry, cardEl) {
            // If clicking the same card, close
            if (activeDetailEntry && activeDetailEntry.id === entry.id) {
                closeDetail();
                return;
            }
            closeDetail();

            activeDetailEntry = entry;
            activeCardEl = cardEl;
            cardEl.classList.add('active');

            var detail = document.createElement('div');
            detail.className = 'showcase-detail';

            var closeBtn = document.createElement('button');
            closeBtn.className = 'showcase-detail-close';
            closeBtn.innerHTML = '&times;';
            closeBtn.setAttribute('aria-label', 'Close');
            closeBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                closeDetail();
            });
            detail.appendChild(closeBtn);

            var layout = document.createElement('div');
            layout.className = 'showcase-detail-layout';

            // Image
            if (entry.pic_link) {
                var img = document.createElement('img');
                img.className = 'showcase-detail-img';
                img.src = '../' + entry.pic_link;
                img.alt = entry.name_indigenous || '';
                img.onerror = function() {
                    var ph = document.createElement('div');
                    ph.className = 'showcase-detail-placeholder';
                    ph.textContent = '\uD83D\uDC3E';
                    this.replaceWith(ph);
                };
                layout.appendChild(img);
            } else {
                var ph = document.createElement('div');
                ph.className = 'showcase-detail-placeholder';
                ph.textContent = '\uD83D\uDC3E';
                layout.appendChild(ph);
            }

            // Info
            var info = document.createElement('div');
            info.className = 'showcase-detail-info';

            var html = '<h3>' + escapeHtml(entry.name_indigenous) + '</h3>';
            if (entry.name_portuguese) {
                html += '<div class="detail-portuguese">' + escapeHtml(entry.name_portuguese) + '</div>';
            }
            if (entry.scientific_name) {
                html += '<div class="detail-scientific">' + escapeHtml(entry.scientific_name) + '</div>';
            }
            if (entry.category) {
                html += '<div class="detail-field"><strong>' + escapeHtml(T.fauna_detail_family || 'Família') + ':</strong> ' + escapeHtml(entry.category) + '</div>';
            }
            if (entry.classification_indigenous) {
                html += '<div class="detail-tag">' + escapeHtml(entry.classification_indigenous) + '</div>';
            }
            if (entry.info) {
                html += '<div class="detail-info-text">' + escapeHtml(entry.info) + '</div>';
            }

            // Cross-links
            if (entry._linked_dictionary && entry._linked_dictionary.length > 0) {
                html += '<div class="showcase-detail-links"><strong>' + escapeHtml(T.see_in_dictionary || 'Ver no Dicionário') + ':</strong> ';
                html += entry._linked_dictionary.map(function(d) {
                    return '<a href="dictionary.html?search=' + encodeURIComponent(d.entry) + '">' + escapeHtml(d.entry) + '</a>';
                }).join(', ');
                html += '</div>';
            }

            info.innerHTML = html;
            layout.appendChild(info);
            detail.appendChild(layout);

            // Insert after the card in the grid
            var grid = cardEl.parentNode;
            var next = cardEl.nextSibling;
            if (next) {
                grid.insertBefore(detail, next);
            } else {
                grid.appendChild(detail);
            }
            activeDetailEl = detail;

            // Scroll into view on mobile
            if (window.innerWidth <= 700) {
                setTimeout(function() {
                    detail.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                }, 50);
            }
        }

        function closeDetail() {
            if (activeDetailEl) {
                activeDetailEl.remove();
                activeDetailEl = null;
            }
            if (activeCardEl) {
                activeCardEl.classList.remove('active');
                activeCardEl = null;
            }
            activeDetailEntry = null;
        }

        // ── Section collapse/expand ──

        function toggleSection(e) {
            var header = e.currentTarget;
            header.classList.toggle('collapsed');
        }

        // ── Search & filter ──

        function matchesSearch(entry, query) {
            if (!query) return true;
            var q = normalize(query);
            return normalize(entry.name_indigenous).indexOf(q) !== -1 ||
                   normalize(entry.name_portuguese).indexOf(q) !== -1 ||
                   normalize(entry.scientific_name).indexOf(q) !== -1 ||
                   normalize(entry.category).indexOf(q) !== -1 ||
                   normalize(entry.info).indexOf(q) !== -1;
        }

        function filterEntries() {
            closeDetail();
            var query = searchInput.value.trim();
            var catFilter = filterSelect.value;
            var visibleCount = 0;

            var sections = container.querySelectorAll('.showcase-section');
            for (var s = 0; s < sections.length; s++) {
                var section = sections[s];
                var sectionCat = section.getAttribute('data-category');
                var cards = section.querySelectorAll('.showcase-card');
                var sectionVisible = 0;

                // If category filter is active and doesn't match this section
                var sectionMatchesCat = !catFilter ||
                    sectionCat === catFilter ||
                    (catFilter === '__uncategorized__' && sectionCat === '__uncategorized__');

                for (var c = 0; c < cards.length; c++) {
                    var cardId = parseInt(cards[c].getAttribute('data-id'));
                    var entry = ALL_DATA.find(function(e) { return e.id === cardId; });
                    var visible = sectionMatchesCat && entry && matchesSearch(entry, query);
                    cards[c].classList.toggle('hidden', !visible);
                    if (visible) {
                        sectionVisible++;
                        visibleCount++;
                    }
                }

                section.classList.toggle('hidden', sectionVisible === 0);
                // Update section count
                var countEl = section.querySelector('.section-count');
                if (countEl) countEl.textContent = sectionVisible;

                // Uncollapse when filtering
                if (query || catFilter) {
                    var hdr = section.querySelector('.showcase-section-header');
                    if (hdr) hdr.classList.remove('collapsed');
                }
            }

            noResultsEl.style.display = visibleCount === 0 ? '' : 'none';
            updateStats(visibleCount);
        }

        function updateStats(count) {
            if (count === undefined) count = ALL_DATA.length;
            var label = count !== 1 ? (T.fauna_result_plural || 'espécies') : (T.fauna_result_singular || 'espécie');
            statsEl.textContent = count + ' ' + label;
        }

        // ── Debounce ──

        function debounce(fn, ms) {
            var timer;
            return function() {
                clearTimeout(timer);
                timer = setTimeout(fn, ms);
            };
        }

        // ── Init ──

        renderAll();

        searchInput.addEventListener('input', debounce(filterEntries, 200));
        filterSelect.addEventListener('change', filterEntries);

        // URL param support
        var urlParams = new URLSearchParams(window.location.search);
        var initialSearch = urlParams.get('search');
        var initialCat = urlParams.get('category');
        if (initialSearch) {
            searchInput.value = initialSearch;
            filterEntries();
        }
        if (initialCat) {
            filterSelect.value = initialCat;
            filterEntries();
        }
    })();
    </script>
{% endblock %}
