{{- /* Footer custom content area start */ -}}
{{- /*     Insert any custom code web-analytics, resources, etc. here */ -}}
<div class="search-palette" id="search-command-palette" hidden>
    <div class="search-palette__backdrop" data-search-close></div>
    <section class="search-palette__panel" role="dialog" aria-modal="true" aria-labelledby="search-palette-title">
        <div class="search-palette__header">
            <div class="search-palette__title-group">
                <p class="search-palette__eyebrow">{{ cond (eq site.Language.Lang "zh") "快速搜索" "Quick Search" }}</p>
                <h2 id="search-palette-title">{{ cond (eq site.Language.Lang "zh") "查找博客中的文章、笔记与关键词" "Find posts, notes, and keywords" }}</h2>
            </div>
            <button type="button" class="search-palette__close" data-search-close aria-label="{{ cond (eq site.Language.Lang "zh") "关闭搜索" "Close search" }}">Esc</button>
        </div>
        <div class="search-palette__input-wrap">
            <svg class="search-palette__input-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                <circle cx="11" cy="11" r="8"></circle>
                <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
            </svg>
            <input
                id="search-palette-input"
                class="search-palette__input"
                type="search"
                autocomplete="off"
                spellcheck="false"
                placeholder="{{ cond (eq site.Language.Lang "zh") "输入标题、摘要或正文关键词" "Search by title, summary, or content" }}"
                aria-label="{{ cond (eq site.Language.Lang "zh") "站内搜索" "Site search" }}">
            <div class="search-palette__shortcut" aria-hidden="true">
                <kbd>&uarr;&darr;</kbd>
                <kbd>Enter</kbd>
            </div>
        </div>
        <div class="search-palette__meta">
            <span id="search-palette-status">{{ cond (eq site.Language.Lang "zh") "按 / 或 Cmd/Ctrl + K 打开" "Press / or Cmd/Ctrl + K to open" }}</span>
            <a href="{{ "search/" | relLangURL }}" class="search-palette__full-link">{{ cond (eq site.Language.Lang "zh") "打开完整搜索页" "Open full search page" }}</a>
        </div>
        <ul class="search-palette__results" id="search-palette-results" aria-live="polite"></ul>
    </section>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const palette = document.getElementById('search-command-palette');
        const input = document.getElementById('search-palette-input');
        const results = document.getElementById('search-palette-results');
        const status = document.getElementById('search-palette-status');
        const triggers = document.querySelectorAll('[data-search-trigger]');
        const closers = document.querySelectorAll('[data-search-close]');
        const searchIndexUrl = '{{ "index.json" | relLangURL }}';
        const fullSearchUrl = '{{ "search/" | relLangURL }}';
        const labels = {
            empty: '{{ cond (eq site.Language.Lang "zh") "输入至少 1 个关键词开始搜索" "Type at least one character to search" }}',
            loading: '{{ cond (eq site.Language.Lang "zh") "正在加载搜索索引..." "Loading search index..." }}',
            noResults: '{{ cond (eq site.Language.Lang "zh") "没有找到匹配内容" "No matching content found" }}',
            loadError: '{{ cond (eq site.Language.Lang "zh") "搜索暂时不可用，请打开完整搜索页" "Search is unavailable, open the full search page" }}',
            resultSuffix: '{{ cond (eq site.Language.Lang "zh") "条结果" "results" }}',
            openFull: '{{ cond (eq site.Language.Lang "zh") "打开完整搜索页" "Open full search page" }}'
        };

        if (!palette || !input || !results || !status) {
            return;
        }

        let pages = [];
        let searchReady = false;
        let loadingPromise = null;
        let activeIndex = -1;
        let currentMatches = [];
        let previousFocus = null;

        function escapeHtml(value) {
            return (value || '').replace(/[&<>"']/g, function (char) {
                return {
                    '&': '&amp;',
                    '<': '&lt;',
                    '>': '&gt;',
                    '"': '&quot;',
                    "'": '&#39;'
                }[char];
            });
        }

        function normalize(value) {
            return (value || '').toLowerCase();
        }

        function summarize(item) {
            return item.summary || item.content || '';
        }

        function buildPreview(text, query) {
            const safeText = (text || '').replace(/\s+/g, ' ').trim();
            if (!safeText) {
                return '';
            }
            const normalizedText = normalize(safeText);
            const normalizedQuery = normalize(query);
            const hit = normalizedText.indexOf(normalizedQuery);
            const start = hit > 40 ? hit - 40 : 0;
            const slice = safeText.slice(start, start + 120);
            return (start > 0 ? '...' : '') + slice + (safeText.length > start + 120 ? '...' : '');
        }

        function scoreItem(item, query) {
            const title = normalize(item.title);
            const summary = normalize(item.summary);
            const content = normalize(item.content);
            let score = 0;

            if (title.includes(query)) score += 12;
            if (summary.includes(query)) score += 6;
            if (content.includes(query)) score += 3;
            if (title.startsWith(query)) score += 5;

            return score;
        }

        function setActive(index) {
            const entries = results.querySelectorAll('.search-palette__result');
            entries.forEach(function (entry, entryIndex) {
                if (entryIndex === index) {
                    entry.classList.add('is-active');
                    entry.scrollIntoView({ block: 'nearest' });
                } else {
                    entry.classList.remove('is-active');
                }
            });
            activeIndex = index;
        }

        function renderResults(items, query) {
            currentMatches = items;
            results.innerHTML = '';
            activeIndex = -1;

            if (!query.trim()) {
                status.textContent = labels.empty;
                return;
            }

            if (!items.length) {
                status.textContent = labels.noResults;
                results.innerHTML = '<li class="search-palette__empty">' + labels.noResults + '</li>';
                return;
            }

            status.textContent = items.length + ' ' + labels.resultSuffix;

            items.forEach(function (item, index) {
                const preview = buildPreview(summarize(item), query);
                const li = document.createElement('li');
                li.className = 'search-palette__result' + (index === 0 ? ' is-active' : '');
                const dateStr = item.date ? new Date(item.date).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }) : '';
                li.innerHTML =
                    '<a class="search-palette__result-link" href="' + escapeHtml(item.permalink) + '">' +
                    '<span class="search-palette__result-title">' + escapeHtml(item.title || item.permalink) + '</span>' +
                    (preview ? '<span class="search-palette__result-preview">' + escapeHtml(preview) + '</span>' : '') +
                    (dateStr ? '<span class="search-palette__result-date">' + escapeHtml(dateStr) + '</span>' : '') +
                    '</a>';
                li.addEventListener('mouseenter', function () {
                    setActive(index);
                });
                results.appendChild(li);
            });

            setActive(0);
        }

        function performSearch(query) {
            const normalizedQuery = normalize(query.trim());
            if (!normalizedQuery) {
                renderResults([], '');
                return;
            }

            const matches = pages
                .map(function (item) {
                    return {
                        item: item,
                        score: scoreItem(item, normalizedQuery)
                    };
                })
                .filter(function (entry) {
                    return entry.score > 0;
                })
                .sort(function (left, right) {
                    return right.score - left.score;
                })
                .slice(0, 8)
                .map(function (entry) {
                    return entry.item;
                });

            renderResults(matches, normalizedQuery);
        }

        function ensureIndex() {
            if (searchReady) {
                return Promise.resolve(pages);
            }
            if (loadingPromise) {
                return loadingPromise;
            }

            status.textContent = labels.loading;
            loadingPromise = fetch(searchIndexUrl)
                .then(function (response) {
                    if (!response.ok) {
                        throw new Error('Failed to load search index');
                    }
                    return response.json();
                })
                .then(function (data) {
                    pages = Array.isArray(data) ? data : [];
                    searchReady = true;
                    status.textContent = labels.empty;
                    return pages;
                })
                .catch(function () {
                    status.innerHTML = labels.loadError + ' <a href="' + fullSearchUrl + '">' + labels.openFull + '</a>';
                    return [];
                });

            return loadingPromise;
        }

        function openPalette() {
            previousFocus = document.activeElement;
            palette.hidden = false;
            document.body.classList.add('search-palette-open');
            triggers.forEach(function (trigger) {
                trigger.setAttribute('aria-expanded', 'true');
            });
            ensureIndex().finally(function () {
                input.focus();
                input.select();
                if (input.value.trim()) {
                    performSearch(input.value);
                }
            });
        }

        function closePalette() {
            palette.hidden = true;
            document.body.classList.remove('search-palette-open');
            triggers.forEach(function (trigger) {
                trigger.setAttribute('aria-expanded', 'false');
            });
            if (previousFocus && typeof previousFocus.focus === 'function') {
                previousFocus.focus();
            }
        }

        function isTypingTarget(target) {
            return target && (
                target.tagName === 'INPUT' ||
                target.tagName === 'TEXTAREA' ||
                target.tagName === 'SELECT' ||
                target.isContentEditable
            );
        }

        triggers.forEach(function (trigger) {
            trigger.addEventListener('click', function () {
                openPalette();
            });
        });

        closers.forEach(function (closer) {
            closer.addEventListener('click', function () {
                closePalette();
            });
        });

        input.addEventListener('input', function () {
            performSearch(input.value);
        });

        results.addEventListener('click', function () {
            closePalette();
        });

        document.addEventListener('keydown', function (event) {
            const key = event.key.toLowerCase();
            const metaK = (event.metaKey || event.ctrlKey) && key === 'k';
            const slashOpen = event.key === '/' && !event.metaKey && !event.ctrlKey && !event.altKey;
            const isOpen = !palette.hidden;

            if (metaK) {
                event.preventDefault();
                if (isOpen) {
                    closePalette();
                } else {
                    openPalette();
                }
                return;
            }

            if (slashOpen && !isTypingTarget(event.target) && !isOpen) {
                event.preventDefault();
                openPalette();
                return;
            }

            if (!isOpen) {
                return;
            }

            if (event.key === 'Escape') {
                event.preventDefault();
                closePalette();
                return;
            }

            if (event.key === 'ArrowDown' && currentMatches.length) {
                event.preventDefault();
                setActive((activeIndex + 1) % currentMatches.length);
                return;
            }

            if (event.key === 'ArrowUp' && currentMatches.length) {
                event.preventDefault();
                setActive((activeIndex - 1 + currentMatches.length) % currentMatches.length);
                return;
            }

            if (event.key === 'Enter' && currentMatches.length && activeIndex >= 0) {
                const activeLink = results.querySelectorAll('.search-palette__result-link')[activeIndex];
                if (activeLink) {
                    window.location.href = activeLink.href;
                }
            }
        });
    });
</script>
{{- /* Footer custom content area end */ -}}
