{% extends "base.html.j2" %}

{% block title %}{{ t.enc_title | default(site.encyclopedia_label) }}{% endblock %}

{% block extra_styles %}
.enc-welcome {
    text-align: center;
    padding: 2rem 1rem;
    background: var(--td-color-primary);
    color: white;
    border-radius: var(--td-radius);
    margin-bottom: 1.5rem;
}
.enc-welcome h1 {
    color: white;
    margin: 0 0 0.5rem 0;
    font-size: 2rem;
}
.enc-welcome-text {
    opacity: 0.9;
    max-width: 600px;
    margin: 0 auto;
    font-size: 0.95rem;
    line-height: 1.6;
}
.enc-stat {
    font-size: 0.85rem;
    opacity: 0.7;
    margin-top: 0.5rem;
}
.portal-section {
    background: var(--td-color-surface);
    border: 1px solid var(--td-color-border);
    border-radius: var(--td-radius);
    padding: 1.25rem;
    margin-bottom: 1.5rem;
}
.portal-section h2 {
    margin: 0 0 1rem 0;
    font-size: 1.1rem;
    color: var(--td-color-primary);
    border-bottom: 2px solid var(--td-color-accent);
    padding-bottom: 0.5rem;
}
.portal-columns {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1.5rem;
}
.portal-columns .portal-section {
    margin-bottom: 0;
}
.featured-card {
    display: flex;
    gap: 1.25rem;
}
.featured-image {
    flex-shrink: 0;
    width: 200px;
}
.featured-image img {
    width: 100%;
    border-radius: var(--td-radius);
    object-fit: cover;
}
.featured-image .credit {
    font-size: 0.75rem;
    color: var(--td-color-text-muted);
    margin-top: 0.25rem;
}
.featured-text h3 {
    margin: 0 0 0.5rem 0;
    font-size: 1.2rem;
}
.featured-text h3 a {
    color: var(--td-color-primary);
    text-decoration: none;
}
.featured-text h3 a:hover {
    color: var(--td-color-accent);
}
.featured-abstract {
    font-style: italic;
    color: var(--td-color-text-secondary);
    margin: 0 0 0.5rem 0;
    font-size: 0.9rem;
    line-height: 1.5;
}
.featured-excerpt {
    color: var(--td-color-text-secondary);
    font-size: 0.9rem;
    line-height: 1.6;
    margin: 0 0 0.5rem 0;
}
.featured-readmore {
    display: inline-block;
    color: var(--td-color-accent);
    text-decoration: none;
    font-size: 0.9rem;
    font-weight: 500;
}
.featured-readmore:hover {
    text-decoration: underline;
}
.cat-list {
    list-style: none;
    padding: 0;
    margin: 0;
}
.cat-list > li {
    padding: 0.3rem 0;
}
.cat-list a {
    color: var(--td-color-accent);
    text-decoration: none;
    font-size: 0.95rem;
}
.cat-list a:hover {
    text-decoration: underline;
}
.cat-count {
    font-size: 0.8rem;
    color: var(--td-color-text-muted);
}
.cat-list ul {
    list-style: none;
    padding-left: 1rem;
    margin: 0.15rem 0;
}
.cat-list ul li {
    padding: 0.15rem 0;
}
.cat-list ul a {
    font-size: 0.85rem;
}
.highlights-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));
    gap: 0.75rem;
}
.highlight-card {
    text-decoration: none;
    color: inherit;
    text-align: center;
    transition: transform 0.2s;
}
.highlight-card:hover {
    transform: translateY(-2px);
}
.highlight-card img {
    width: 100%;
    height: 80px;
    object-fit: cover;
    border-radius: var(--td-radius);
}
.highlight-card span {
    font-size: 0.8rem;
    color: var(--td-color-primary);
    display: block;
    margin-top: 0.25rem;
}
.highlight-card:hover span {
    color: var(--td-color-accent);
}
.entry {
    transition: background 0.2s;
}
.entry:hover {
    background: var(--td-color-bg-light);
}
.entry-header {
    display: flex;
    align-items: baseline;
    gap: 0.5rem;
    flex-wrap: wrap;
    margin-bottom: 0.25rem;
}
.entry-word {
    font-size: 1.25rem;
    font-weight: 600;
    color: var(--td-color-primary);
}
.entry-word a {
    color: inherit;
    text-decoration: none;
}
.entry-word a:hover {
    color: var(--td-color-accent);
    text-decoration: underline;
}
.entry-type-tag {
    font-size: 0.7rem;
    background: var(--td-color-accent-light);
    color: var(--td-color-text-muted);
    padding: 0.1rem 0.4rem;
    border-radius: var(--td-radius);
}
.entry-summary {
    color: var(--td-color-text-secondary);
    font-size: 0.95rem;
    margin: 0;
    line-height: 1.5;
}
.entry-categories {
    margin-top: 0.35rem;
    display: flex;
    gap: 0.25rem;
    flex-wrap: wrap;
}
.entry-cat {
    font-size: 0.72rem;
    background: var(--td-color-border);
    color: var(--td-color-text-secondary);
    padding: 0.12rem 0.4rem;
    border-radius: var(--td-radius);
    cursor: pointer;
}
.entry-cat:hover {
    background: var(--td-color-border-dark);
}
.entry-variants {
    font-size: 0.85rem;
    color: var(--td-color-text-muted);
    margin-top: 0.2rem;
}
.variant-tag {
    background: var(--td-color-border);
    padding: 0.1rem 0.5rem;
    border-radius: var(--td-radius);
    margin-right: 0.3rem;
    font-style: italic;
}
.enc-skeleton {
    padding: 1.5rem;
}
@media (max-width: 900px) and (min-width: 701px) {
    .portal-columns {
        gap: 1rem;
    }
    .featured-card {
        gap: 1rem;
    }
    .featured-image {
        width: 140px;
        min-width: 120px;
    }
}
@media (max-width: 700px) {
    .portal-columns {
        grid-template-columns: 1fr;
    }
    .featured-card {
        flex-direction: column;
    }
    .featured-image {
        width: 100%;
    }
}
{% endblock %}

{% block content %}
    <div class="enc-welcome">
        <h1>{{ t.enc_title | default(site.encyclopedia_label) }}</h1>
        <p class="enc-welcome-text">{{ t.enc_welcome_text | default('') }}</p>
        <p class="enc-stat">{{ meta.record_count }} {{ t.articles_label | default('verbetes') }}</p>
    </div>

    <div class="no-js-only results-container">
        {% for entry in data %}
        <div class="entry">
            <div class="entry-header">
                <span class="entry-word"><a href="encyclopedia/{{ entry.id }}.html">{{ entry.title }}</a></span>
                {% if entry.entry_type %}<span class="entry-type-tag">{{ entry.entry_type }}</span>{% endif %}
            </div>
            {% if entry.abstract %}<p class="entry-summary">{{ entry.abstract }}</p>{% endif %}
        </div>
        {% endfor %}
    </div>

    <div class="js-only">
        <div class="search-container">
            <div class="search-row">
                <input type="text" id="search-input" class="search-input"
                       placeholder="{{ t.enc_search_placeholder | default('Pesquisar...') }}"
                       autocomplete="off"
                       aria-label="{{ t.search_label | default('Pesquisar') }}">
                <select id="keyword-filter" class="filter-select"
                        aria-label="{{ t.filter_label | default('Filtrar resultados') }}">
                    <option value="">{{ t.enc_filter_all | default('Todas as categorias') }}</option>
                    <option value="__uncategorized__">{{ t.enc_filter_uncategorized | default('Sem categoria') }}</option>
                </select>
            </div>
            <div class="stats" id="stats" aria-live="polite"></div>
        </div>

        <div id="portal">
            <div id="featured-section" class="portal-section" style="display:none;"></div>
            <div class="portal-columns">
                <div id="categories-section" class="portal-section" style="display:none;"></div>
                <div id="highlights-section" class="portal-section" style="display:none;"></div>
            </div>
        </div>

        <div class="results-container" id="results" style="display:none;">
            <div class="enc-skeleton" id="loading">
                <div class="skeleton skeleton-block"></div>
                <div class="skeleton skeleton-line"></div>
                <div class="skeleton skeleton-line"></div>
                <div class="skeleton skeleton-line" style="width:60%"></div>
            </div>
        </div>
    </div>
{% endblock %}

{% block scripts %}
    <script>
    var T = {{ t | tojson }};
    var BASE_PATH = '{{ base_path | default("../") }}';

    function hasCategory(entry, value) {
        if (value === '__uncategorized__') return !entry.categories || entry.categories.length === 0;
        return entry.categories && entry.categories.some(function(cat) {
            return cat === value || cat.indexOf(value + '/') === 0;
        });
    }

    function attachCategoryFilters() {
        document.querySelectorAll('.entry-cat').forEach(function(el) {
            el.addEventListener('click', function(e) {
                e.stopPropagation();
                var cat = this.getAttribute('data-category');
                if (cat) {
                    var kw = document.getElementById('keyword-filter');
                    var found = false;
                    for (var i = 0; i < kw.options.length; i++) {
                        if (kw.options[i].value === cat) { found = true; break; }
                    }
                    if (!found) {
                        var opt = document.createElement('option');
                        opt.value = cat;
                        opt.textContent = cat;
                        kw.appendChild(opt);
                    }
                    kw.value = cat;
                    kw.dispatchEvent(new Event('change'));
                }
            });
        });
    }

    function addFilterOption(kwFilter, value) {
        for (var i = 0; i < kwFilter.options.length; i++) {
            if (kwFilter.options[i].value === value) return;
        }
        var opt = document.createElement('option');
        opt.value = value;
        opt.textContent = value;
        kwFilter.appendChild(opt);
    }

    var json = {% if client_index %}{{ client_index | tojson }}{% else %}{
        data: {{ data | tojson }},
        category_tree: {},
        featured: null,
        highlights: []
    }{% endif %};
    (function() {
            var kwFilter = document.getElementById('keyword-filter');
            var searchInput = document.getElementById('search-input');
            var portal = document.getElementById('portal');
            var resultsEl = document.getElementById('results');

            // --- Render Featured Article ---
            if (json.featured) {
                var f = json.featured;
                var html = '<h2>' + escapeHtml(T.enc_featured_title) + '</h2>';
                html += '<div class="featured-card">';
                if (f.image) {
                    html += '<div class="featured-image">';
                    html += '<a href="encyclopedia/' + encodeURIComponent(f.id) + '.html">';
                    html += '<img src="' + BASE_PATH + escapeHtml(f.image.url) + '" alt="' + escapeHtml(f.image.alt || f.title) + '">';
                    html += '</a>';
                    if (f.image.credit) html += '<div class="credit">' + escapeHtml(f.image.credit) + '</div>';
                    html += '</div>';
                }
                html += '<div class="featured-text">';
                html += '<h3><a href="encyclopedia/' + encodeURIComponent(f.id) + '.html">' + escapeHtml(f.title) + '</a></h3>';
                if (f.abstract) html += '<p class="featured-abstract">' + escapeHtml(f.abstract) + '</p>';
                if (f.content_excerpt) html += '<p class="featured-excerpt">' + escapeHtml(f.content_excerpt) + '</p>';
                html += '<a href="encyclopedia/' + encodeURIComponent(f.id) + '.html" class="featured-readmore">' + escapeHtml(T.enc_read_more) + ' &rarr;</a>';
                html += '</div></div>';
                document.getElementById('featured-section').innerHTML = html;
                document.getElementById('featured-section').style.display = '';
            }

            // --- Render Category Tree (top two levels) ---
            if (json.category_tree) {
                var topKeys = Object.keys(json.category_tree).filter(function(k) { return k !== '_count'; }).sort();
                if (topKeys.length > 0) {
                    var catHtml = '<h2>' + escapeHtml(T.enc_browse_categories) + '</h2>';
                    catHtml += '<ul class="cat-list">';
                    topKeys.forEach(function(key) {
                        var node = json.category_tree[key];
                        var count = node._count || 0;
                        catHtml += '<li><a href="#" data-cat-filter="' + escapeHtml(key) + '">' + escapeHtml(key) + '</a> <span class="cat-count">(' + count + ')</span>';
                        var subKeys = Object.keys(node).filter(function(k) { return k !== '_count'; }).sort();
                        if (subKeys.length > 0) {
                            catHtml += '<ul>';
                            subKeys.forEach(function(sub) {
                                var subCount = (node[sub] || {})._count || 0;
                                catHtml += '<li><a href="#" data-cat-filter="' + escapeHtml(key + '/' + sub) + '">' + escapeHtml(sub) + '</a> <span class="cat-count">(' + subCount + ')</span></li>';
                            });
                            catHtml += '</ul>';
                        }
                        catHtml += '</li>';
                    });
                    catHtml += '</ul>';
                    document.getElementById('categories-section').innerHTML = catHtml;
                    document.getElementById('categories-section').style.display = '';
                }
            }

            // --- Render Highlights (entries with images) ---
            if (json.highlights && json.highlights.length > 0) {
                var hlHtml = '<h2>' + escapeHtml(T.enc_highlights_title) + '</h2>';
                hlHtml += '<div class="highlights-grid">';
                json.highlights.forEach(function(h) {
                    hlHtml += '<a href="encyclopedia/' + encodeURIComponent(h.id) + '.html" class="highlight-card">';
                    if (h.image) {
                        hlHtml += '<img src="' + BASE_PATH + escapeHtml(h.image.url) + '" alt="' + escapeHtml(h.image.alt || h.title) + '" loading="lazy">';
                    }
                    hlHtml += '<span>' + escapeHtml(h.title) + '</span>';
                    hlHtml += '</a>';
                });
                hlHtml += '</div>';
                document.getElementById('highlights-section').innerHTML = hlHtml;
                document.getElementById('highlights-section').style.display = '';
            }

            // --- Populate filter dropdown ---
            var categories = {};
            json.data.forEach(function(item) {
                if (item.categories) item.categories.forEach(function(cat) { categories[cat] = true; });
            });
            Object.keys(categories).sort().forEach(function(cat) {
                addFilterOption(kwFilter, cat);
            });

            // --- Setup search ---
            initSearchPage({
                data: json.data,
                fuseKeys: [
                    { name: 'title', weight: 2 },
                    { name: 'abstract', weight: 1.5 },
                    { name: 'categories', weight: 1 },
                    { name: 'variants', weight: 0.5 }
                ],
                filterField: null,
                filterElementId: 'keyword-filter',
                filterFn: hasCategory,
                renderEntry: function(entry, matchMap) {
                    var html = '<div class="entry">';
                    html += '<div class="entry-header">';
                    html += '<span class="entry-word"><a href="encyclopedia/' + encodeURIComponent(entry.id) + '.html">' + highlightMatches(entry.title, matchMap['title']) + '</a></span>';
                    if (entry.entry_type) {
                        html += '<span class="entry-type-tag">' + escapeHtml(entry.entry_type) + '</span>';
                    }
                    html += '</div>';
                    if (entry.abstract) {
                        html += '<p class="entry-summary">' + highlightMatches(entry.abstract, matchMap['abstract']) + '</p>';
                    }
                    if (entry.variants && entry.variants.length > 0) {
                        html += '<div class="entry-variants">';
                        entry.variants.forEach(function(v) {
                            html += '<span class="variant-tag">' + escapeHtml(v) + '</span>';
                        });
                        html += '</div>';
                    }
                    if (entry.categories && entry.categories.length > 0) {
                        html += '<div class="entry-categories">';
                        entry.categories.forEach(function(cat) {
                            html += '<span class="entry-cat" data-category="' + escapeHtml(cat) + '">' + escapeHtml(cat) + '</span>';
                        });
                        html += '</div>';
                    }
                    html += '</div>';
                    return html;
                },
                onResults: attachCategoryFilters,
                labels: {
                    results: function(n) { return n !== 1 ? T.enc_result_plural : T.enc_result_singular; },
                    emptyTitle: T.enc_empty_title,
                    emptyText: T.enc_empty_text,
                    noResults: T.enc_no_results,
                    noResultsHint: T.enc_no_results_hint,
                    overflow: function(n) { return T.enc_overflow.replace('{n}', n); }
                }
            });

            // --- Toggle portal/results visibility ---
            function updateView() {
                var q = searchInput.value.trim();
                var f = kwFilter.value;
                if (q.length >= 2 || f) {
                    portal.style.display = 'none';
                    resultsEl.style.display = '';
                } else {
                    portal.style.display = '';
                    resultsEl.style.display = 'none';
                }
            }

            searchInput.addEventListener('input', debounce(updateView, 210));
            kwFilter.addEventListener('change', function() { setTimeout(updateView, 10); });

            // --- Category tree click handlers ---
            document.querySelectorAll('[data-cat-filter]').forEach(function(el) {
                el.addEventListener('click', function(e) {
                    e.preventDefault();
                    var cat = this.getAttribute('data-cat-filter');
                    addFilterOption(kwFilter, cat);
                    kwFilter.value = cat;
                    kwFilter.dispatchEvent(new Event('change'));
                });
            });

            // --- Handle ?category= URL param ---
            var urlParams = new URLSearchParams(window.location.search);
            var catParam = urlParams.get('category');
            if (catParam) {
                addFilterOption(kwFilter, catParam);
                kwFilter.value = catParam;
                kwFilter.dispatchEvent(new Event('change'));
            }

            // Ensure correct initial visibility
            updateView();
    })();
    </script>
{% endblock %}
