import { VERSION, loadConfigurationActions } from "@coveo/headless";
import { EcommerceDefaultFieldsToInclude, buildRecommendationEngine, loadFieldActions, loadRecommendationActions, loadSearchConfigurationActions } from "@coveo/headless/recommendation";
import { provide } from "@lit/context";
import i18next from "i18next";
import { LitElement, html } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { bindingsContext } from "../../common/context/bindings-context.js";
import { augmentAnalyticsConfigWithAtomicVersion } from "../../common/interface/analytics-config.js";
import { InterfaceController } from "../../common/interface/interface-controller.js";
import { arrayConverter } from "../../../converters/array-converter.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 { getAnalyticsConfig } from "./analytics-config.js";
import { createRecsStore } 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 FirstRecommendationExecutedFlag = 'firstRecommendationExecuted';
const engineConfigurationConflictError = (configurationName)=>`A ${configurationName} is configured on the recommendation interface element, but the recommendation interface was initialized with an engine. You should only configure the ${configurationName} in the target engine.`;
class AtomicRecsInterface extends ChildrenUpdateCompleteMixin(LitElement) {
    connectedCallback() {
        super.connectedCallback();
        this.store.setLoadingFlag(FirstRecommendationExecutedFlag);
        this.initFieldsToInclude();
        this.addEventListener('atomic/initializeComponent', this.handleInitialization);
    }
    willUpdate(changedProperties) {
        super.willUpdate(changedProperties);
        if (changedProperties.has('fieldsToInclude')) this.updateFieldsToInclude();
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.removeEventListener('atomic/initializeComponent', this.handleInitialization);
    }
    initialize(options) {
        return this.internalInitialization(()=>this.initEngine(options));
    }
    initializeWithRecommendationEngine(engine) {
        if (this.pipeline && this.pipeline !== engine.state.pipeline) console.warn(engineConfigurationConflictError('query pipeline'));
        if (this.searchHub && this.searchHub !== engine.state.searchHub) console.warn(engineConfigurationConflictError('search hub'));
        engine.dispatch(loadConfigurationActions(engine).updateAnalyticsConfiguration({
            ...augmentAnalyticsConfigWithAtomicVersion()
        }));
        return this.internalInitialization(()=>{
            this.engine = engine;
        });
    }
    async getRecommendations() {
        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 request.', this);
        this.engine.dispatch(loadRecommendationActions(this.engine).getRecommendations());
    }
    registerFieldsToInclude() {
        this.engine?.dispatch(loadFieldActions(this.engine).registerFieldsToInclude(this.store.state.fieldsToInclude));
    }
    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`<slot></slot>`;
    }
    getBindings() {
        return {
            engine: this.engine,
            i18n: this.i18n,
            store: this.store,
            interfaceElement: this
        };
    }
    initEngine(options) {
        const analyticsConfig = getAnalyticsConfig(options, this.analytics);
        try {
            this.engine = buildRecommendationEngine({
                configuration: {
                    pipeline: this.pipeline,
                    searchHub: this.searchHub ?? 'default',
                    locale: this.language,
                    timezone: this.timezone,
                    analytics: analyticsConfig,
                    ...options
                },
                loggerOptions: {
                    level: this.logLevel
                }
            });
        } catch (error) {
            this.error = error;
            throw error;
        }
    }
    initFieldsToInclude() {
        const fields = EcommerceDefaultFieldsToInclude.concat(this.fieldsToInclude);
        this.store.addFieldsToInclude(fields);
    }
    updateFieldsToInclude() {
        this.store.state.fieldsToInclude = [];
        this.initFieldsToInclude();
        this.registerFieldsToInclude();
    }
    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.store.unsetLoadingFlag(FirstRecommendationExecutedFlag);
        await waitForAtomicChildrenToBeDefined(this);
        await this.getUpdateComplete();
        this.initialized = true;
    }
    constructor(){
        super(), this.bindings = {}, this.initialized = false, this.interfaceController = new InterfaceController(this, 'CoveoAtomicRecs', VERSION), this.fieldsToInclude = [], this.analytics = true, this.language = 'en', this.languageAssetsPath = './lang', this.iconAssetsPath = './assets', this.handleInitialization = (event)=>{
            this.interfaceController.onComponentInitializing(event);
        };
        this.store = createRecsStore();
        const { promise, resolve } = Promise.withResolvers();
        this.i18Initialized = promise;
        this.i18n = i18next.createInstance(void 0, resolve);
    }
}
_ts_decorate([
    state(),
    provide({
        context: bindingsContext
    }),
    _ts_metadata("design:type", "u" < typeof RecsBindings ? Object : RecsBindings)
], AtomicRecsInterface.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicRecsInterface.prototype, "error", void 0);
_ts_decorate([
    property({
        type: Array,
        attribute: 'fields-to-include',
        converter: arrayConverter
    }),
    _ts_metadata("design:type", Array)
], AtomicRecsInterface.prototype, "fieldsToInclude", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicRecsInterface.prototype, "pipeline", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'search-hub',
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicRecsInterface.prototype, "searchHub", void 0);
_ts_decorate([
    property({
        type: Boolean,
        converter: booleanConverter,
        reflect: true
    })
], AtomicRecsInterface.prototype, "analytics", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicRecsInterface.prototype, "timezone", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'log-level',
        reflect: true
    }),
    _ts_metadata("design:type", "u" < typeof RecsLogLevel ? Object : RecsLogLevel)
], AtomicRecsInterface.prototype, "logLevel", void 0);
_ts_decorate([
    property({
        type: Object,
        attribute: false
    }),
    _ts_metadata("design:type", "u" < typeof i18n ? Object : i18n)
], AtomicRecsInterface.prototype, "i18n", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    })
], AtomicRecsInterface.prototype, "language", void 0);
_ts_decorate([
    property({
        type: Object,
        attribute: false
    }),
    _ts_metadata("design:type", "u" < typeof RecommendationEngine ? Object : RecommendationEngine)
], AtomicRecsInterface.prototype, "engine", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'language-assets-path',
        reflect: true
    })
], AtomicRecsInterface.prototype, "languageAssetsPath", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'icon-assets-path',
        reflect: true
    })
], AtomicRecsInterface.prototype, "iconAssetsPath", void 0);
_ts_decorate([
    watch('analytics'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicRecsInterface.prototype, "toggleAnalytics", null);
_ts_decorate([
    watch('language'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicRecsInterface.prototype, "updateLanguage", null);
_ts_decorate([
    watch('iconAssetsPath'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicRecsInterface.prototype, "updateIconAssetsPath", null);
_ts_decorate([
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicRecsInterface.prototype, "render", null);
AtomicRecsInterface = _ts_decorate([
    customElement('atomic-recs-interface'),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicRecsInterface);
export { AtomicRecsInterface };
