import { EcommerceDefaultFieldsToInclude, VERSION, buildSearchEngine, buildSearchStatus, buildUrlManager, loadConfigurationActions, loadFieldActions, loadQueryActions, loadSearchConfigurationActions } from "@coveo/headless";
import { provide } from "@lit/context";
import i18next from "i18next";
import { LitElement, css, html } from "lit";
import { customElement, property, query, state } from "lit/decorators.js";
import { when } from "lit/directives/when.js";
import { bindingsContext } from "../../common/context/bindings-context.js";
import { InterfaceController } from "../../common/interface/interface-controller.js";
import { MobileBreakpointController } from "../../common/layout/mobile-breakpoint-controller.js";
import { errorSelector, firstSearchExecutedSelector, noResultsSelector } from "../atomic-search-layout/search-layout.js";
import { booleanConverter } from "../../../converters/boolean-converter.js";
import { errorGuard } from "../../../decorators/error-guard.js";
import { watch } from "../../../decorators/watch.js";
import { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import { ChildrenUpdateCompleteMixin } from "../../../mixins/children-update-complete-mixin.js";
import { markParentAsReady } from "../../../utils/init-queue.js";
import { waitForAtomicChildrenToBeDefined } from "../../../utils/initialization-common-utils.js";
import { SafeStorage, StorageItems } from "../../../utils/local-storage-utils.js";
import "../atomic-relevance-inspector/atomic-relevance-inspector.js";
import { augmentAnalyticsConfigWithAtomicVersion } from "../../common/interface/analytics-config.js";
import { arrayConverter } from "../../../converters/array-converter.js";
import { getAnalyticsConfig } from "./analytics-config.js";
import { createSearchStore } from "./store.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);
}
const FirstSearchExecutedFlag = 'firstSearchExecuted';
class AtomicSearchInterface extends ChildrenUpdateCompleteMixin(LitElement) {
    connectedCallback() {
        super.connectedCallback();
        this.store.setLoadingFlag(FirstSearchExecutedFlag);
        this.initFieldsToInclude();
        this.addEventListener('atomic/initializeComponent', this.handleInitialization);
        this.addEventListener('atomic/scrollToTop', this.scrollToTop);
    }
    willUpdate(changedProperties) {
        super.willUpdate(changedProperties);
        if (changedProperties.has('fieldsToInclude')) this.updateFieldsToInclude();
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        if ('function' == typeof this.unsubscribeUrlManager) this.unsubscribeUrlManager();
        if ('function' == typeof this.unsubscribeSearchStatus) this.unsubscribeSearchStatus();
        window.removeEventListener('hashchange', this.onHashChange);
        this.removeEventListener('atomic/initializeComponent', this.handleInitialization);
        this.removeEventListener('atomic/scrollToTop', this.scrollToTop);
    }
    scrollToTop() {
        const scrollContainerElement = document.querySelector(this.scrollContainer);
        if (!scrollContainerElement) return void this.bindings.engine.logger.warn(`Could not find the scroll container with the selector "${this.scrollContainer}". This will prevent UX interactions that require a scroll from working correctly. Please review the CSS selector in the scrollContainer option`);
        scrollContainerElement.scrollIntoView({
            behavior: 'smooth'
        });
    }
    closeRelevanceInspector() {
        if (this.relevanceInspector) this.relevanceInspector.open = false;
    }
    initialize(options) {
        return this.internalInitialization(()=>this.initEngine(options));
    }
    initializeWithSearchEngine(engine) {
        if (this.pipeline && this.pipeline !== engine.state.pipeline) console.warn('Mismatch between search interface pipeline and engine pipeline. The engine pipeline will be used.');
        if (this.searchHub && this.searchHub !== engine.state.searchHub) console.warn('Mismatch between search interface search hub and engine search hub. The engine search hub will be used.');
        engine.dispatch(loadConfigurationActions(engine).updateAnalyticsConfiguration({
            ...augmentAnalyticsConfigWithAtomicVersion()
        }));
        return this.internalInitialization(()=>{
            this.engine = engine;
        });
    }
    async executeFirstSearch() {
        if (!this.interfaceController.engineIsCreated(this.engine)) return;
        if (!this.initialized) return void console.error('You have to wait until the "initialize" promise is fulfilled before executing a search.', this);
        const safeStorage = new SafeStorage();
        const standaloneSearchBoxData = safeStorage.getParsedJSON(StorageItems.STANDALONE_SEARCH_BOX_DATA, null);
        if (!standaloneSearchBoxData) return void this.engine.executeFirstSearch();
        safeStorage.removeItem(StorageItems.STANDALONE_SEARCH_BOX_DATA);
        const { updateQuery } = loadQueryActions(this.engine);
        const { value, enableQuerySyntax, analytics } = standaloneSearchBoxData;
        this.engine.dispatch(updateQuery({
            q: value,
            enableQuerySyntax
        }));
        this.engine.executeFirstSearchAfterStandaloneSearchBoxRedirect(analytics);
    }
    updateSearchConfiguration(updatedProp, newValue) {
        if (!this.interfaceController.engineIsCreated(this.engine)) return;
        if (this.engine.state[updatedProp] === newValue) return;
        const { updateSearchConfiguration } = loadSearchConfigurationActions(this.engine);
        this.engine.dispatch(updateSearchConfiguration({
            [updatedProp]: newValue
        }));
    }
    registerFieldsToInclude() {
        this.engine?.dispatch(loadFieldActions(this.engine).registerFieldsToInclude(this.store.state.fieldsToInclude));
    }
    updateSearchHub() {
        this.updateSearchConfiguration('searchHub', this.searchHub ?? 'default');
    }
    updatePipeline() {
        this.updateSearchConfiguration('pipeline', this.pipeline);
    }
    toggleAnalytics() {
        if (!this.interfaceController.engineIsCreated(this.engine)) return;
        this.interfaceController.onAnalyticsChange();
    }
    updateLanguage() {
        if (!this.interfaceController.engineIsCreated(this.engine) || !this.language) return;
        const { updateSearchConfiguration } = loadSearchConfigurationActions(this.engine);
        this.engine.dispatch(updateSearchConfiguration({
            locale: this.language
        }));
        return this.interfaceController.onLanguageChange();
    }
    updateIconAssetsPath() {
        this.store.state.iconAssetsPath = this.iconAssetsPath;
    }
    render() {
        return html`
      ${when(this.bindings?.engine && this.enableRelevanceInspector && !this.disableRelevanceInspector, ()=>html`<atomic-relevance-inspector></atomic-relevance-inspector>`)}
      <slot></slot>
    `;
    }
    getBindings() {
        return {
            engine: this.engine,
            i18n: this.i18n,
            store: this.store,
            interfaceElement: this,
            createStyleElement: ()=>{
                const styleTag = document.createElement('style');
                return styleTag;
            },
            createScriptElement: ()=>{
                const scriptTag = document.createElement("script");
                return scriptTag;
            }
        };
    }
    initFieldsToInclude() {
        const fields = EcommerceDefaultFieldsToInclude.concat(this.fieldsToInclude);
        this.store.addFieldsToInclude(fields);
    }
    updateFieldsToInclude() {
        this.store.state.fieldsToInclude = [];
        this.initFieldsToInclude();
        this.registerFieldsToInclude();
    }
    initEngine(options) {
        const searchConfig = this.getSearchConfiguration(options);
        const analyticsConfig = getAnalyticsConfig(options, this.analytics, this.store);
        try {
            this.engine = buildSearchEngine({
                configuration: {
                    ...options,
                    search: searchConfig,
                    analytics: analyticsConfig
                },
                loggerOptions: {
                    level: this.logLevel
                }
            });
        } catch (error) {
            this.error = error;
            throw error;
        }
    }
    getSearchConfiguration(options) {
        const searchConfigFromProps = {
            searchHub: this.searchHub ?? 'default',
            pipeline: this.pipeline,
            locale: this.language,
            timezone: this.timezone
        };
        if (options.search) return {
            ...searchConfigFromProps,
            ...options.search
        };
        return searchConfigFromProps;
    }
    get fragment() {
        return window.location.hash.slice(1);
    }
    initUrlManager() {
        if (this.disableStateReflectionInUrl) return;
        if (!this.reflectStateInUrl) return;
        this.urlManager = buildUrlManager(this.engine, {
            initialState: {
                fragment: this.fragment
            }
        });
        this.unsubscribeUrlManager = this.urlManager.subscribe(()=>this.updateHash());
        window.addEventListener('hashchange', this.onHashChange);
    }
    async internalInitialization(initEngine) {
        await Promise.all([
            this.interfaceController.onInitialization(initEngine),
            this.i18Initialized
        ]);
        this.updateLanguage();
        this.bindings = this.getBindings();
        markParentAsReady(this);
        this.pipeline = this.engine.state.pipeline;
        this.searchHub = this.engine.state.searchHub;
        this.initSearchStatus();
        await waitForAtomicChildrenToBeDefined(this);
        await this.getUpdateComplete();
        this.initUrlManager();
        this.initialized = true;
    }
    initSearchStatus() {
        this.searchStatus = buildSearchStatus(this.engine);
        this.unsubscribeSearchStatus = this.searchStatus.subscribe(()=>{
            const hasNoResultsAfterInitialSearch = !this.searchStatus.state.hasResults && this.searchStatus.state.firstSearchExecuted && !this.searchStatus.state.hasError;
            this.classList.toggle(noResultsSelector, hasNoResultsAfterInitialSearch);
            this.classList.toggle(errorSelector, this.searchStatus.state.hasError);
            this.classList.toggle(firstSearchExecutedSelector, this.searchStatus.state.firstSearchExecuted);
            if (this.searchStatus.state.firstSearchExecuted && this.store.hasLoadingFlag(FirstSearchExecutedFlag)) this.store.unsetLoadingFlag(FirstSearchExecutedFlag);
        });
    }
    updateHash() {
        const newFragment = this.urlManager.state.fragment;
        if (!this.searchStatus.state.firstSearchExecuted) {
            history.replaceState(null, document.title, `#${newFragment}`);
            this.bindings.engine.logger.info(`History replaceState #${newFragment}`);
            return;
        }
        history.pushState(null, document.title, `#${newFragment}`);
        this.bindings.engine.logger.info(`History pushState #${newFragment}`);
    }
    constructor(){
        super(), this.bindings = {}, this.unsubscribeUrlManager = ()=>{}, this.unsubscribeSearchStatus = ()=>{}, this.initialized = false, this.interfaceController = new InterfaceController(this, 'CoveoAtomic', VERSION), this.fieldsToInclude = [], this.analytics = true, this.language = 'en', this.reflectStateInUrl = true, this.disableStateReflectionInUrl = false, this.scrollContainer = 'atomic-search-interface', this.languageAssetsPath = './lang', this.iconAssetsPath = './assets', this.enableRelevanceInspector = true, this.disableRelevanceInspector = false, this.handleInitialization = (event)=>{
            this.interfaceController.onComponentInitializing(event);
        }, this.onHashChange = ()=>{
            this.urlManager.synchronize(this.fragment);
        };
        this.store = createSearchStore();
        new MobileBreakpointController(this, this.store);
        const { promise, resolve } = Promise.withResolvers();
        this.i18Initialized = promise;
        this.i18n = i18next.createInstance(void 0, resolve);
    }
}
AtomicSearchInterface.styles = [
    css`:host{height:inherit;width:inherit;&>slot{height:inherit}}`
];
_ts_decorate([
    state(),
    provide({
        context: bindingsContext
    }),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicSearchInterface.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicSearchInterface.prototype, "error", void 0);
_ts_decorate([
    query('atomic-relevance-inspector'),
    _ts_metadata("design:type", "u" < typeof AtomicRelevanceInspector ? Object : AtomicRelevanceInspector)
], AtomicSearchInterface.prototype, "relevanceInspector", void 0);
_ts_decorate([
    property({
        type: Array,
        attribute: 'fields-to-include',
        converter: arrayConverter
    }),
    _ts_metadata("design:type", Array)
], AtomicSearchInterface.prototype, "fieldsToInclude", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicSearchInterface.prototype, "pipeline", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'search-hub',
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicSearchInterface.prototype, "searchHub", void 0);
_ts_decorate([
    property({
        type: Boolean,
        converter: booleanConverter,
        reflect: true
    })
], AtomicSearchInterface.prototype, "analytics", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicSearchInterface.prototype, "timezone", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'log-level',
        reflect: true
    }),
    _ts_metadata("design:type", "u" < typeof LogLevel ? Object : LogLevel)
], AtomicSearchInterface.prototype, "logLevel", void 0);
_ts_decorate([
    property({
        type: Object,
        attribute: false
    }),
    _ts_metadata("design:type", "u" < typeof i18n ? Object : i18n)
], AtomicSearchInterface.prototype, "i18n", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    })
], AtomicSearchInterface.prototype, "language", void 0);
_ts_decorate([
    property({
        type: Object,
        attribute: false
    }),
    _ts_metadata("design:type", "u" < typeof SearchEngine ? Object : SearchEngine)
], AtomicSearchInterface.prototype, "engine", void 0);
_ts_decorate([
    property({
        type: Boolean,
        attribute: 'reflect-state-in-url',
        reflect: true,
        converter: booleanConverter
    })
], AtomicSearchInterface.prototype, "reflectStateInUrl", void 0);
_ts_decorate([
    property({
        type: Boolean,
        attribute: 'disable-state-reflection-in-url',
        reflect: true
    })
], AtomicSearchInterface.prototype, "disableStateReflectionInUrl", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'scroll-container',
        reflect: true
    })
], AtomicSearchInterface.prototype, "scrollContainer", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'language-assets-path',
        reflect: true
    })
], AtomicSearchInterface.prototype, "languageAssetsPath", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'icon-assets-path',
        reflect: true
    })
], AtomicSearchInterface.prototype, "iconAssetsPath", void 0);
_ts_decorate([
    property({
        type: Boolean,
        attribute: 'enable-relevance-inspector',
        reflect: true,
        converter: booleanConverter
    })
], AtomicSearchInterface.prototype, "enableRelevanceInspector", void 0);
_ts_decorate([
    property({
        type: Boolean,
        attribute: 'disable-relevance-inspector',
        reflect: true
    })
], AtomicSearchInterface.prototype, "disableRelevanceInspector", void 0);
_ts_decorate([
    watch('searchHub'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicSearchInterface.prototype, "updateSearchHub", null);
_ts_decorate([
    watch('pipeline'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicSearchInterface.prototype, "updatePipeline", null);
_ts_decorate([
    watch('analytics'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicSearchInterface.prototype, "toggleAnalytics", null);
_ts_decorate([
    watch('language'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicSearchInterface.prototype, "updateLanguage", null);
_ts_decorate([
    watch('iconAssetsPath'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicSearchInterface.prototype, "updateIconAssetsPath", null);
_ts_decorate([
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicSearchInterface.prototype, "render", null);
AtomicSearchInterface = _ts_decorate([
    customElement('atomic-search-interface'),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicSearchInterface);
export { AtomicSearchInterface };
