import { VERSION, buildCommerceEngine, buildContext, buildProductListing, buildSearch, loadConfigurationActions, loadContextActions, loadQueryActions } 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 { errorSelector, firstSearchExecutedSelector, noProductsSelector } from "../atomic-commerce-layout/commerce-layout.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 { MobileBreakpointController } from "../../common/layout/mobile-breakpoint-controller.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 { getAnalyticsConfig } from "./analytics-config.js";
import { createCommerceStore } 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 FirstRequestExecutedFlag = 'firstRequestExecuted';
class AtomicCommerceInterface extends ChildrenUpdateCompleteMixin(LitElement) {
    connectedCallback() {
        super.connectedCallback();
        this.store.setLoadingFlag(FirstRequestExecutedFlag);
        this.addEventListener('atomic/initializeComponent', this.handleInitialization);
        this.addEventListener('atomic/scrollToTop', this.scrollToTop);
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        if ('function' == typeof this.unsubscribeUrlManager) this.unsubscribeUrlManager();
        if ('function' == typeof this.unsubscribeSummary) this.unsubscribeSummary();
        window.removeEventListener('hashchange', this.onHashChange);
        this.removeEventListener('atomic/initializeComponent', this.handleInitialization);
        this.removeEventListener('atomic/scrollToTop', this.scrollToTop);
    }
    initialize(options) {
        return this.internalInitialization(()=>this.initEngine(options));
    }
    initializeWithEngine(engine) {
        engine.dispatch(loadConfigurationActions(engine).updateAnalyticsConfiguration({
            trackingId: engine.configuration.analytics.trackingId,
            ...augmentAnalyticsConfigWithAtomicVersion()
        }));
        return this.internalInitialization(()=>{
            this.engine = engine;
        });
    }
    async executeFirstRequest() {
        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);
        if ('search' === this.type) {
            const safeStorage = new SafeStorage();
            const standaloneSearchBoxData = safeStorage.getParsedJSON(StorageItems.STANDALONE_SEARCH_BOX_DATA, null);
            if (!standaloneSearchBoxData) return void this.searchOrListing.executeFirstSearch();
            safeStorage.removeItem(StorageItems.STANDALONE_SEARCH_BOX_DATA);
            const { value } = standaloneSearchBoxData;
            this.engine.dispatch(loadQueryActions(this.engine).updateQuery({
                query: value
            }));
            this.searchOrListing.executeFirstSearch();
        } else this.searchOrListing.executeFirstRequest();
    }
    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() {
        if (!this.interfaceController.engineIsCreated(this.engine)) return;
        this.interfaceController.onAnalyticsChange();
    }
    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 `initialize` or `initializeWithEngine`, and update the language as needed using the `updateLocale` method.');
        this.context.setLanguage(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 = buildCommerceEngine({
                configuration: {
                    ...options,
                    analytics: analyticsConfig
                },
                loggerOptions: {
                    level: this.logLevel
                }
            });
        } catch (error) {
            this.error = error;
            throw error;
        }
    }
    get fragment() {
        return window.location.hash.slice(1);
    }
    initContext() {
        this.context = buildContext(this.engine);
    }
    initLanguage() {
        if (!this.context || this.language) return;
        this.interfaceController.onLanguageChange(this.context.state.language);
    }
    initRequestStatus() {
        this.searchOrListing = 'product-listing' === this.type ? buildProductListing(this.engine) : buildSearch(this.engine);
    }
    initSummary() {
        this.summary = this.searchOrListing.summary();
        this.unsubscribeSummary = this.summary.subscribe(()=>{
            const { firstRequestExecuted, hasProducts, hasError } = this.summary.state;
            const hasNoProductsAfterInitialQuery = firstRequestExecuted && !hasError && !hasProducts;
            this.classList.toggle(noProductsSelector, hasNoProductsAfterInitialQuery);
            this.classList.toggle(errorSelector, hasError);
            this.classList.toggle(firstSearchExecutedSelector, firstRequestExecuted);
            if (firstRequestExecuted) this.store.unsetLoadingFlag(FirstRequestExecutedFlag);
        });
    }
    initUrlManager() {
        if (this.disableStateReflectionInUrl) return;
        if (!this.reflectStateInUrl) return;
        this.urlManager = this.searchOrListing.urlManager({
            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.initContext();
        this.updateLanguage();
        this.bindings = this.getBindings();
        markParentAsReady(this);
        this.initRequestStatus();
        this.initSummary();
        this.initLanguage();
        await waitForAtomicChildrenToBeDefined(this);
        await this.getUpdateComplete();
        this.initUrlManager();
        this.initialized = true;
    }
    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;
    }
    scrollToTop() {
        const scrollContainerElement = document.querySelector(this.scrollContainer);
        if (!scrollContainerElement) return void console.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'
        });
    }
    updateHash() {
        const newFragment = this.urlManager.state.fragment;
        if (!this.summary.state.firstRequestExecuted) {
            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.unsubscribeSummary = ()=>{}, this.initialized = false, this.interfaceController = new InterfaceController(this, 'CoveoAtomic', VERSION), this.type = 'search', this.analytics = true, this.reflectStateInUrl = true, this.disableStateReflectionInUrl = false, this.scrollContainer = 'atomic-commerce-interface', this.languageAssetsPath = './lang', this.iconAssetsPath = './assets', this.handleInitialization = (event)=>{
            this.interfaceController.onComponentInitializing(event);
        }, this.onHashChange = ()=>{
            this.urlManager.synchronize(this.fragment);
        };
        this.store = createCommerceStore(this.type);
        new MobileBreakpointController(this, this.store);
        const { promise, resolve } = Promise.withResolvers();
        this.i18Initialized = promise;
        this.i18n = i18next.createInstance(void 0, resolve);
    }
}
AtomicCommerceInterface.styles = [
    css`:host{height:inherit;width:inherit;&>slot{height:inherit}}`
];
_ts_decorate([
    state(),
    provide({
        context: bindingsContext
    }),
    _ts_metadata("design:type", "u" < typeof CommerceBindings ? Object : CommerceBindings)
], AtomicCommerceInterface.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicCommerceInterface.prototype, "error", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicCommerceInterface.prototype, "type", void 0);
_ts_decorate([
    property({
        type: Boolean,
        converter: booleanConverter,
        reflect: true
    })
], AtomicCommerceInterface.prototype, "analytics", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'log-level',
        reflect: true
    }),
    _ts_metadata("design:type", "u" < typeof LogLevel ? Object : LogLevel)
], AtomicCommerceInterface.prototype, "logLevel", void 0);
_ts_decorate([
    property({
        type: Object,
        attribute: false
    }),
    _ts_metadata("design:type", "u" < typeof i18n ? Object : i18n)
], AtomicCommerceInterface.prototype, "i18n", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicCommerceInterface.prototype, "language", void 0);
_ts_decorate([
    property({
        type: Object,
        attribute: false
    }),
    _ts_metadata("design:type", "u" < typeof CommerceEngine ? Object : CommerceEngine)
], AtomicCommerceInterface.prototype, "engine", void 0);
_ts_decorate([
    property({
        type: Boolean,
        attribute: 'reflect-state-in-url',
        reflect: true,
        converter: booleanConverter
    })
], AtomicCommerceInterface.prototype, "reflectStateInUrl", void 0);
_ts_decorate([
    property({
        type: Boolean,
        attribute: 'disable-state-reflection-in-url',
        reflect: true
    })
], AtomicCommerceInterface.prototype, "disableStateReflectionInUrl", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'scroll-container',
        reflect: true
    })
], AtomicCommerceInterface.prototype, "scrollContainer", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'language-assets-path',
        reflect: true
    })
], AtomicCommerceInterface.prototype, "languageAssetsPath", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'icon-assets-path',
        reflect: true
    })
], AtomicCommerceInterface.prototype, "iconAssetsPath", void 0);
_ts_decorate([
    watch('analytics'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceInterface.prototype, "toggleAnalytics", null);
_ts_decorate([
    watch('language'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceInterface.prototype, "updateLanguage", null);
_ts_decorate([
    watch('iconAssetsPath'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceInterface.prototype, "updateIconAssetsPath", null);
_ts_decorate([
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceInterface.prototype, "render", null);
AtomicCommerceInterface = _ts_decorate([
    customElement('atomic-commerce-interface'),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicCommerceInterface);
export { AtomicCommerceInterface };
