import { VERSION, buildInsightEngine, buildResultsPerPage, loadFieldActions } from "@coveo/headless/insight";
import { provide } from "@lit/context";
import i18next from "i18next";
import { LitElement, css, html } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { bindingsContext } from "../../common/context/bindings-context.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 { createInsightStore } 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 FirstInsightRequestExecutedFlag = 'firstInsightRequestExecuted';
class AtomicInsightInterface extends ChildrenUpdateCompleteMixin(LitElement) {
    connectedCallback() {
        super.connectedCallback();
        this.store.setLoadingFlag(FirstInsightRequestExecutedFlag);
        this.addEventListener('atomic/initializeComponent', this.handleInitialization);
    }
    initialize(options) {
        return this.internalInitialization(()=>this.initEngine(options));
    }
    initializeWithInsightEngine(engine) {
        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);
        this.engine.executeFirstSearch();
    }
    toggleAnalytics() {
        this.interfaceController.onAnalyticsChange();
    }
    updateIconAssetsPath() {
        this.store.state.iconAssetsPath = this.iconAssetsPath;
    }
    updateLanguage() {
        return this.interfaceController.onLanguageChange();
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.removeEventListener('atomic/initializeComponent', this.handleInitialization);
    }
    render() {
        return html`
      <slot name="full-search"></slot>
      <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 = buildInsightEngine({
                configuration: {
                    ...options,
                    analytics: analyticsConfig
                },
                loggerOptions: {
                    level: this.logLevel
                }
            });
        } catch (error) {
            this.error = error;
            throw error;
        }
    }
    initResultsPerPage() {
        if (!this.interfaceController.engineIsCreated(this.engine)) return;
        buildResultsPerPage(this.bindings.engine, {
            initialState: {
                numberOfResults: this.resultsPerPage
            }
        });
    }
    async internalInitialization(initEngine) {
        await Promise.all([
            this.interfaceController.onInitialization(initEngine),
            this.i18Initialized
        ]);
        this.updateLanguage();
        this.bindings = this.getBindings();
        markParentAsReady(this);
        this.initResultsPerPage();
        this.registerFieldsToInclude();
        this.store.unsetLoadingFlag(FirstInsightRequestExecutedFlag);
        await waitForAtomicChildrenToBeDefined(this);
        await this.getUpdateComplete();
        this.initialized = true;
    }
    registerFieldsToInclude() {
        if (this.fieldsToInclude.length) this.engine.dispatch(loadFieldActions(this.engine).registerFieldsToInclude([
            ...this.fieldsToInclude
        ]));
    }
    constructor(){
        super(), this.bindings = {}, this.initialized = false, this.interfaceController = new InterfaceController(this, 'CoveoAtomic', VERSION), this.analytics = true, this.language = 'en', this.languageAssetsPath = './lang', this.iconAssetsPath = './assets', this.fieldsToInclude = [], this.resultsPerPage = 5, this.handleInitialization = (event)=>{
            this.interfaceController.onComponentInitializing(event);
        };
        this.store = createInsightStore();
        const { promise, resolve } = Promise.withResolvers();
        this.i18Initialized = promise;
        this.i18n = i18next.createInstance(void 0, resolve);
    }
}
AtomicInsightInterface.styles = css`:host{position:relative}slot[name=full-search]{display:block;position:absolute;right:0;top:0}`;
_ts_decorate([
    state(),
    provide({
        context: bindingsContext
    }),
    _ts_metadata("design:type", "u" < typeof InsightBindings ? Object : InsightBindings)
], AtomicInsightInterface.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicInsightInterface.prototype, "error", void 0);
_ts_decorate([
    property({
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof InsightEngine ? Object : InsightEngine)
], AtomicInsightInterface.prototype, "engine", void 0);
_ts_decorate([
    property({
        type: Boolean,
        converter: booleanConverter,
        reflect: true
    })
], AtomicInsightInterface.prototype, "analytics", void 0);
_ts_decorate([
    property({
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof i18n ? Object : i18n)
], AtomicInsightInterface.prototype, "i18n", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'log-level',
        reflect: true
    }),
    _ts_metadata("design:type", "u" < typeof InsightLogLevel ? Object : InsightLogLevel)
], AtomicInsightInterface.prototype, "logLevel", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'language',
        reflect: true
    })
], AtomicInsightInterface.prototype, "language", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'language-assets-path',
        reflect: true
    })
], AtomicInsightInterface.prototype, "languageAssetsPath", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'icon-assets-path',
        reflect: true
    })
], AtomicInsightInterface.prototype, "iconAssetsPath", void 0);
_ts_decorate([
    property({
        type: Array,
        attribute: 'fields-to-include',
        converter: arrayConverter
    }),
    _ts_metadata("design:type", Array)
], AtomicInsightInterface.prototype, "fieldsToInclude", void 0);
_ts_decorate([
    property({
        type: Number,
        attribute: 'results-per-page',
        reflect: true
    })
], AtomicInsightInterface.prototype, "resultsPerPage", void 0);
_ts_decorate([
    watch('analytics'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicInsightInterface.prototype, "toggleAnalytics", null);
_ts_decorate([
    watch('iconAssetsPath'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicInsightInterface.prototype, "updateIconAssetsPath", null);
_ts_decorate([
    watch('language'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicInsightInterface.prototype, "updateLanguage", null);
_ts_decorate([
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicInsightInterface.prototype, "render", null);
AtomicInsightInterface = _ts_decorate([
    customElement('atomic-insight-interface'),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicInsightInterface);
export { AtomicInsightInterface };
