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

{% block title %}{{ t.dict_title | default(site.dictionary_label) }}{% endblock %}

{% block extra_styles %}
        .dict-header {
            padding: 1.5rem 0 1rem;
            margin-bottom: 1rem;
            position: relative;
            padding-left: 1.5rem;
        }
        .dict-header::before {
            content: '';
            position: absolute;
            left: 0;
            top: 1.5rem;
            width: 4px;
            height: 48px;
            background: var(--td-color-primary);
            border-radius: 2px;
        }
        .dict-header h1 {
            margin: 0 0 0.5rem 0;
        }
        .dict-controls {
            background: var(--td-color-surface);
            padding: 0.75rem 1rem;
            border-radius: var(--td-radius);
            border: 1px solid var(--td-color-border);
            margin-bottom: 0.75rem;
        }
        .dict-controls .search-row {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }
        .dict-controls .search-input {
            flex: 1;
            min-width: 180px;
            padding: 0.6rem 1rem;
            font-size: 0.95rem;
            border: 1px solid var(--td-color-border);
            border-radius: 999px;
            outline: none;
            transition: border-color 0.2s;
        }
        .dict-controls .search-input:focus {
            border-color: var(--td-color-primary);
            box-shadow: 0 0 0 3px var(--td-color-accent-ring);
        }
        .dict-controls .filter-select {
            padding: 0.6rem 1rem;
            font-size: 0.95rem;
            border: 1px solid var(--td-color-border);
            border-radius: 999px;
            background: var(--td-color-surface);
            cursor: pointer;
        }
        .dict-stats {
            margin-top: 0.4rem;
            font-size: 0.82rem;
            color: var(--td-color-text-muted);
        }
        .dict-layout {
            display: flex;
            gap: 0;
            background: var(--td-color-surface);
            border-radius: var(--td-radius);
            border: 1px solid var(--td-color-border);
            overflow: hidden;
            height: calc(100vh - 10rem);
            min-height: 420px;
            box-shadow: var(--td-shadow-sm);
        }

        /* Letter bar */
        .letter-bar {
            display: flex;
            flex-wrap: wrap;
            gap: 0.25rem;
            padding: 0.5rem;
            border-bottom: 1px solid var(--td-color-border);
            background: var(--td-color-bg-light);
            position: sticky;
            top: 0;
            z-index: 2;
        }
        .letter-btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 2rem;
            height: 2rem;
            border: none;
            border-radius: 999px;
            background: transparent;
            color: var(--td-color-primary);
            font-weight: 600;
            font-size: 0.85rem;
            cursor: pointer;
            transition: background 0.15s, color 0.15s;
        }
        .letter-btn:hover {
            background: var(--td-color-primary);
            color: white;
        }
        .letter-btn.active {
            background: var(--td-color-primary);
            color: white;
        }
        .letter-btn.dimmed {
            opacity: 0.3;
            cursor: default;
        }
        .letter-btn.dimmed:hover {
            background: transparent;
            color: var(--td-color-primary);
        }

        /* Left panel */
        .dict-list-panel {
            width: 280px;
            min-width: 220px;
            border-right: 1px solid var(--td-color-border);
            display: flex;
            flex-direction: column;
            flex-shrink: 0;
            background: var(--td-color-bg-light);
        }
        .word-list {
            overflow-y: auto;
            flex: 1;
        }
        .letter-header {
            position: sticky;
            top: 0;
            background: var(--td-color-bg-light);
            padding: 0.35rem 0.75rem;
            font-weight: 700;
            font-size: 0.9rem;
            color: var(--td-color-primary);
            z-index: 1;
            font-family: var(--td-font-headings);
        }
        .letter-count {
            font-weight: 400;
            color: var(--td-color-text-muted);
            font-size: 0.8rem;
        }
        .word-item {
            padding: 0.3rem 0.75rem;
            cursor: pointer;
            font-size: 0.9rem;
            color: var(--td-color-text);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            transition: background 0.1s;
        }
        .word-item:hover {
            background: var(--td-color-accent-light);
        }
        .word-item.selected {
            background: var(--td-color-primary);
            color: white;
        }
        .letter-group.hidden {
            display: none;
        }
        .word-item.hidden {
            display: none;
        }

        /* Right panel */
        .dict-detail-panel {
            flex: 1;
            overflow-y: auto;
            padding: 1.5rem;
            min-width: 0;
            background: var(--td-color-surface);
        }
        .detail-empty {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
            color: var(--td-color-text-muted);
            text-align: center;
            padding: 2rem;
        }
        .detail-header {
            position: sticky;
            top: 0;
            background: var(--td-color-surface);
            padding-bottom: 0.5rem;
            margin-bottom: 0.5rem;
            border-bottom: 1px solid var(--td-color-border-light);
            z-index: 1;
        }
        .detail-word {
            font-size: 1.8rem;
            font-weight: 700;
            color: var(--td-color-primary);
            margin: 0 0 0.25rem 0;
            font-family: var(--td-font-headings);
        }
        .detail-meta {
            display: flex;
            align-items: baseline;
            gap: 0.75rem;
            flex-wrap: wrap;
            margin-bottom: 1rem;
        }
        .detail-ipa {
            color: var(--td-color-text-muted);
            font-family: var(--td-font-mono);
            font-size: 1.1rem;
        }
        .detail-pos {
            font-size: 0.8rem;
            background: var(--td-color-accent-light);
            color: var(--td-color-accent-muted);
            padding: 0.2rem 0.75rem;
            border-radius: 999px;
            font-weight: 500;
        }
        .detail-definition {
            font-size: 1.05rem;
            color: var(--td-color-text);
            margin-bottom: 1rem;
            line-height: 1.7;
        }
        .detail-example {
            padding: 0.75rem 1rem;
            border-left: 4px solid var(--td-color-primary);
            background: var(--td-color-accent-light);
            color: var(--td-color-text-secondary);
            font-style: italic;
            margin-bottom: 1rem;
            border-radius: 0 var(--td-radius) var(--td-radius) 0;
        }
        .detail-scientific {
            font-style: italic;
            color: var(--td-color-text-muted);
            font-size: 0.95rem;
            margin-bottom: 1rem;
        }
        .detail-comment {
            padding: 0.75rem;
            background: var(--td-color-warning-bg);
            border-radius: var(--td-radius);
            font-size: 0.9rem;
            color: var(--td-color-text-muted);
            margin-bottom: 1rem;
        }
        .detail-audio {
            margin-bottom: 1rem;
        }
        .detail-audio .audio-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin-bottom: 0.35rem;
        }
        .detail-audio .audio-speaker {
            font-size: 0.82rem;
            color: var(--td-color-text-secondary);
            min-width: 5em;
        }
        .detail-audio audio {
            height: 28px;
            flex: 1;
            max-width: 280px;
        }
        .detail-media {
            margin-bottom: 1rem;
        }
        .detail-media img {
            max-width: 200px;
            max-height: 150px;
            border-radius: var(--td-radius);
            object-fit: cover;
        }
        .detail-links {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 1px solid var(--td-color-border-light);
        }
        .detail-links a {
            color: var(--td-color-primary);
            text-decoration: none;
            font-size: 0.9rem;
        }
        .detail-links a:hover {
            text-decoration: underline;
        }
        .link-row {
            display: flex;
            align-items: center;
            gap: 0.4rem;
        }
        .link-icon {
            font-size: 0.85rem;
        }

        .dict-skeleton {
            padding: 1.5rem;
        }

        /* Tablet */
        @media (max-width: 900px) and (min-width: 701px) {
            .dict-list-panel {
                width: 220px;
                min-width: 180px;
            }
            .dict-detail-panel {
                padding: 1.25rem;
            }
            .detail-word {
                font-size: 1.5rem;
            }
        }
        /* Mobile */
        @media (max-width: 700px) {
            .dict-layout {
                flex-direction: column;
                height: auto;
                min-height: auto;
            }
            .dict-list-panel {
                width: 100%;
                min-width: unset;
                border-right: none;
                border-bottom: 1px solid var(--td-color-border);
                max-height: 45vh;
            }
            .letter-bar {
                flex-wrap: nowrap;
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
                scrollbar-width: thin;
            }
            .dict-detail-panel {
                min-height: 40vh;
                padding: 1rem;
            }
            .detail-word {
                font-size: 1.4rem;
            }
        }
{% endblock %}

{% block content %}
    <div class="dict-header">
        <h1>{{ t.dict_title | default(site.dictionary_label) }} {{ page_badge(badge_type=theme.page_badge|default("moiety")) }}</h1>
        <p class="subtitle">{{ meta.description }} &mdash; {{ meta.record_count }} {{ t.entries_label | default('entradas') }}</p>
    </div>

    <div class="no-js-only results-container">
        {% for entry in data %}
        <div class="entry">
            <div class="entry-header">
                <span class="entry-word">{{ entry.entry }}</span>
                {% if entry.pos %}<span class="entry-tag">{{ t['pos_' + entry.pos] | default(entry.pos) }}</span>{% endif %}
            </div>
            {% if entry.definition %}<p class="entry-definition">{{ entry.definition }}</p>{% endif %}
            {% if entry.example_sent %}<p class="entry-example">{{ entry.example_sent }}</p>{% endif %}
        </div>
        {% endfor %}
    </div>

    <div class="js-only">
        <div class="dict-controls">
            <div class="search-row">
                <input type="text" id="search-input" class="search-input" placeholder="{{ t.dict_search_placeholder | default('Pesquisar...') }}" autocomplete="off" aria-label="{{ t.search_label | default('Pesquisar') }}">
                <select id="pos-filter" class="filter-select" aria-label="{{ t.filter_label | default('Filtrar resultados') }}">
                    <option value="">{{ t.dict_all_pos | default(t.dict_filter_all | default('Todas as classes')) }}</option>
                </select>
            </div>
            <div class="dict-stats" id="stats" aria-live="polite"></div>
        </div>

        <div class="dict-layout" id="dict-layout">
            <div class="dict-list-panel" style="{{ section_spine(intensity=intensity) }}">
                <div class="letter-bar" id="letter-bar"></div>
                <div class="word-list" id="word-list"></div>
            </div>
            <div class="dict-detail-panel" id="detail-panel">
                <div class="dict-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>
    </div>
{% endblock %}

{% block scripts %}
    <script>
    (function() {
        var T = {{ t | tojson }};
        var BASE_PATH = '{{ base_path | default("") }}';
        var posLabels = {};
        ['LEX','S','VC','ADV','PPASS','POSP','SUF','INTJ','VT','PRON','V','PRCL','PPAS','PPART','NUM','IP','DEM','CONJ','X','PROPN'].forEach(function(k) {
            posLabels[k] = T['pos_' + k] || k;
        });

        var allEntries = [];
        var entriesById = {};
        var entriesByLetter = {};
        var visibleEntries = [];
        var selectedId = null;
        var availableLetters = [];

        var searchInput = document.getElementById('search-input');
        var posFilter = document.getElementById('pos-filter');
        var letterBar = document.getElementById('letter-bar');
        var wordList = document.getElementById('word-list');
        var detailPanel = document.getElementById('detail-panel');
        var statsDiv = document.getElementById('stats');

        function getEntryLetter(entry) {
            var word = (entry.entry || '').replace(/^-+/, '');
            if (!word) return '?';
            return word[0].toUpperCase();
        }

        function buildLookups(entries) {
            entriesById = {};
            entriesByLetter = {};
            for (var i = 0; i < entries.length; i++) {
                var e = entries[i];
                entriesById[e.id] = e;
                var letter = getEntryLetter(e);
                if (!entriesByLetter[letter]) entriesByLetter[letter] = [];
                entriesByLetter[letter].push(e);
            }
            availableLetters = Object.keys(entriesByLetter).sort(function(a, b) {
                return a.localeCompare(b);
            });
        }

        function renderLetterBar(activeLetters) {
            var html = '';
            for (var i = 0; i < availableLetters.length; i++) {
                var l = availableLetters[i];
                var dimmed = activeLetters && activeLetters.indexOf(l) === -1;
                html += '<button class="letter-btn' + (dimmed ? ' dimmed' : '') + '" data-letter="' + l + '">' + l + '</button>';
            }
            letterBar.innerHTML = html;
        }

        function renderWordList(entries) {
            visibleEntries = entries;
            var grouped = {};
            var letters = [];
            for (var i = 0; i < entries.length; i++) {
                var l = getEntryLetter(entries[i]);
                if (!grouped[l]) {
                    grouped[l] = [];
                    letters.push(l);
                }
                grouped[l].push(entries[i]);
            }
            letters.sort(function(a, b) { return a.localeCompare(b); });

            var html = '';
            for (var li = 0; li < letters.length; li++) {
                var letter = letters[li];
                var group = grouped[letter];
                html += '<div class="letter-group" data-letter="' + letter + '" id="letter-' + letter + '">';
                html += '<div class="letter-header">' + letter + ' <span class="letter-count">(' + group.length + ')</span></div>';
                for (var gi = 0; gi < group.length; gi++) {
                    var e = group[gi];
                    var sel = e.id === selectedId ? ' selected' : '';
                    html += '<div class="word-item' + sel + '" data-id="' + e.id + '">' + escapeHtml(e.entry) + '</div>';
                }
                html += '</div>';
            }
            wordList.innerHTML = html;

            // Update letter bar
            renderLetterBar(letters);
        }

        function renderDetail(entry) {
            if (!entry) {
                detailPanel.innerHTML = '<div class="detail-empty"><p>' + (T.dict_browse_hint || 'Selecione uma entrada para ver os detalhes') + '</p></div>';
                return;
            }

            var html = '';
            html += '<div class="detail-header">';
            html += '<h2 class="detail-word">' + escapeHtml(entry.entry) + '</h2>';

            html += '<div class="detail-meta">';
            if (entry.ipa) {
                html += '<span class="detail-ipa">[' + escapeHtml(entry.ipa) + ']</span>';
            }
            if (entry.pos) {
                html += '<span class="detail-pos">' + escapeHtml(posLabels[entry.pos] || entry.pos) + '</span>';
            }
            html += '</div>';
            html += '</div>';

            if (entry.definition) {
                html += '<div class="detail-definition">' + escapeHtml(entry.definition) + '</div>';
            }

            if (entry.example_sent) {
                html += '<div class="detail-example">' + escapeHtml(entry.example_sent) + '</div>';
            }

            if (entry.scientific_name) {
                html += '<div class="detail-scientific">' + (T.dict_scientific_name || 'Nome científico') + ': <em>' + escapeHtml(entry.scientific_name) + '</em></div>';
            }

            if (entry.comment) {
                html += '<div class="detail-comment">' + escapeHtml(entry.comment) + '</div>';
            }

            // Audio
            if (entry.audio && entry.audio.length > 0) {
                html += '<div class="detail-audio">';
                for (var i = 0; i < entry.audio.length; i++) {
                    var a = entry.audio[i];
                    var mimeType = a.format === 'webm' ? 'audio/webm' : 'audio/wav';
                    var speaker = a.speaker.charAt(0).toUpperCase() + a.speaker.slice(1);
                    html += '<div class="audio-item">';
                    html += '<span class="audio-speaker">' + escapeHtml(speaker) + '</span>';
                    html += '<audio controls preload="none"><source src="' + BASE_PATH + 'recordings/' + escapeHtml(a.file_path) + '" type="' + mimeType + '"></audio>';
                    html += '</div>';
                }
                html += '</div>';
            }

            // Image
            if (entry.pic_link) {
                html += '<div class="detail-media">';
                html += '<a href="' + escapeHtml(entry.pic_link) + '" target="_blank" rel="noopener">';
                html += '<img src="' + escapeHtml(entry.pic_link) + '" alt="' + escapeHtml(entry.entry) + '" loading="lazy" onerror="this.parentNode.parentNode.style.display=\'none\'">';
                html += '</a>';
                html += '</div>';
            }

            // Cross-links
            var hasLinks = (entry._linked_fauna && entry._linked_fauna.length > 0)
                || (entry._linked_encyclopedia && entry._linked_encyclopedia.length > 0)
                || entry.wiki_link;

            if (hasLinks) {
                html += '<div class="detail-links">';

                if (entry._linked_fauna && entry._linked_fauna.length > 0) {
                    for (var fi = 0; fi < entry._linked_fauna.length; fi++) {
                        var f = entry._linked_fauna[fi];
                        html += '<div class="link-row">';
                        html += '<span class="link-icon">&#x1f43e;</span> ';
                        html += '<a href="fauna.html?search=' + encodeURIComponent(f.name_indigenous) + '">' + (T.see_in_fauna || 'Ver na Fauna') + ': ' + escapeHtml(f.name_indigenous) + '</a>';
                        html += '</div>';
                    }
                }

                if (entry._linked_encyclopedia && entry._linked_encyclopedia.length > 0) {
                    for (var ei = 0; ei < entry._linked_encyclopedia.length; ei++) {
                        var enc = entry._linked_encyclopedia[ei];
                        html += '<div class="link-row">';
                        html += '<span class="link-icon">&#x1f4d6;</span> ';
                        html += '<a href="encyclopedia/' + encodeURIComponent(enc.id) + '.html">' + (T.see_in_encyclopedia || 'Ver na Enciclopédia') + ': ' + escapeHtml(enc.title) + '</a>';
                        html += '</div>';
                    }
                }

                if (entry.wiki_link) {
                    html += '<div class="link-row">';
                    html += '<span class="link-icon">&#x1f310;</span> ';
                    html += '<a href="' + escapeHtml(entry.wiki_link) + '" target="_blank" rel="noopener">Wikipedia</a>';
                    html += '</div>';
                }

                html += '</div>';
            }

            detailPanel.innerHTML = html;
        }

        function selectEntry(id) {
            selectedId = id;

            // Update word list selection
            var items = wordList.querySelectorAll('.word-item');
            for (var i = 0; i < items.length; i++) {
                if (parseInt(items[i].getAttribute('data-id')) === id) {
                    items[i].classList.add('selected');
                } else {
                    items[i].classList.remove('selected');
                }
            }

            var entry = entriesById[id];
            renderDetail(entry);

            // On mobile, scroll detail into view
            if (window.innerWidth <= 700) {
                detailPanel.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        }

        function scrollToLetter(letter) {
            var el = document.getElementById('letter-' + letter);
            if (el) {
                wordList.scrollTop = el.offsetTop - wordList.offsetTop;
            }
        }

        function matchesSearch(entry, query) {
            var q = query.toLowerCase();
            var fields = [entry.entry, entry.definition, entry.ipa, entry.scientific_name, entry.comment];
            for (var i = 0; i < fields.length; i++) {
                if (fields[i] && fields[i].toLowerCase().indexOf(q) !== -1) return true;
            }
            return false;
        }

        function filterEntries() {
            var query = searchInput.value.trim();
            var pos = posFilter.value;

            var filtered = allEntries;

            if (query) {
                filtered = filtered.filter(function(e) { return matchesSearch(e, query); });
            }
            if (pos) {
                filtered = filtered.filter(function(e) { return e.pos === pos; });
            }

            renderWordList(filtered);

            // Stats
            if (query || pos) {
                statsDiv.textContent = filtered.length + ' ' + (filtered.length !== 1
                    ? (T.dict_result_plural || 'resultados encontrados')
                    : (T.dict_result_singular || 'resultado encontrado'));
            } else {
                statsDiv.textContent = '';
            }

            // If selected entry is still visible, keep it selected
            if (selectedId && entriesById[selectedId]) {
                var stillVisible = filtered.some(function(e) { return e.id === selectedId; });
                if (!stillVisible) {
                    selectedId = null;
                    renderDetail(null);
                }
            }
        }

        // Keyboard navigation
        function getVisibleIds() {
            var ids = [];
            var items = wordList.querySelectorAll('.word-item');
            for (var i = 0; i < items.length; i++) {
                ids.push(parseInt(items[i].getAttribute('data-id')));
            }
            return ids;
        }

        function handleKeyDown(e) {
            if (e.target === searchInput) return;

            var ids = getVisibleIds();
            if (ids.length === 0) return;

            var idx = selectedId ? ids.indexOf(selectedId) : -1;

            if (e.key === 'ArrowDown') {
                e.preventDefault();
                idx = idx < ids.length - 1 ? idx + 1 : idx;
                selectEntry(ids[idx]);
                var el = wordList.querySelector('.word-item.selected');
                if (el) el.scrollIntoView({ block: 'nearest' });
            } else if (e.key === 'ArrowUp') {
                e.preventDefault();
                idx = idx > 0 ? idx - 1 : 0;
                selectEntry(ids[idx]);
                var el = wordList.querySelector('.word-item.selected');
                if (el) el.scrollIntoView({ block: 'nearest' });
            }
        }

        // Debounce
        var filterTimer;
        function debouncedFilter() {
            clearTimeout(filterTimer);
            filterTimer = setTimeout(filterEntries, 150);
        }

        // Event listeners
        wordList.addEventListener('click', function(e) {
            var item = e.target.closest('.word-item');
            if (item) {
                selectEntry(parseInt(item.getAttribute('data-id')));
            }
        });

        letterBar.addEventListener('click', function(e) {
            var btn = e.target.closest('.letter-btn');
            if (btn && !btn.classList.contains('dimmed')) {
                scrollToLetter(btn.getAttribute('data-letter'));
            }
        });

        searchInput.addEventListener('input', debouncedFilter);
        posFilter.addEventListener('change', filterEntries);
        document.addEventListener('keydown', handleKeyDown);

        // Load data
        var json = { data: {{ data | tojson }} };
        allEntries = json.data.sort(function(a, b) {
            var ae = (a.entry || '').replace(/^-+/, '');
            var be = (b.entry || '').replace(/^-+/, '');
            return ae.localeCompare(be, 'pt');
        });

        buildLookups(allEntries);

        // Populate POS filter
        var posTypes = {};
        for (var i = 0; i < allEntries.length; i++) {
            if (allEntries[i].pos) posTypes[allEntries[i].pos] = true;
        }
        Object.keys(posTypes).sort().forEach(function(pos) {
            var opt = document.createElement('option');
            opt.value = pos;
            opt.textContent = posLabels[pos] || pos;
            posFilter.appendChild(opt);
        });

        // Check URL params
        var urlParams = new URLSearchParams(window.location.search);
        var initialSearch = urlParams.get('search');
        var initialEntry = urlParams.get('entry');

        if (initialSearch) {
            searchInput.value = initialSearch;
        }

        // Render initial list
        filterEntries();

        // Select initial entry
        if (initialEntry) {
            var entryId = parseInt(initialEntry);
            if (entriesById[entryId]) {
                selectEntry(entryId);
                // Scroll to the selected entry in word list
                setTimeout(function() {
                    var el = wordList.querySelector('.word-item.selected');
                    if (el) el.scrollIntoView({ block: 'center' });
                }, 100);
            }
        } else if (!initialSearch) {
            renderDetail(null);
        }

        searchInput.focus();
    })();
    </script>
{% endblock %}
