import { buildSearchBox, loadInsightSearchActions } from "@coveo/headless/insight";
import { LitElement, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { classMap } from "lit/directives/class-map.js";
import { createRef, ref } from "lit/directives/ref.js";
import { renderSearchBoxWrapper } from "../../common/search-box/search-box-wrapper.js";
import { renderSearchBoxTextArea } from "../../common/search-box/search-text-area.js";
import { getPartialSearchBoxSuggestionElement, renderQuerySuggestion } from "../../common/suggestions/query-suggestions.js";
import { SuggestionManager } from "../../common/suggestions/suggestion-manager.js";
import { elementHasQuery } from "../../common/suggestions/suggestions-utils.js";
import { bindStateToController } from "../../../decorators/bind-state.js";
import { bindings } from "../../../decorators/bindings.js";
import { errorGuard } from "../../../decorators/error-guard.js";
import { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import { AriaLiveRegionController } from "../../../utils/accessibility-utils.js";
import { hasKeyboard, isMacOS } from "../../../utils/device-utils.js";
import { isFocusingOut, randomID } from "../../../utils/utils.js";
import search_slim from "../../../images/search-slim.js";
import "../../common/atomic-icon/atomic-icon.js";
import { bindingGuard } from "../../../decorators/binding-guard.js";
import atomic_insight_search_box_tw_css from "./atomic-insight-search-box.tw.css.js";
import "@coveo/atomic-legacy/atomic-suggestion-renderer";
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 AtomicInsightSearchBox extends LitElement {
    initialize() {
        this.searchBoxId = randomID('atomic-search-box-');
        const searchBoxOptions = {
            id: this.searchBoxId,
            numberOfSuggestions: 0,
            highlightOptions: {
                notMatchDelimiters: {
                    open: '<span class="font-bold">',
                    close: '</span>'
                },
                correctionDelimiters: {
                    open: '<span class="font-normal">',
                    close: '</span>'
                }
            }
        };
        const { fetchQuerySuggestions, registerQuerySuggest } = loadInsightSearchActions(this.bindings.engine);
        this.searchBox = buildSearchBox(this.bindings.engine, {
            options: searchBoxOptions
        });
        this.bindings.engine.dispatch(registerQuerySuggest({
            id: this.searchBoxId,
            count: this.numberOfSuggestions
        }));
        this.suggestionManager = new SuggestionManager({
            getNumberOfSuggestionsToDisplay: ()=>this.numberOfSuggestions,
            updateQuery: (query)=>this.searchBox.updateText(query),
            getSearchBoxValue: ()=>this.searchBoxState.value,
            getSuggestionTimeout: ()=>500,
            getSuggestionDelay: ()=>0,
            getHost: ()=>this,
            getLogger: ()=>this.bindings.engine.logger
        });
        this.suggestionManager.registerSuggestions({
            position: 0,
            renderItems: ()=>this.searchBox.state.suggestions.map((suggestion)=>this.renderSuggestionItem(suggestion)),
            onInput: ()=>this.bindings.engine.dispatch(fetchQuerySuggestions({
                    id: this.searchBoxId
                })),
            panel: 'left'
        });
    }
    onSubmit() {
        if (this.suggestionManager.activeDescendantElement) return void this.suggestionManager.clickOnActiveElement();
        this.searchBox.submit();
        this.suggestionManager.clearSuggestions();
    }
    async onKeyDown(e) {
        if (this.disableSearch) return;
        switch(e.key){
            case 'Enter':
                if (!e.shiftKey) this.onSubmit();
                break;
            case 'Escape':
                this.suggestionManager.clearSuggestions();
                break;
            case 'ArrowDown':
                e.preventDefault();
                await this.suggestionManager.focusNextValue();
                this.announceNewActiveSuggestionToScreenReader();
                break;
            case 'ArrowUp':
                e.preventDefault();
                await this.suggestionManager.focusPreviousValue();
                this.announceNewActiveSuggestionToScreenReader();
                break;
            case 'Tab':
                this.suggestionManager.clearSuggestions();
                break;
        }
    }
    triggerTextAreaChange(value) {
        if (!this.textAreaRef.value) return;
        this.textAreaRef.value.value = value;
        this.textAreaRef.value.dispatchEvent(new window.Event('change'));
    }
    renderSuggestion(item, index, lastIndex) {
        const id = `${this.searchBoxId}-suggestion-${item.key}`;
        const isSelected = id === this.suggestionManager.activeDescendant || this.suggestionManager.suggestedQuery === item.query;
        if (index === lastIndex && item.hideIfLast) return nothing;
        return html`<atomic-suggestion-renderer
      .i18n=${this.bindings.i18n}
      .id=${id}
      .suggestion=${item}
      .isSelected=${isSelected}
      .side=${'left'}
      .index=${index}
      .lastIndex=${lastIndex}
      .isDoubleList=${false}
      @click=${(e)=>{
            this.suggestionManager.onSuggestionClick(item, e);
        }}
      @mouseenter=${()=>{
            this.suggestionManager.onSuggestionMouseOver(item, 'left', id);
        }}
    ></atomic-suggestion-renderer>`;
    }
    renderSuggestionItem(suggestion) {
        const hasQuery = '' !== this.searchBox.state.value;
        const partialItem = getPartialSearchBoxSuggestionElement(suggestion, this.bindings.i18n);
        return {
            ...partialItem,
            content: renderQuerySuggestion({
                icon: search_slim,
                hasQuery,
                suggestion,
                hasMultipleKindOfSuggestions: false,
                alwaysShowIcon: this.searchBoxState.suggestions.length > 1
            }),
            onSelect: ()=>{
                this.searchBox.selectSuggestion(suggestion.rawValue);
            }
        };
    }
    renderPanel(elements, setRef, getRef) {
        if (!elements.length) return nothing;
        return html`<div
      part="suggestions"
      ${ref(setRef)}
      class="flex grow basis-1/2 flex-col"
      @mousedown=${(e)=>{
            if (e.target === getRef()) e.preventDefault();
        }}
    >
      ${elements.map((suggestion, index)=>this.renderSuggestion(suggestion, index, elements.length - 1))}
    </div>`;
    }
    renderSuggestions() {
        if (!this.suggestionManager.hasSuggestions) {
            this.suggestionManager.updateActiveDescendant();
            return nothing;
        }
        const isVisible = this.suggestionManager.hasSuggestions && this.isExpanded;
        const classes = {
            'bg-background border-neutral absolute top-full left-0 z-10 flex w-full rounded-md border': true,
            hidden: !isVisible
        };
        return html`<div
      id="${this.searchBoxId}-popup"
      part="suggestions-wrapper"
      class=${classMap(classes)}
      role="application"
      aria-label=${this.bindings.i18n.t('search-suggestions-single-list')}
      aria-activedescendant=${this.suggestionManager.activeDescendant}
    >
      ${this.renderPanel(this.suggestionManager.allSuggestionElements, (el)=>{
            this.suggestionManager.leftPanel = el;
        }, ()=>this.suggestionManager.leftPanel)}
    </div>`;
    }
    getSearchInputLabel() {
        if (isMacOS()) return this.bindings.i18n.t('search-box-with-suggestions-macos');
        if (!hasKeyboard()) return this.bindings.i18n.t('search-box-with-suggestions-keyboardless');
        return this.bindings.i18n.t('search-box-with-suggestions');
    }
    async onFocus() {
        if (this.isExpanded) return;
        this.isExpanded = true;
        await this.suggestionManager.triggerSuggestions();
        this.announceNewSuggestionsToScreenReader();
    }
    async onInput(value) {
        this.searchBox.updateText(value);
        this.isExpanded = true;
        await this.suggestionManager.triggerSuggestions();
        this.announceNewSuggestionsToScreenReader();
    }
    announceNewActiveSuggestionToScreenReader() {
        const ariaLabel = this.suggestionManager.activeDescendantElement?.ariaLabel;
        if (isMacOS() && ariaLabel) this.suggestionsAriaMessage.message = ariaLabel;
    }
    announceNewSuggestionsToScreenReader() {
        const numberOfSuggestionsToAnnounce = this.suggestionManager.allSuggestionElements.filter(elementHasQuery).length;
        this.searchBoxAriaMessage.message = numberOfSuggestionsToAnnounce ? this.bindings.i18n.t(this.searchBoxState.value ? 'query-suggestions-available' : 'query-suggestions-available-no-query', {
            count: numberOfSuggestionsToAnnounce,
            query: this.searchBoxState.value
        }) : this.bindings.i18n.t('query-suggestions-unavailable');
    }
    render() {
        return html`${renderSearchBoxWrapper({
            props: {
                disabled: this.disableSearch,
                onFocusout: (event)=>{
                    if (!isFocusingOut(event)) return;
                    this.suggestionManager.clearSuggestions();
                    this.isExpanded = false;
                }
            }
        })(html`
      <atomic-icon
        part="submit-icon"
        .icon=${search_slim}
        class="my-auto mr-0 ml-4 h-4 w-4"
      ></atomic-icon>
      ${renderSearchBoxTextArea({
            props: {
                textAreaRef: this.textAreaRef,
                loading: this.searchBoxState.isLoading,
                i18n: this.bindings.i18n,
                value: this.searchBoxState.value,
                ariaLabel: this.getSearchInputLabel(),
                title: this.bindings.i18n.t('search'),
                onClear: ()=>{
                    this.searchBox.clear();
                    this.triggerTextAreaChange('');
                },
                popup: {
                    id: `${this.searchBoxId}-popup`,
                    activeDescendant: this.suggestionManager.activeDescendant || '',
                    expanded: this.isExpanded && this.suggestionManager.hasSuggestions,
                    hasSuggestions: this.suggestionManager.hasSuggestions
                },
                onInput: (e)=>this.onInput(e.target.value),
                onFocus: ()=>this.onFocus(),
                onKeyDown: (e)=>this.onKeyDown(e)
            }
        })}
      ${this.renderSuggestions()}
    `)}`;
    }
    constructor(...args){
        super(...args), this.isExpanded = false, this.disableSearch = false, this.numberOfSuggestions = 5, this.textAreaRef = createRef(), this.searchBoxAriaMessage = new AriaLiveRegionController(this, 'search-box'), this.suggestionsAriaMessage = new AriaLiveRegionController(this, 'search-suggestions', true);
    }
}
AtomicInsightSearchBox.shadowRootOptions = {
    ...LitElement.shadowRootOptions,
    delegatesFocus: true
};
AtomicInsightSearchBox.styles = atomic_insight_search_box_tw_css;
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof InsightBindings ? Object : InsightBindings)
], AtomicInsightSearchBox.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicInsightSearchBox.prototype, "error", void 0);
_ts_decorate([
    bindStateToController('searchBox'),
    state(),
    _ts_metadata("design:type", "u" < typeof InsightSearchBoxState ? Object : InsightSearchBoxState)
], AtomicInsightSearchBox.prototype, "searchBoxState", void 0);
_ts_decorate([
    state()
], AtomicInsightSearchBox.prototype, "isExpanded", void 0);
_ts_decorate([
    property({
        type: Boolean,
        reflect: true,
        attribute: 'disable-search'
    })
], AtomicInsightSearchBox.prototype, "disableSearch", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'number-of-suggestions'
    })
], AtomicInsightSearchBox.prototype, "numberOfSuggestions", void 0);
_ts_decorate([
    errorGuard(),
    bindingGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicInsightSearchBox.prototype, "render", null);
AtomicInsightSearchBox = _ts_decorate([
    customElement('atomic-insight-search-box'),
    bindings(),
    withTailwindStyles
], AtomicInsightSearchBox);
export { AtomicInsightSearchBox };
