/*!
 * Crafted with ❤ by Salla
 */
'use strict';

var index = require('./index-vstkdqRz.js');
var search = require('./search-c7Aa7lM9.js');

var StoreAlt = `<!-- Generated by IcoMoon.io -->
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
<title>store-alt</title>
<path d="M6.667 24h5.333c0.736 0 1.333-0.596 1.333-1.333s-0.597-1.333-1.333-1.333h-5.333c-0.736 0-1.333 0.596-1.333 1.333s0.597 1.333 1.333 1.333zM31.86 10.071l-4-8c-0.227-0.452-0.688-0.737-1.193-0.737h-21.333c-0.505 0-0.967 0.285-1.193 0.737l-4 8c-0.092 0.184-0.14 0.389-0.14 0.596v18.667c0 0.737 0.597 1.333 1.333 1.333h29.333c0.736 0 1.333-0.596 1.333-1.333v-18.667c0-0.207-0.048-0.412-0.14-0.596zM6.157 4h19.685l3.333 6.667h-26.352zM24 28h-5.333v-9.333h5.333zM29.333 28h-2.667v-10.667c0-0.737-0.597-1.333-1.333-1.333h-8c-0.736 0-1.333 0.596-1.333 1.333v10.667h-13.333v-14.667h26.667zM6.667 18.667h5.333c0.736 0 1.333-0.596 1.333-1.333s-0.597-1.333-1.333-1.333h-5.333c-0.736 0-1.333 0.596-1.333 1.333s0.597 1.333 1.333 1.333z"></path>
</svg>
`;

var ModeType;
(function (ModeType) {
    ModeType["DEFAULT"] = "default";
    ModeType["AVAILABILITY"] = "availability";
})(ModeType || (ModeType = {}));

const sallaScopesCss = ".s-scopes-availability-content{display:flex;justify-content:center;align-items:center}.s-scopes-placeholder{flex:0 0 85%}";

const SallaScopees = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        //to avoid over loading scopes in each open call
        this.loadedScopes = {
            [ModeType.DEFAULT]: null,
            [ModeType.AVAILABILITY]: null,
        };
        this.translationLoaded = false;
        this.mode = ModeType.DEFAULT;
        this.scopes = [];
        this.originalScopesList = [];
        this.isOpenedBefore = salla.storage.get("branch-choosed-before");
        this.hasError = false;
        this.loading = false;
        /**
         * Optionally open the modal or enforce the pop-up to the viewer
         */
        this.selection = 'optional';
        /**
         * Dictates when to show the search field
         */
        this.searchDisplayLimit = 6;
        this.getFormTitle = () => {
            if (this.originalScopesList?.length < 2)
                return "";
            const isMultiCountries = salla.config.get('store.features')?.includes('multi-countries');
            if (this.mode === ModeType.DEFAULT) {
                return salla.lang.get(isMultiCountries
                    ? "blocks.scope.shopping_from_another_market"
                    : "blocks.scope.shopping_from_another_branch");
            }
            return salla.lang.get('blocks.scope.search_for_availability_in_other_branches');
        };
        salla.event.on('scopes::open', ({ mode = null, product_id = null }) => {
            this.open(mode, product_id);
        });
        salla.lang.onLoaded(() => {
            this.translationLoaded = true;
        });
    }
    /**
     * Closes the scope modal.
     */
    async close() {
        return await this.modal?.close();
    }
    /**
     * Opens the scope modal.
     */
    async open(mode = ModeType.DEFAULT, product_id = null) {
        this.hasError = false;
        this.mode = [ModeType.AVAILABILITY, ModeType.DEFAULT].includes(mode) ? mode : ModeType.DEFAULT;
        this.loading = !this.loadedScopes[this.mode];
        this.setScopeValues([]);
        salla.log('SallaScope:: opened');
        this.modal.open();
        if (!this.loading) {
            this.setScopeValues(this.loadedScopes[this.mode]);
            return this.modal.stopLoading();
        }
        let callback = () => mode == ModeType.AVAILABILITY ? salla.scope.getProductAvailability(product_id) : salla.scope.get();
        return await salla.api.withoutNotifier(callback)
            .then((resp) => {
            if (mode == ModeType.AVAILABILITY) {
                return this.setScopeValues(this.loadedScopes[ModeType.AVAILABILITY] = resp.data);
            }
            this.setScopeValues(this.loadedScopes[this.mode] = resp.data.scopes);
        }).catch(e => {
            console.log(e);
            this.hasError = true;
        })
            .finally(() => {
            this.modal.stopLoading();
            this.loading = false;
        });
    }
    /**
     * Submit form to change exsiting scope.
     */
    async handleSubmit() {
        let payload = { 'id': this.current_scope.id };
        this.changeBtn.load();
        return await salla.scope.change(payload)
            .then(() => {
            salla.storage.set("branch-choosed-before", true);
            salla.storage.set("scope", {
                'type': this.current_scope.type,
                'id': this.current_scope.id
            });
            salla.cart.reset();
            window.location.replace(salla.helpers.addParamToUrl('scope', this.current_scope.id));
        }).catch(e => console.log(e))
            .finally(() => {
            this.changeBtn.stop();
        });
    }
    setScopeValues(value) {
        this.scopes = value;
        this.originalScopesList = value;
        if (value?.length == 1) {
            this.current_scope = value[0];
            this.selected_scope = value[0];
            this.scopes = [value[0]]; // Just to make sure it's consistent, might not have that much effect though.
        }
        else {
            this.current_scope = value?.find(scope => scope.selected);
            this.selected_scope = value?.find(scope => scope.selected);
        }
    }
    handleSearchFieldTyping(e) {
        let value = e.target.value.toLocaleLowerCase();
        if (!!value) {
            this.scopes = this.originalScopesList.filter(scope => scope.name.toLowerCase().includes(value));
        }
        else {
            this.scopes = this.originalScopesList;
        }
    }
    handleScopeSelection(event) {
        this.current_scope = this.scopes?.find(scope => scope.id == event.target.value);
    }
    placeholderContent() {
        return index.h("salla-placeholder", { alignment: "center", class: "s-scopes-placeholder" }, index.h("span", { slot: "title" }, salla.lang.get("blocks.scope.branch_looking_for_not_found")), index.h("span", { slot: "description" }, salla.lang.get("blocks.scope.our_services_not_available_in_this_branch")));
    }
    defaultContent() {
        return [index.h("div", { class: "s-scopes-container s-scrollbar" }, this.scopes?.map((scope) => index.h("div", { class: "s-scopes-input-wrap", "data-selection": this.selection }, index.h("input", { id: `${this.selection} + '_scope_' + ${scope.id}`, name: "lang", type: "radio", value: scope.id, onChange: (event) => this.handleScopeSelection(event), class: "s-scopes-input", checked: !!this.current_scope && this.current_scope.id == scope.id }), index.h("label", { htmlFor: `${this.selection} + '_scope_' + ${scope.id}`, class: "s-scopes-label s-scopes-clickable" }, index.h("span", null, scope.name))))), this.footerContent()];
    }
    availabilityContent() {
        return index.h("div", { class: "s-scopes-container" }, this.scopes?.map((scope) => index.h("div", { class: "s-scopes-input-wrap", "data-selection": this.selection }, index.h("h2", { class: { "s-scopes-label": true, "s-scopes-clickable": this.mode === ModeType.DEFAULT } }, index.h("span", null, scope.name)), index.h("h2", { style: { 'color': scope?.availability?.color }, class: `s-scopes-${scope?.availability?.key}` }, scope?.availability?.label))));
    }
    footerContent() {
        return index.h("div", { class: "s-scopes-footer" }, index.h("slot", { name: "footer" }, index.h("salla-button", { ref: btn => this.changeBtn = btn, disabled: !this.current_scope, onClick: () => this.handleSubmit(), class: "s-scopes-submit", "loader-position": "center", width: "wide" }, salla.lang.get('common.elements.confirm'))));
    }
    //let's wait to salla to be ready then render it.
    componentWillLoad() {
        return salla.onReady();
    }
    render() {
        return (index.h(index.Host, { key: '743fc37aec29a2ec15deb00c7463b51d0edcc29e' }, index.h("salla-modal", { key: '4b98493956bf34f97217d384d194a21d69ec011f', ref: modal => this.modal = modal, isClosable: !!(this.isOpenedBefore || (this.selection == 'optional')), class: "s-scopes-modal", isLoading: this.loading, "has-skeleton": true }, this.loading ?
            index.h("div", { slot: "loading" }, index.h("div", { class: "s-scopes-skeleton" }, index.h("salla-list-tile", { class: "s-scopes-header" }, index.h("div", { slot: "icon", class: "s-scopes-header-icon" }, index.h("salla-skeleton", { type: "circle" })), index.h("div", { slot: "title", class: "s-scopes-header-title mb-5" }, index.h("salla-skeleton", { height: '15px', width: '50%' })), index.h("div", { slot: "subtitle", class: "s-scopes-header-subtitle" }, index.h("salla-skeleton", { height: '10px' }), index.h("salla-skeleton", { height: '10px', width: '75%' }))), index.h("div", { class: "s-scopes-skeleton-search" }, index.h("salla-skeleton", { height: '10px', width: '50%' }), index.h("salla-skeleton", { height: '30px', width: '100%' })), index.h("div", { class: "s-scopes-skeleton-scopes" }, index.h("salla-skeleton", { height: '10px', width: '30%' }), index.h("salla-skeleton", { height: '10px', width: '25%' }), index.h("salla-skeleton", { height: '10px', width: '30%' }), index.h("salla-skeleton", { height: '10px', width: '25%' }), index.h("salla-skeleton", { height: '10px', width: '30%' }), index.h("salla-skeleton", { height: '10px', width: '25%' }), index.h("salla-skeleton", { height: '10px', width: '30%' }), index.h("salla-skeleton", { height: '10px', width: '25%' })), index.h("div", { class: "s-scopes-skeleton-btn" }, index.h("salla-skeleton", { height: '40px', width: '100%' }))))
            :
                [index.h("salla-list-tile", { class: this.originalScopesList?.length ? "s-scopes-header block" : "s-hidden" }, index.h("div", { slot: "icon", class: "s-scopes-header-icon", innerHTML: StoreAlt }), index.h("div", { slot: "title", class: "s-scopes-header-title" }, salla.lang.get('blocks.scope.you_are_browse_store_from')), index.h("div", { slot: "subtitle", class: "s-scopes-header-subtitle" }, !!this.selected_scope ? this.selected_scope.name : "")), index.h("div", { class: "s-scopes-wrap" }, !!this.originalScopesList?.length && index.h("h4", { class: "s-scopes-title" }, this.getFormTitle()), this.originalScopesList?.length > this.searchDisplayLimit ?
                        index.h("div", { class: "s-scopes-search-wrapper" }, index.h("div", { class: "s-scopes-search-icon", innerHTML: search.Search }), index.h("input", { type: "text", class: "s-scopes-search-input", onInput: e => this.handleSearchFieldTyping(e), enterkeyhint: "search", placeholder: salla.lang.get('blocks.scope.searching_for_a_branch') }))
                        : "", this.hasError || (!this.originalScopesList?.length && this.mode !== ModeType.AVAILABILITY) ?
                        this.placeholderContent()
                        : this.mode === ModeType.DEFAULT ? this.defaultContent() : this.availabilityContent())])));
    }
    async componentDidLoad() {
        await Salla.hooks.registerComponent('salla-scopes', this);
        // * Note: Do not auto open scopes modal in mobile app
        const isMobileApp = salla.config.isMobileApp();
        if (isMobileApp)
            return;
        if (!this.isOpenedBefore && this.selection == 'mandatory') {
            this.open();
        }
    }
};
SallaScopees.style = sallaScopesCss;

exports.salla_scopes = SallaScopees;
