import { buildRecentQueriesList } from "@coveo/headless/commerce";
import { LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { errorGuard } from "../../../decorators/error-guard.js";
import { AriaLiveRegionController } from "../../../utils/accessibility-utils.js";
import { SafeStorage, StorageItems } from "../../../utils/local-storage-utils.js";
import { once } from "../../../utils/utils.js";
import clock from "../../../images/clock.js";
import { getPartialRecentQueryClearElement, getPartialRecentQueryElement, renderRecentQuery, renderRecentQueryClear } from "../../common/suggestions/recent-queries.js";
import { dispatchSearchBoxSuggestionsEvent } from "../../common/suggestions/suggestions-events.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 AtomicCommerceSearchBoxRecentQueries extends LitElement {
    connectedCallback() {
        super.connectedCallback();
        try {
            dispatchSearchBoxSuggestionsEvent((bindings)=>{
                this.bindings = bindings;
                return this.initialize();
            }, this, [
                'atomic-commerce-search-box'
            ]);
        } catch (error) {
            this.error = error;
        }
    }
    initialize() {
        this.storage = new SafeStorage();
        this.recentQueriesList = buildRecentQueriesList(this.bindings.engine, {
            initialState: {
                queries: this.retrieveLocalStorage()
            },
            options: {
                maxLength: 1000,
                clearFilters: this.bindings.clearFilters
            }
        });
        this.recentQueriesList.subscribe(()=>this.updateLocalStorage());
        return {
            position: Array.from(this.parentNode.children).indexOf(this),
            renderItems: ()=>this.renderItems()
        };
    }
    retrieveLocalStorage() {
        return this.storage.getParsedJSON(StorageItems.RECENT_QUERIES, []);
    }
    updateLocalStorage() {
        if (!this.recentQueriesList.state.analyticsEnabled) return this.disableFeature();
        return this.storage.setJSON(StorageItems.RECENT_QUERIES, this.recentQueriesList.state.queries);
    }
    disableFeature() {
        this.warnUser();
        this.storage.removeItem(StorageItems.RECENT_QUERIES);
    }
    renderItems() {
        if (!this.recentQueriesList.state.analyticsEnabled) return [];
        const query = this.bindings.searchBoxController.state.value;
        const hasQuery = '' !== query;
        const max = hasQuery ? this.maxWithQuery : this.maxWithoutQuery;
        const filteredQueries = this.recentQueriesList.state.queries.filter((recentQuery)=>recentQuery.toLowerCase().startsWith(query.toLowerCase())).slice(0, max);
        const suggestionElements = filteredQueries.map((value)=>this.renderItem(value));
        if (suggestionElements.length) suggestionElements.unshift(this.renderClear());
        return suggestionElements;
    }
    renderClear() {
        const partialItem = getPartialRecentQueryClearElement(this.bindings.i18n);
        return {
            ...partialItem,
            content: renderRecentQueryClear({
                i18n: this.bindings.i18n
            }),
            onSelect: ()=>{
                this.recentQueriesList.clear();
                this.bindings.triggerSuggestions();
                this.searchBoxAriaMessage.message = this.bindings.i18n.t('recent-search-cleared');
            }
        };
    }
    renderItem(value) {
        const query = this.bindings.searchBoxController.state.value;
        const partialItem = getPartialRecentQueryElement(value, this.bindings.i18n);
        return {
            ...partialItem,
            content: renderRecentQuery({
                icon: this.icon || clock,
                query,
                value
            }),
            onSelect: ()=>{
                if (this.bindings.isStandalone) {
                    this.bindings.searchBoxController.updateText(value);
                    this.bindings.searchBoxController.submit();
                    return;
                }
                this.recentQueriesList.executeRecentQuery(this.recentQueriesList.state.queries.indexOf(value));
            }
        };
    }
    render() {
        return nothing;
    }
    constructor(...args){
        super(...args), this.maxWithQuery = 3, this.searchBoxAriaMessage = new AriaLiveRegionController(this, 'recent-search-cleared', true), this.warnUser = once(()=>this.bindings.engine.logger.warn('The recent queries feature is deactivated because analytics are disabled.'));
    }
}
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicCommerceSearchBoxRecentQueries.prototype, "error", void 0);
_ts_decorate([
    property(),
    _ts_metadata("design:type", String)
], AtomicCommerceSearchBoxRecentQueries.prototype, "icon", void 0);
_ts_decorate([
    property({
        type: Number,
        attribute: 'max-with-query',
        reflect: true
    })
], AtomicCommerceSearchBoxRecentQueries.prototype, "maxWithQuery", void 0);
_ts_decorate([
    property({
        type: Number,
        attribute: 'max-without-query',
        reflect: true
    }),
    _ts_metadata("design:type", Number)
], AtomicCommerceSearchBoxRecentQueries.prototype, "maxWithoutQuery", void 0);
_ts_decorate([
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceSearchBoxRecentQueries.prototype, "render", null);
AtomicCommerceSearchBoxRecentQueries = _ts_decorate([
    customElement('atomic-commerce-search-box-recent-queries')
], AtomicCommerceSearchBoxRecentQueries);
export { AtomicCommerceSearchBoxRecentQueries };
