"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.n = (module)=>{
        var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
(()=>{
    __webpack_require__.d = (exports1, definition)=>{
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
    __webpack_require__.r = (exports1)=>{
        if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    AtomicSearchInterface: ()=>AtomicSearchInterface
});
const headless_namespaceObject = require("@coveo/headless");
const context_namespaceObject = require("@lit/context");
const external_i18next_namespaceObject = require("i18next");
var external_i18next_default = /*#__PURE__*/ __webpack_require__.n(external_i18next_namespaceObject);
const external_lit_namespaceObject = require("lit");
const decorators_js_namespaceObject = require("lit/decorators.js");
const when_js_namespaceObject = require("lit/directives/when.js");
const bindings_context_cjs_namespaceObject = require("../../common/context/bindings-context.cjs");
const interface_controller_cjs_namespaceObject = require("../../common/interface/interface-controller.cjs");
const mobile_breakpoint_controller_cjs_namespaceObject = require("../../common/layout/mobile-breakpoint-controller.cjs");
const search_layout_cjs_namespaceObject = require("../atomic-search-layout/search-layout.cjs");
const boolean_converter_cjs_namespaceObject = require("../../../converters/boolean-converter.cjs");
const error_guard_cjs_namespaceObject = require("../../../decorators/error-guard.cjs");
const watch_cjs_namespaceObject = require("../../../decorators/watch.cjs");
const with_tailwind_styles_cjs_namespaceObject = require("../../../decorators/with-tailwind-styles.cjs");
const children_update_complete_mixin_cjs_namespaceObject = require("../../../mixins/children-update-complete-mixin.cjs");
const init_queue_cjs_namespaceObject = require("../../../utils/init-queue.cjs");
const initialization_common_utils_cjs_namespaceObject = require("../../../utils/initialization-common-utils.cjs");
const local_storage_utils_cjs_namespaceObject = require("../../../utils/local-storage-utils.cjs");
require("../atomic-relevance-inspector/atomic-relevance-inspector.cjs");
const analytics_config_cjs_namespaceObject = require("../../common/interface/analytics-config.cjs");
const array_converter_cjs_namespaceObject = require("../../../converters/array-converter.cjs");
const external_analytics_config_cjs_namespaceObject = require("./analytics-config.cjs");
const external_store_cjs_namespaceObject = require("./store.cjs");
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 (0, children_update_complete_mixin_cjs_namespaceObject.ChildrenUpdateCompleteMixin)(external_lit_namespaceObject.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((0, headless_namespaceObject.loadConfigurationActions)(engine).updateAnalyticsConfiguration({
            ...(0, analytics_config_cjs_namespaceObject.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 local_storage_utils_cjs_namespaceObject.SafeStorage();
        const standaloneSearchBoxData = safeStorage.getParsedJSON(local_storage_utils_cjs_namespaceObject.StorageItems.STANDALONE_SEARCH_BOX_DATA, null);
        if (!standaloneSearchBoxData) return void this.engine.executeFirstSearch();
        safeStorage.removeItem(local_storage_utils_cjs_namespaceObject.StorageItems.STANDALONE_SEARCH_BOX_DATA);
        const { updateQuery } = (0, headless_namespaceObject.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 } = (0, headless_namespaceObject.loadSearchConfigurationActions)(this.engine);
        this.engine.dispatch(updateSearchConfiguration({
            [updatedProp]: newValue
        }));
    }
    registerFieldsToInclude() {
        this.engine?.dispatch((0, headless_namespaceObject.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 } = (0, headless_namespaceObject.loadSearchConfigurationActions)(this.engine);
        this.engine.dispatch(updateSearchConfiguration({
            locale: this.language
        }));
        return this.interfaceController.onLanguageChange();
    }
    updateIconAssetsPath() {
        this.store.state.iconAssetsPath = this.iconAssetsPath;
    }
    render() {
        return (0, external_lit_namespaceObject.html)`
      ${(0, when_js_namespaceObject.when)(this.bindings?.engine && this.enableRelevanceInspector && !this.disableRelevanceInspector, ()=>(0, external_lit_namespaceObject.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 = headless_namespaceObject.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 = (0, external_analytics_config_cjs_namespaceObject.getAnalyticsConfig)(options, this.analytics, this.store);
        try {
            this.engine = (0, headless_namespaceObject.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 = (0, headless_namespaceObject.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();
        (0, init_queue_cjs_namespaceObject.markParentAsReady)(this);
        this.pipeline = this.engine.state.pipeline;
        this.searchHub = this.engine.state.searchHub;
        this.initSearchStatus();
        await (0, initialization_common_utils_cjs_namespaceObject.waitForAtomicChildrenToBeDefined)(this);
        await this.getUpdateComplete();
        this.initUrlManager();
        this.initialized = true;
    }
    initSearchStatus() {
        this.searchStatus = (0, headless_namespaceObject.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(search_layout_cjs_namespaceObject.noResultsSelector, hasNoResultsAfterInitialSearch);
            this.classList.toggle(search_layout_cjs_namespaceObject.errorSelector, this.searchStatus.state.hasError);
            this.classList.toggle(search_layout_cjs_namespaceObject.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 interface_controller_cjs_namespaceObject.InterfaceController(this, 'CoveoAtomic', headless_namespaceObject.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 = (0, external_store_cjs_namespaceObject.createSearchStore)();
        new mobile_breakpoint_controller_cjs_namespaceObject.MobileBreakpointController(this, this.store);
        const { promise, resolve } = Promise.withResolvers();
        this.i18Initialized = promise;
        this.i18n = external_i18next_default().createInstance(void 0, resolve);
    }
}
AtomicSearchInterface.styles = [
    (0, external_lit_namespaceObject.css)`
      :host {
        height: inherit;
        width: inherit;
        & > slot {
          height: inherit;
        }
      }
    `
];
_ts_decorate([
    (0, decorators_js_namespaceObject.state)(),
    (0, context_namespaceObject.provide)({
        context: bindings_context_cjs_namespaceObject.bindingsContext
    }),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicSearchInterface.prototype, "bindings", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicSearchInterface.prototype, "error", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.query)('atomic-relevance-inspector'),
    _ts_metadata("design:type", "u" < typeof AtomicRelevanceInspector ? Object : AtomicRelevanceInspector)
], AtomicSearchInterface.prototype, "relevanceInspector", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Array,
        attribute: 'fields-to-include',
        converter: array_converter_cjs_namespaceObject.arrayConverter
    }),
    _ts_metadata("design:type", Array)
], AtomicSearchInterface.prototype, "fieldsToInclude", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicSearchInterface.prototype, "pipeline", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: String,
        attribute: 'search-hub',
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicSearchInterface.prototype, "searchHub", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Boolean,
        converter: boolean_converter_cjs_namespaceObject.booleanConverter,
        reflect: true
    })
], AtomicSearchInterface.prototype, "analytics", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicSearchInterface.prototype, "timezone", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: String,
        attribute: 'log-level',
        reflect: true
    }),
    _ts_metadata("design:type", "u" < typeof LogLevel ? Object : LogLevel)
], AtomicSearchInterface.prototype, "logLevel", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Object,
        attribute: false
    }),
    _ts_metadata("design:type", "u" < typeof i18n ? Object : i18n)
], AtomicSearchInterface.prototype, "i18n", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: String,
        reflect: true
    })
], AtomicSearchInterface.prototype, "language", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Object,
        attribute: false
    }),
    _ts_metadata("design:type", "u" < typeof SearchEngine ? Object : SearchEngine)
], AtomicSearchInterface.prototype, "engine", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Boolean,
        attribute: 'reflect-state-in-url',
        reflect: true,
        converter: boolean_converter_cjs_namespaceObject.booleanConverter
    })
], AtomicSearchInterface.prototype, "reflectStateInUrl", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Boolean,
        attribute: 'disable-state-reflection-in-url',
        reflect: true
    })
], AtomicSearchInterface.prototype, "disableStateReflectionInUrl", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: String,
        attribute: 'scroll-container',
        reflect: true
    })
], AtomicSearchInterface.prototype, "scrollContainer", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: String,
        attribute: 'language-assets-path',
        reflect: true
    })
], AtomicSearchInterface.prototype, "languageAssetsPath", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: String,
        attribute: 'icon-assets-path',
        reflect: true
    })
], AtomicSearchInterface.prototype, "iconAssetsPath", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Boolean,
        attribute: 'enable-relevance-inspector',
        reflect: true,
        converter: boolean_converter_cjs_namespaceObject.booleanConverter
    })
], AtomicSearchInterface.prototype, "enableRelevanceInspector", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Boolean,
        attribute: 'disable-relevance-inspector',
        reflect: true
    })
], AtomicSearchInterface.prototype, "disableRelevanceInspector", void 0);
_ts_decorate([
    (0, watch_cjs_namespaceObject.watch)('searchHub'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicSearchInterface.prototype, "updateSearchHub", null);
_ts_decorate([
    (0, watch_cjs_namespaceObject.watch)('pipeline'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicSearchInterface.prototype, "updatePipeline", null);
_ts_decorate([
    (0, watch_cjs_namespaceObject.watch)('analytics'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicSearchInterface.prototype, "toggleAnalytics", null);
_ts_decorate([
    (0, watch_cjs_namespaceObject.watch)('language'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicSearchInterface.prototype, "updateLanguage", null);
_ts_decorate([
    (0, watch_cjs_namespaceObject.watch)('iconAssetsPath'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicSearchInterface.prototype, "updateIconAssetsPath", null);
_ts_decorate([
    (0, error_guard_cjs_namespaceObject.errorGuard)(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicSearchInterface.prototype, "render", null);
AtomicSearchInterface = _ts_decorate([
    (0, decorators_js_namespaceObject.customElement)('atomic-search-interface'),
    with_tailwind_styles_cjs_namespaceObject.withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicSearchInterface);
exports.AtomicSearchInterface = __webpack_exports__.AtomicSearchInterface;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "AtomicSearchInterface"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
