<script>
    autocomplete({
        container: '#autocomplete',
        initialState: {
            query: "{{ query }}",
        },
        getSources({ query }) {
            return [
                {
                    sourceId: 'tags-autocomplete',
                    getItems() {
                        return invoke("autocomplete_tags", { query: query })
                            .then((data) => {
                                return data.map((item) => {
                                    return {
                                        ...item,
                                        suggestion: item.suggestion,
                                        media_count: item.media_count,
                                        _highlightResult: {
                                            highlighted_suggestion: {
                                                value: item.highlighted_suggestion
                                                    .replace(/<mark>/g, '__aa-highlight__')
                                                    .replace(/<\/mark>/g, '__/aa-highlight__')
                                            },
                                        },
                                    };
                                });
                            });
                    },
                    onSelect({ item }) {
                        window.location.href = '/search?q=' + item.suggestion + '&p=1';
                    },
                    getItemUrl({ item }) {
                        return '/search?q=' + item.suggestion + '&p=1';
                    },
                    getItemInputValue: ({ item }) => item.suggestion,
                    templates: {
                        item({ item, components, html }) {
                            return html`<div class="aa-ItemContent">
                                <div class="aa-ItemContentTitle">
                                    ${components.Highlight({ hit: item, attribute: 'highlighted_suggestion' })}
                                </div>
                                <div class="aa-ItemContentDescription">
                                    <span class="float-right">${item.media_count}</span>
                                </div>
                            </div>`;
                        },
                    },
                },
            ];
        },
        onSubmit({ state }) {
            if (state.query) {
                window.location.href = '/search?q=' + encodeURIComponent(state.query) + '&p=1';
            }
        },
    });
</script>