import { VERSION, buildContext, loadConfigurationActions, loadContextActions } from "@coveo/headless/commerce";
import { provide } from "@lit/context";
import i18next from "i18next";
import { LitElement, css, html } from "lit";
import { customElement, property, state } from "lit/decorators.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 { bindingsContext } from "../../common/context/bindings-context.js";
import { augmentAnalyticsConfigWithAtomicVersion } from "../../common/interface/analytics-config.js";
import { InterfaceController } from "../../common/interface/interface-controller.js";
import { createCommerceRecommendationStore } 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);
}
class AtomicCommerceRecommendationInterface extends ChildrenUpdateCompleteMixin(LitElement) {
    connectedCallback() {
        super.connectedCallback();
        this.addEventListener('atomic/initializeComponent', this.handleInitialization);
        this.addEventListener('atomic/scrollToTop', this.scrollToTop);
    }
    initializeWithEngine(engine) {
        engine.dispatch(loadConfigurationActions(engine).updateAnalyticsConfiguration({
            trackingId: engine.configuration.analytics.trackingId,
            ...augmentAnalyticsConfigWithAtomicVersion()
        }));
        return this.internalInitialization(()=>{
            this.engine = engine;
        });
    }
    updateLocale(language, country, currency) {
        if (!this.interfaceController.engineIsCreated(this.engine) || !this.context) return;
        language && this.interfaceController.onLanguageChange(language);
        if (this.isNewLocale(language, country, currency)) {
            const { setContext } = loadContextActions(this.engine);
            this.engine.dispatch(setContext({
                ...this.context.state,
                ...language && {
                    language
                },
                ...country && {
                    country
                },
                ...currency && {
                    currency
                }
            }));
        }
    }
    toggleAnalytics() {
        this.interfaceController.onAnalyticsChange();
    }
    updateIconAssetsPath() {
        this.store.state.iconAssetsPath = this.iconAssetsPath;
    }
    async updateLanguage() {
        if (!this.interfaceController.engineIsCreated(this.engine) || !this.language || !this.context) return;
        this.engine.logger.warn('The `language` property will be removed in the next major version of Atomic (v4). Rather than using this property, set the initial language through the engine configuration when calling `initializeWithEngine`, and update the language as needed using the `updateLocale` method.');
        this.context.setLanguage(this.language);
        return this.interfaceController.onLanguageChange();
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.removeEventListener('atomic/initializeComponent', this.handleInitialization);
        this.removeEventListener('atomic/scrollToTop', this.scrollToTop);
    }
    render() {
        return html`<slot></slot>`;
    }
    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'
        });
    }
    async internalInitialization(initEngine) {
        await Promise.all([
            this.interfaceController.onInitialization(initEngine),
            this.i18Initialized
        ]);
        this.initContext();
        this.updateLanguage();
        this.bindings = this.getBindings();
        markParentAsReady(this);
        this.initLanguage();
        await waitForAtomicChildrenToBeDefined(this);
        await this.getUpdateComplete();
    }
    initContext() {
        this.context = buildContext(this.engine);
    }
    getBindings() {
        return {
            engine: this.engine,
            i18n: this.i18n,
            store: this.store,
            interfaceElement: this
        };
    }
    initLanguage() {
        if (!this.context || this.language) return;
        this.interfaceController.onLanguageChange(this.context.state.language);
    }
    isNewLocale(language, country, currency) {
        if (!this.context) return false;
        return language && language !== this.context.state.language || country && country !== this.context.state.country || currency && currency !== this.context.state.currency;
    }
    constructor(){
        super(), this.bindings = {}, this.interfaceController = new InterfaceController(this, 'CoveoAtomic', VERSION), this.scrollContainer = 'atomic-commerce-recommendation-interface', this.languageAssetsPath = './lang', this.iconAssetsPath = './assets', this.analytics = true, this.handleInitialization = (event)=>{
            this.interfaceController.onComponentInitializing(event);
        };
        this.store = createCommerceRecommendationStore();
        const { promise, resolve } = Promise.withResolvers();
        this.i18Initialized = promise;
        this.i18n = i18next.createInstance(void 0, resolve);
    }
}
AtomicCommerceRecommendationInterface.styles = [
    css`:host{display:block;height:inherit;width:inherit;&>slot{height:inherit}}`
];
_ts_decorate([
    state(),
    provide({
        context: bindingsContext
    }),
    _ts_metadata("design:type", "u" < typeof CommerceBindings ? Object : CommerceBindings)
], AtomicCommerceRecommendationInterface.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicCommerceRecommendationInterface.prototype, "error", void 0);
_ts_decorate([
    property({
        type: Object,
        attribute: false
    }),
    _ts_metadata("design:type", "u" < typeof i18n ? Object : i18n)
], AtomicCommerceRecommendationInterface.prototype, "i18n", void 0);
_ts_decorate([
    property({
        type: Object,
        attribute: false
    }),
    _ts_metadata("design:type", "u" < typeof CommerceEngine ? Object : CommerceEngine)
], AtomicCommerceRecommendationInterface.prototype, "engine", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'scroll-container',
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicCommerceRecommendationInterface.prototype, "scrollContainer", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'language-assets-path',
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicCommerceRecommendationInterface.prototype, "languageAssetsPath", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'icon-assets-path',
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicCommerceRecommendationInterface.prototype, "iconAssetsPath", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicCommerceRecommendationInterface.prototype, "language", void 0);
_ts_decorate([
    property({
        type: Boolean,
        converter: booleanConverter,
        reflect: true
    }),
    _ts_metadata("design:type", Boolean)
], AtomicCommerceRecommendationInterface.prototype, "analytics", void 0);
_ts_decorate([
    watch('analytics'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceRecommendationInterface.prototype, "toggleAnalytics", null);
_ts_decorate([
    watch('iconAssetsPath'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceRecommendationInterface.prototype, "updateIconAssetsPath", null);
_ts_decorate([
    watch('language'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", Promise)
], AtomicCommerceRecommendationInterface.prototype, "updateLanguage", null);
_ts_decorate([
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceRecommendationInterface.prototype, "render", null);
AtomicCommerceRecommendationInterface = _ts_decorate([
    customElement('atomic-commerce-recommendation-interface'),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicCommerceRecommendationInterface);
export { AtomicCommerceRecommendationInterface };
