import { buildInstantResults, buildInteractiveInstantResult } from "@coveo/headless";
import { LitElement, html, nothing, render } from "lit";
import { customElement, property, state as decorators_js_state } from "lit/decorators.js";
import { keyed } from "lit/directives/keyed.js";
import { ResultTemplateProvider } from "../../common/item-list/result-template-provider.js";
import { getPartialInstantItemElement, getPartialInstantItemShowAllElement, renderInstantItemShowAllButton } from "../../common/suggestions/instant-item.js";
import { dispatchSearchBoxSuggestionsEvent } from "../../common/suggestions/suggestions-events.js";
import { errorGuard } from "../../../decorators/error-guard.js";
import { encodeForDomAttribute } from "../../../utils/string-utils.js";
function _ts_decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
    else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function _ts_metadata(k, v) {
    if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
}
class AtomicSearchBoxInstantResults extends LitElement {
    async setRenderFunction(resultRenderingFunction) {
        this.itemRenderingFunction = resultRenderingFunction;
    }
    connectedCallback() {
        super.connectedCallback();
        try {
            dispatchSearchBoxSuggestionsEvent((bindings)=>{
                this.bindings = bindings;
                return this.initialize();
            }, this, [
                'atomic-search-box'
            ]);
        } catch (error) {
            this.error = error;
        }
    }
    getLink(el) {
        const atomicResult = 'ATOMIC-RESULT' === el.tagName ? el : el?.querySelector('atomic-result');
        return atomicResult?.shadowRoot?.querySelector('atomic-result-link a:not([slot])') || null;
    }
    handleLinkClick(el, hasModifier) {
        const setTarget = (value)=>el.setAttribute('target', value);
        const initialTarget = el.getAttribute('target');
        hasModifier && setTarget('_blank');
        el.click();
        hasModifier && setTarget(initialTarget || '');
    }
    renderItems() {
        if (!this.bindings.suggestedQuery() || this.bindings.store.isMobile()) return [];
        const results = this.instantResults.state.results.length ? this.instantResults.state.results : this.results;
        const elements = results.map((result)=>{
            const partialItem = getPartialInstantItemElement(this.bindings.i18n, 'instant-results-suggestion-label', this.ariaLabelGenerator?.(this.bindings, result) || result.title, result.uniqueId);
            const key = `instant-result-${encodeForDomAttribute(result.uniqueId)}`;
            const template = html`${keyed(key, html`<atomic-result
            part="outline"
            .result=${result}
            .interactiveResult=${buildInteractiveInstantResult(this.bindings.engine, {
                options: {
                    result
                }
            })}
            .display=${this.display}
            .density=${this.density}
            .imageSize=${this.imageSize}
            .content=${this.itemTemplateProvider.getTemplateContent(result)}
            .renderingFunction=${this.itemRenderingFunction}
          ></atomic-result>`)}`;
            const container = document.createElement('div');
            render(template, container);
            const resultElement = container.firstElementChild;
            return {
                ...partialItem,
                content: resultElement,
                onSelect: (e)=>{
                    const link = this.getLink(e.target);
                    if (!link) return;
                    this.handleLinkClick(link, e.ctrlKey || e.metaKey);
                }
            };
        });
        if (elements.length) {
            const partialItem = getPartialInstantItemShowAllElement(this.bindings.i18n, 'show-all-results');
            elements.push({
                ...partialItem,
                content: renderInstantItemShowAllButton({
                    i18n: this.bindings.i18n,
                    i18nKey: 'show-all-results'
                }),
                onSelect: ()=>{
                    this.bindings.clearSuggestions();
                    this.bindings.searchBoxController.updateText(this.instantResults.state.q);
                    this.bindings.searchBoxController.submit();
                }
            });
        }
        return elements;
    }
    initialize() {
        this.instantResults = buildInstantResults(this.bindings.engine, {
            options: {
                maxResultsPerQuery: this.maxResultsPerQuery
            }
        });
        this.itemTemplateProvider = new ResultTemplateProvider({
            includeDefaultTemplate: true,
            templateElements: Array.from(this.querySelectorAll('atomic-result-template')),
            getResultTemplateRegistered: ()=>true,
            setResultTemplateRegistered: ()=>{},
            getTemplateHasError: ()=>this.templateHasError,
            setTemplateHasError: (value)=>{
                this.templateHasError = value;
            },
            bindings: this.bindings
        });
        return {
            position: Array.from(this.parentNode.children).indexOf(this),
            panel: 'right',
            onSuggestedQueryChange: (q)=>{
                this.instantResults.updateQuery(q);
                return this.onSuggestedQueryChange();
            },
            renderItems: ()=>this.renderItems()
        };
    }
    onSuggestedQueryChange() {
        if (!this.bindings.getSuggestionElements().length && !this.bindings.searchBoxController.state.value) console.warn("There doesn't seem to be any query suggestions configured. Make sure to include either an atomic-search-box-query-suggestions or atomic-search-box-recent-queries in your search box in order to see some instant results.");
        return new Promise((resolve)=>{
            const unsubscribe = this.instantResults.subscribe(()=>{
                const state = this.instantResults.state;
                if (!state.isLoading) {
                    if (state.results.length) this.results = state.results;
                    unsubscribe();
                    resolve();
                }
            });
        });
    }
    render() {
        return nothing;
    }
    constructor(...args){
        super(...args), this.results = [], this.display = 'list', this.templateHasError = false, this.maxResultsPerQuery = 4, this.density = 'normal', this.imageSize = 'icon';
    }
}
_ts_decorate([
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicSearchBoxInstantResults.prototype, "error", void 0);
_ts_decorate([
    decorators_js_state()
], AtomicSearchBoxInstantResults.prototype, "templateHasError", void 0);
_ts_decorate([
    property({
        attribute: 'max-results-per-query',
        reflect: true,
        type: Number
    })
], AtomicSearchBoxInstantResults.prototype, "maxResultsPerQuery", void 0);
_ts_decorate([
    property({
        reflect: true
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayDensity ? Object : ItemDisplayDensity)
], AtomicSearchBoxInstantResults.prototype, "density", void 0);
_ts_decorate([
    property({
        attribute: 'image-size',
        reflect: true
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayImageSize ? Object : ItemDisplayImageSize)
], AtomicSearchBoxInstantResults.prototype, "imageSize", void 0);
_ts_decorate([
    property({
        attribute: 'aria-label-generator'
    }),
    _ts_metadata("design:type", "u" < typeof AriaLabelGenerator ? Object : AriaLabelGenerator)
], AtomicSearchBoxInstantResults.prototype, "ariaLabelGenerator", void 0);
_ts_decorate([
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicSearchBoxInstantResults.prototype, "render", null);
AtomicSearchBoxInstantResults = _ts_decorate([
    customElement('atomic-search-box-instant-results')
], AtomicSearchBoxInstantResults);
export { AtomicSearchBoxInstantResults };
