/*!
 * Crafted with ❤ by Salla
 */
import { proxyCustomElement, HTMLElement, h } from '@stencil/core/internal/client';
import { S as Search } from './search.js';
import { H as Helper } from './Helper.js';
import { d as defineCustomElement$4 } from './salla-button2.js';
import { d as defineCustomElement$3 } from './salla-loading2.js';
import { d as defineCustomElement$2 } from './salla-modal2.js';

const sallaSearchCss = ".s-search-placeholder-wrapper{position:relative;display:inline-block}.s-search-input-wrapper{position:relative}.s-search-placeholder-trigger{cursor:pointer;appearance:none;text-align:start}";

const SallaSearch$1 = /*@__PURE__*/ proxyCustomElement(class SallaSearch extends HTMLElement {
    constructor() {
        super();
        this.__registerHost();
        this.inputValue = '';
        this.translationLoaded = false;
        this.loading = false;
        this.typing = false;
        this.debounce = setTimeout(() => '', 1000);
        /**
         * Set the component to display as a placeholder (button) that will open the modal. Defaults to `false`
         */
        this.placeholder = false;
        /**
         * Set the component display without modal window. Defaults to `false`
         */
        this.inline = false;
        /**
         * Adds a border radius to the input. Half of the height.
         */
        this.oval = false;
        /**
         * Sets the height of the input
         */
        this.height = 60;
        /**
         * Maximum number of words allowed in the input
         */
        this.maxWords = 5;
        /**
         * Show submit action buttons at the end.
         */
        this.showAction = false;
        this.productSlot =
            this.host.querySelector('[slot="product"]')?.innerHTML || this.getDefaultProductSlot();
        salla.event.on('search::open', () => this.open());
        salla.lang.onLoaded(() => {
            this.translationLoaded = true;
        });
        salla.event.on('modalClosed', () => this.onModalClose());
    }
    async open() {
        if (!this.inline) {
            await this.modal.open().then(() => setTimeout(() => this.searchInput.focus(), 300));
        }
    }
    onModalClose() {
        this.searchInput.value = '';
        this.results = undefined;
        this.afterSearching();
        this.container.classList.remove('s-search-no-results');
    }
    handleKeyDown(ev) {
        if (ev.key === 'Enter' && this.search_term?.length) {
            window.location.href = salla.url.get('search?q=' + encodeURI(this.search_term));
        }
    }
    getDefaultProductSlot() {
        return ('<div class="s-search-product-image-container">' +
            '  <img class="s-search-product-image" src="{image}" alt="{name}"/>' +
            '</div>' +
            '<div class="s-search-product-details">' +
            '  <div class="s-search-product-title">{name}</div> <div class="s-search-product-price">{price} <span class="s-search-product-regular-price">{regular_price}</span></div>' +
            '</div>');
    }
    debounceSearch(event) {
        this.typing = true;
        clearTimeout(this.debounce);
        this.debounce = setTimeout(() => {
            this.typing = false;
            this.search_term = event.target.value;
        }, 700);
    }
    limitWordsAndSearch(event) {
        let value = event.target.value;
        const words = value.trim().split(/\s+/);
        if (words.length > this.maxWords) {
            const truncatedInput = words.slice(0, this.maxWords).join(' ');
            this.searchInput.value = truncatedInput;
        }
        this.debounceSearch(event);
    }
    getQueryParam(param) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(param);
    }
    handleActionClick() {
        if (!!this.search_term && this.search_term.length > 2) {
            return this.search(this.search_term);
        }
    }
    handleSearch(val) {
        this.inputValue = val;
        if (val.length > 2) {
            this.search(val);
        }
        else {
            this.results = undefined;
            this.afterSearching();
        }
    }
    search(val) {
        this.noResults.style.display = 'none';
        //run loading spinner or stop it
        this.loading = true;
        salla.product
            .fetch({ source: 'search', source_value: val })
            .then(response => {
            this.results = response;
            salla.event.emit('Products Searched', val);
        })
            .catch(err => (err !== 'Query is same as previous one!' ? (this.results = undefined) : null))
            .finally(() => this.afterSearching(/*isEmpty*/ false));
    }
    afterSearching(isEmpty = true) {
        this.noResults.style.display = isEmpty || this.results?.data.length > 0 ? 'none' : 'block';
        Helper.toggleElementClassIf(this.container, 's-search-container-open', 's-search-no-results', () => this.results?.data.length);
        this.loading = false;
        salla.product.api.previousQuery = ''; //avoid having error 'Query is same as previous one!' after reopen modal;
        this.inputValue.length < 3 ? this.container.classList.remove('s-search-no-results') : '';
    }
    render() {
        const searchContent = (h("div", { key: '6d47849faffad8faa82bfb8368ea2ad9e2aced49', class: { 's-search-container': true, 's-search-inline': this.inline }, ref: container => (this.container = container) }, h("div", { key: '6c6330e985c6505b1cf8c78e5ab95cb3b22844c9', class: "s-search-input-wrapper" }, h("span", { key: 'e01360120e50a316881569d19e455ccb998e50ab', class: "s-search-icon-wrap" }, h("span", { key: 'f9d9e717638271402ba445d59ec8b5315d542a16', class: "s-search-icon", innerHTML: this.loading ? '<i class="s-search-spinner-loader"/>' : Search })), h("input", { key: '4abd6b3c6647ccfd411463aa2c9610c8428efd17', type: "search", enterkeyhint: "search", autocomplete: "off", class: "s-search-input", placeholder: salla.lang.get('blocks.header.search_placeholder'), onInput: (e) => this.limitWordsAndSearch(e), onKeyDown: e => this.handleKeyDown(e), ref: input => (this.searchInput = input), style: {
                height: this.height + 'px',
                borderRadius: this.oval ? this.height / 2 + 'px' : '',
            } }), this.showAction ? (h("salla-button", { loading: this.loading, class: { 's-search-action': true, 's-search-action-oval': this.oval }, onClick: () => this.handleActionClick() }, !this.loading && h("span", { innerHTML: Search }))) : null), h("div", { key: '1a28e1cef5a6785ed45cef1beb1e177c174aca0c', class: "s-search-results" }, this.results?.data.map(product => (h("a", { href: product.url + '?from=search-bar', class: {
                's-search-product': true,
                's-search-product-not-available': !product.is_available,
            }, innerHTML: this.productSlot
                .replace(/\{name\}/g, product.name)
                .replace(/\{price\}/g, product.price ? salla.money(product.price) : '')
                .replace(/\{regular_price\}/g, product.is_on_sale && product.regular_price
                ? salla.money(product.regular_price)
                : '')
                .replace(/\{image\}/g, product.image.url) }))), h("p", { key: 'df6eb433971ec24b64de09de7f5d861fe7d26c7e', ref: el => (this.noResults = el), class: "s-search-no-results-placeholder" }, salla.lang.get('common.elements.no_options')))));
        const modalContent = (h("salla-modal", { key: '37af042080e667919d94197c9ac16496a716bc9e', position: "top", class: "s-search-modal", ref: modal => (this.modal = modal) }, searchContent));
        const placeholderContent = (h("div", { key: 'ce1fa4591a9c61563344a8bc48ed3e09d1ad6796', class: "s-search-placeholder-wrapper s-search-inline" }, h("div", { key: 'f42ee11b614068bcbde12e6e82034b8b3b22bfaa', class: "s-search-input-wrapper" }, h("span", { key: '8b775e814e03a3de5c24bbe4e252e3e78fa82988', class: "s-search-icon-wrap" }, h("span", { key: '69cfca5e26fe366e2544e95e9b468aba28b32e55', class: "s-search-icon", innerHTML: Search })), h("button", { key: '998a6aa2efd5003e413d7d467ca4e78b0f97bbe1', type: "button", class: "s-search-input s-search-placeholder-trigger", onClick: () => this.open(), style: {
                height: this.height + 'px',
                borderRadius: this.oval ? this.height / 2 + 'px' : '',
            } }, salla.lang.get('blocks.header.search_placeholder'))), modalContent));
        return this.placeholder ? (placeholderContent) : this.inline ? (h("div", { class: "s-search-modal" }, searchContent)) : (modalContent);
    }
    /**
     * Run it one time after load
     */
    componentDidLoad() {
        this.afterSearching();
        this.searchInput.value = this.getQueryParam('q');
    }
    get host() { return this; }
    static get watchers() { return {
        "search_term": ["handleSearch"]
    }; }
    static get style() { return sallaSearchCss; }
}, [0, "salla-search", {
        "placeholder": [4],
        "inline": [4],
        "oval": [4],
        "height": [2],
        "maxWords": [2, "max-words"],
        "showAction": [4, "show-action"],
        "translationLoaded": [32],
        "results": [32],
        "loading": [32],
        "typing": [32],
        "debounce": [32],
        "search_term": [32]
    }, [[0, "keydown", "handleKeyDown"]], {
        "search_term": ["handleSearch"]
    }]);
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["salla-search", "salla-button", "salla-loading", "salla-modal"];
    components.forEach(tagName => { switch (tagName) {
        case "salla-search":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, SallaSearch$1);
            }
            break;
        case "salla-button":
            if (!customElements.get(tagName)) {
                defineCustomElement$4();
            }
            break;
        case "salla-loading":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "salla-modal":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
    } });
}
defineCustomElement$1();

const SallaSearch = SallaSearch$1;
const defineCustomElement = defineCustomElement$1;

export { SallaSearch, defineCustomElement };
