<!-- show search input box -->
<script lang="ts">
import { onMount, createEventDispatcher } from "svelte";
import { _ } from "svelte-i18n";
import type { WidgetBean } from "@indexea/sdk";
import type { SearchContext } from "@indexea/sdk/context";
import SimpleAutoComplete from "./SimpleAutocomplete.svelte";
import type { Indexea } from "../openapi";

const dispatch = createEventDispatcher();
const inputId = "idx_search_input";

export let indexea: Indexea;
export let widget: WidgetBean;
export let props: any;
export let context: SearchContext;
export let showLogo = true;
export let autoFocus = false;

onMount(() => {
    //@ts-ignore
    if (autoFocus) document.getElementById(inputId).focus();
});

function doSearch() {
    dispatch("search", context.q);
}

async function searchFunction(q: string) {
    return indexea.autocomplete(context.query, context.q, props.complete_count || 10).catch((e) => {
        console.error(e);
        return [];
    });
}

function onChange(e: any) {
    if (e) {
        if (e.url) {
            Object.assign(document.createElement("a"), {
                target: "_blank",
                rel: "noopener noreferrer",
                href: e.url,
            }).click();
        } else {
            doSearch();
        }
    }
}
</script>

<form class="d-flex align-items-center mb-3" on:submit|preventDefault={doSearch}>
    {#if showLogo && (props.logo == undefined || props.logo)}
        <div class="logo">
            <a href="/" on:click|preventDefault={(e) => dispatch("search")}>
                <img
                    src={widget.settings?.logo || "/static/logo.svg"}
                    class="me-4"
                    alt="logo"
                    height="28"
                />
            </a>
        </div>
    {/if}
    <div class="flex-grow-1">
        {#if !props.complete || props.complete === "none"}
            <input id={inputId} type="text" class="form-control" bind:value={context.q} />
        {:else}
            <SimpleAutoComplete
                {onChange}
                {searchFunction}
                {inputId}
                inputClassName="form-control"
                dropdownClassName="border shadow-sm"
                hideArrow={true}
                noInputStyles={true}
                showLoadingIndicator={true}
                localFiltering={false}
                placeholder={props.placeholder}
                bind:text={context.q}
                labelFieldName="value"
                valueFieldName="value"
            />
        {/if}
    </div>
    {#if props.button}
        <button type="submit" class="btn btn-primary ms-2">{$_("button")}</button>
    {/if}
</form>
