{% load static %}
{% load i18n %}
<div class="modal fade" id="search-modal" tabindex="-1" aria-labelledby="search-modal-label" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-xl modal-fullscreen-md-down">
        <div class="modal-content">
            <div class="modal-header searchbar">
                <form class="d-flex align-items-center border border-2" action="{% url 'secrets.secret-list' %}" role="search"
                      method="GET">
                    <label id="search-modal-label" for="search-modal-input">
                        <i class="fa fa-search fa-fw text-body"></i>
                    </label>
                    <input id="search-modal-input" name="search" placeholder="{% trans "Search secrets..." %}"
                           type="text" class="form-control" value="{{ request.GET.search }}">

                    <span id="search-indicator" class="spinner-border spinner-border-sm align-middle"
                          role="status" aria-hidden="true" style="visibility: hidden"></span>
                </form>
            </div>
            <div class="modal-body" id="search-modal-results" style="display: none"></div>
            <div class="modal-footer justify-content-between" id="search-modal-footer" style="display: none">
                <div class="row g-0">
                    <div class="col-6 d-flex align-items-end">
                        <ul class="search-modal-actions d-flex d-lg-grid gap-lg-1 small">
                            <!-- Up, Down -->
                            <li>
                                <kbd class="rounded small p-1">
                                    <i class="fa fa-arrow-up fa-fw"></i>
                                </kbd>
                                <kbd class="rounded small p-1">
                                    <i class="fa fa-arrow-down fa-fw"></i>
                                </kbd>
                                <span class="mx-2 text-muted small">{% translate "Navigate" %}</span>
                            </li>

                            <!-- Escape -->
                            <li>
                                <kbd class="rounded small py-1 px-2">ESC</kbd>
                                <span class="mx-2 text-muted small">{% translate "Close" %}</span>
                            </li>
                        </ul>
                    </div>
                    <div class="col-6 text-end">
                        <div class="row">
                            <div class="col-12 small">
                                <span id="search-modal-result-count"></span>
                            </div>
                        </div>
                        <div class="row d-inline-block mt-1">
                            <div class="col-12">
                                <a id="search-modal-result-count-link" class="btn btn-accent btn-sm"
                                   href="{% url "secrets.secret-list" %}">
                                    {% translate "Show all" %}
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    document.getElementById('search-modal').addEventListener('shown.bs.modal', () => {
        const searchModalInput = document.getElementById('search-modal-input');
        searchModalInput.focus();
        if (searchModalInput.value) {
            const searchTermLen = searchModalInput.value.length;
            searchModalInput.setSelectionRange(searchTermLen, searchTermLen);
        }
    })
    document.addEventListener('keydown', (e) => {
        if (e.key === 'k' && (e.metaKey || e.ctrlKey)) {
            e.preventDefault()
            window.bootstrap.Modal.getOrCreateInstance('#search-modal').show()
        }
    })
</script>

<script>
    const autoCompleteTreshold = 3;
    const autoCompleteDebounce = 500;
    const searchModal = document.getElementById("search-modal")
    const searchIndicator = document.getElementById("search-indicator")
    const searchModalFooter = document.getElementById('search-modal-footer')
    const searchModalResults = document.getElementById("search-modal-results")
    const searchResultCountLink = document.getElementById('search-modal-result-count-link')
    const searchResultCountSpan = document.getElementById('search-modal-result-count')
    const autoCompleteJS = new window.autoCompleteJS({
        name: "secretSearchAutoComplete",
        data: {
            src: async (query) => {
                try {
                    const source = await fetch(`{% url 'secrets.secret-search' %}?q=${query}`);
                    this.originalData = await source.json();
                    return this.originalData.results
                } catch (error) {
                    return error;
                }
            },
            cache: false,
        },
        query: (input) => {
            return DOMPurify.sanitize(input)
        },
        selector: "#search-modal-input",
        threshold: autoCompleteTreshold,
        debounce: autoCompleteDebounce,
        searchEngine: (query, record) => {
            // since our API does the searching, deactivate matching
            return record
        },
        wrapper: false,
        resultsList: {
            class: "list-group px-2",
            destination: "#search-modal-results",
            position: "afterbegin",
            element: (list, data) => {
                if (data.results.length > 0) {
                    searchResultCountSpan.innerHTML = `Displaying <strong>${data.results.length}</strong> out of <strong>${this.originalData.count}</strong> results`;
                } else {
                    searchResultCountSpan.innerHTML = `Found <strong>${data.matches.length}</strong> matching results for <strong>"${DOMPurify.sanitize(data.query)}"</strong>`;
                }
                searchModalFooter.style.display = 'block'

                // Update search link
                let url = new URL(searchResultCountLink.href)
                url.searchParams.set('search', DOMPurify.sanitize(data.query))
                searchResultCountLink.href = url.href
            },
            maxResults: undefined,
            noResults: true,
            tag: "div",
        },
        resultItem: {
            class: "list-group-item list-group-item-action d-flex justify-content-between align-items-center py-3",
            element: (item, data) => {
                item.href = data.value.url;
                item.innerHTML = `{% include "secrets/search/_search_item.html" %}`;
                if (data.value.locked) {
                    item.querySelector('.search-modal-result-action').insertAdjacentHTML(
                        "afterbegin",
                        '<i class="fa fa-lock fa-fw text-danger"></i>',
                    )
                }
            },
            highlight: "autoComplete_highlight",
            selected: "autoComplete_selected",
            tag: "a",
        },
        submit: true,
        events: {
            input: {
                input: (event) => {
                    setTimeout(() => {
                        autoCompleteJS.start();
                        if (event.target.value.length >= autoCompleteTreshold) {
                            searchIndicator.style.visibility = 'visible';
                        }
                    }, autoCompleteDebounce)
                },
                close: () => {
                    searchModalResults.style.display = 'none';
                    searchModalFooter.style.display = 'none';
                },
                selection: (event) => {
                    autoCompleteJS.input.blur();
                    bootstrap.Modal.getInstance('#search-modal').hide()
                    const feedback = event.detail;
                    window.location.replace(feedback.selection.value['url'])
                },
                blur: (event) => {
                    /* Don't hide results after focus loss */
                    event.preventDefault()
                },
                response: () => {
                    searchIndicator.style.visibility = 'hidden'
                },
                results: () => {
                    searchModalResults.style.display = 'block'
                },
                navigate: (event) => {
                    let el = searchModalResults.querySelector(`#autoComplete_result_${event.detail.selection.index}`)
                    teamvault.scrollIfNeeded(el, searchModalResults)
                }
            },
        }
    })
</script>
