import { h } from "@stencil/core";
import { state, onChange } from "./pn-marketweb-siteheader-search-store";
import { search } from "pn-design-assets/pn-assets/icons.js";
export class PnMarketwebSiteheaderSearch {
    constructor() {
        this.i18n = undefined;
        this.showOnlyLink = false;
        this.hideSearch = false;
        this.language = null;
        this.siteid = null;
        this.search = {};
        this.primary = false;
        this.icononly = true;
        this.autoCompleteOptions = [];
    }
    hostElement;
    onSearchValueUpdate() {
        this.getAutocomplete(state.searchValue);
    }
    async getAutocomplete(prefix) {
        if (!this.search.AutocompleteEndpoint || prefix.length < 2) {
            this.autoCompleteOptions = [];
            return;
        }
        if (state.autocompleteSuggestions[prefix]) {
            this.setAutocompleteSuggestions(state.autocompleteSuggestions[prefix]);
            return;
        }
        let autocompleteUrl = `${this.search.AutocompleteEndpoint}?prefix=${prefix}&size=10`;
        if (this.language || this.siteid) {
            autocompleteUrl += `&tags=`;
            if (this.language) {
                autocompleteUrl += `language:${this.language}`;
            }
            if (this.language && this.siteid) {
                autocompleteUrl += `,`;
            }
            if (this.siteid) {
                autocompleteUrl += `siteid:${this.siteid}`;
            }
        }
        const req = await fetch(autocompleteUrl, { signal: state.requestAbortController.signal }).catch(e => {
            console.warn('Unable to fetch autocomplete suggestions', e);
        });
        if (!req) {
            return;
        }
        const data = await req.json();
        if (!data || !data.hits || !data.hits.length) {
            return;
        }
        const suggestions = data.hits
            .filter(item => item.type === 'editorial')
            .map(item => {
            return item.query;
        });
        // Store query in store
        state.autocompleteSuggestions[prefix] = suggestions;
        this.setAutocompleteSuggestions(suggestions);
    }
    setAutocompleteSuggestions(suggestions) {
        if (typeof suggestions !== 'object' || typeof suggestions.length !== 'number' || suggestions.length === 0) {
            return;
        }
        this.autoCompleteOptions = suggestions;
    }
    componentWillLoad() {
        onChange('searchValue', () => {
            this.onSearchValueUpdate();
        });
    }
    componentDidRender() {
        const inputSearchElm = this.hostElement.querySelector('pn-search-field input:not([list])');
        if (inputSearchElm && this.search.AutocompleteEndpoint) {
            inputSearchElm.setAttribute('list', 'siteheader-search-autocomplete');
        }
    }
    render() {
        if (!this.search.formActionUrl || this.hideSearch) {
            return;
        }
        const autocompleteAttribute = this.search.AutocompleteEndpoint ? { list: 'siteheader-search-autocomplete' } : {};
        return (h("div", { class: "siteheader-search" }, this.showOnlyLink ? (h("pn-button", { href: this.search.formActionUrl, appearance: "light", icon: search, tooltip: this.i18n.searchlabel })) : (h("form", { method: "get", action: this.search.formActionUrl, role: "search" }, h("pn-search-field", { ...autocompleteAttribute, label: this.i18n.searchlabel, name: "q", button: this.icononly ? 'icon' : null, "button-label": 'Search', placeholder: this.i18n.searchplaceholder, onUpdate: (e) => {
                state.searchValue = e.detail;
            }, onSearch: () => {
                const form = this.hostElement.querySelector('form');
                if (form) {
                    form.submit();
                }
            } }), this.primary && this.search.AutocompleteEndpoint ? (h("datalist", { id: "siteheader-search-autocomplete" }, this.autoCompleteOptions.map(item => (h("option", null, item))))) : null))));
    }
    static get is() { return "pn-marketweb-siteheader-search"; }
    static get originalStyleUrls() {
        return {
            "$": ["pn-marketweb-siteheader-search.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["pn-marketweb-siteheader-search.css"]
        };
    }
    static get properties() {
        return {
            "i18n": {
                "type": "any",
                "mutable": false,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "i-1-8n",
                "reflect": false
            },
            "showOnlyLink": {
                "type": "boolean",
                "mutable": true,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "show-only-link",
                "reflect": false,
                "defaultValue": "false"
            },
            "hideSearch": {
                "type": "boolean",
                "mutable": true,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "hide-search",
                "reflect": false,
                "defaultValue": "false"
            },
            "language": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Specifies which language we want to show (sv,da,fi,no,en)"
                },
                "attribute": "language",
                "reflect": true,
                "defaultValue": "null"
            },
            "siteid": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Specifies the current site id (guid)"
                },
                "attribute": "siteid",
                "reflect": false,
                "defaultValue": "null"
            },
            "search": {
                "type": "unknown",
                "mutable": true,
                "complexType": {
                    "original": "SiteHeaderSearch",
                    "resolved": "SiteHeaderSearch",
                    "references": {
                        "SiteHeaderSearch": {
                            "location": "import",
                            "path": "./pn-marketweb-siteheader-types",
                            "id": "src/components/layout-components/pn-marketweb-siteheader/pn-marketweb-siteheader-types.ts::SiteHeaderSearch"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "defaultValue": "{}"
            },
            "primary": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "primary",
                "reflect": false,
                "defaultValue": "false"
            },
            "icononly": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "icononly",
                "reflect": false,
                "defaultValue": "true"
            }
        };
    }
    static get states() {
        return {
            "autoCompleteOptions": {}
        };
    }
    static get elementRef() { return "hostElement"; }
}
//# sourceMappingURL=pn-marketweb-siteheader-search.js.map
