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

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

const SallaLocalizationModal = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.languageNames = {
            "ar": "العربية",
            "en": "English",
            "sq": "shqip",
            "hy": "հայերէն",
            "bg": "български",
            "zh": "汉语",
            "hr": "hrvatski",
            "cs": "čeština",
            "da": "dansk",
            "nl": "dutch",
            "et": "eesti keel",
            "fi": "suomen kieli",
            "fr": "Français",
            "de": "Deutsch",
            "el": "Ελληνικά",
            "hi": "हिन्दी",
            "hu": "magyar",
            //we know it's `id` as ISO 639-1 but we are using `ind` as ISO 639-2 on our system as key to avoid conflicts with `id` attribute
            "ind": "bahasa Indonesia",
            "ga": "Gaeilge",
            "it": "Italiano",
            "ja": "日本語",
            "ko": "한국어",
            "lv": "latviešu",
            "mt": "Maltese",
            "fa": "فارسی",
            "pl": "Polish",
            "pt": "português",
            "ro": "română",
            "ru": "русский",
            "sl": "slovenščina",
            "es": "Español",
            "sv": "svenska",
            "tl": "Tagalog (Filipino)",
            "tr": "Türkçe",
            "uk": "украї́нська",
            "ur": "اُردُو",
            "ms": "Bahasa Malaysia",
        };
        this.currenciesList = {
            SAR: { en: "Saudi Riyal", ar: "ريال سعودي", symbol: "ر.س" },
            USD: { en: "US Dollar", ar: "دولار أمريكي", symbol: "$" },
            EUR: { en: "Euro", ar: "يورو", symbol: "€" },
            AED: { en: "UAE Dirham", ar: "درهم اماراتي", symbol: "د.إ" },
            KWD: { en: "Kuwaiti Dinar", ar: "دينار كويتي", symbol: "د.ك" },
            BHD: { en: "Bahraini Dinar", ar: "دينار بحريني", symbol: "د.ب" },
            QAR: { en: "Qatari Riyal", ar: "ريال قطري", symbol: "ر.ق" },
            OMR: { en: "Omani Rial", ar: "ريال عماني", symbol: "ر.ع" },
            AUD: { en: "Australian Dollar", ar: "دولار استرالي", symbol: "$" },
            CAD: { en: "Canadian Dollar", ar: "دولار كندي", symbol: "$" },
            CNY: { en: "Renminbi", ar: "رنمينبي", symbol: "¥" },
            EGP: { en: "Egyptian Pound", ar: "جنيه مصري", symbol: "ج.م" },
            GBP: { en: "Pound Sterling", ar: "جنيه استرليني", symbol: "£" },
            IDR: { en: "Indonesian Rupiah", ar: "روبية إندونيسية", symbol: "Rp" },
            INR: { en: "Indian Rupee", ar: "روبية هندية", symbol: "₹" },
            JPY: { en: "Japanese Yen", ar: "ين ياباني", symbol: "¥" },
            MYR: { en: "Malaysian Ringgit", ar: "رينغيت ماليزي", symbol: "RM" },
            PKR: { en: "Pakistani Rupee", ar: "روبية باكستانية", symbol: "Rs." },
            SEK: { en: "Swedish Krona", ar: "كرونة سويدية", symbol: "kr" },
            SGD: { en: "Singapore Dollar", ar: "دولار سنغافوري", symbol: "$" },
            TRY: { en: "Turkish Lira", ar: "ليرة تركية", symbol: "₺" },
            IQD: { en: "Iraqi Dinar", ar: "دينار عراقي", symbol: "د.ع" },
            LBP: { en: "Lebanese Pound", ar: "ليرة لبنانية", symbol: "ل.ل" },
            MRO: { en: "Mauritanian Ouguiya", ar: "أوقية موريتانية", symbol: "UM" },
            SDG: { en: "Sudanese Pound", ar: "جنيه سوداني", symbol: "SDG" },
            SYP: { en: "Syrian Pound", ar: "ليرة سورية", symbol: "ل.س" },
            TND: { en: "Tunisian Dinar", ar: "دينار تونسي", symbol: "د.ت" },
            JOD: { en: "Jordanian Dinar", ar: "دينار أردني", symbol: "JOD" },
            DZD: { en: "Algerian Dinar", ar: "دينار جزائري", symbol: "دج" },
            MAD: { en: "Moroccan Dirham", ar: "درهم مغربي", symbol: "د.م." },
            LYD: { en: "Libyan Dinar", ar: "دينار ليبي", symbol: "LD" },
            YER: { en: "Yemeni Riyal", ar: "ريال يمني", symbol: "ر.ي" }
        };
        //here we will used the currency code instead of the symbol when current language is not arabic
        this.arabicCurrencies = ["SAR", "AED", "KWD", "BHD", "QAR", "OMR", "EGP", "IQD", "LBP", "SYP", "TND", "DZD", "MAD", "YER"];
        this.languages = [];
        this.currencies = [];
        this.hasError = false;
        /**
         * To show the trigger button or not
         */
        this.showTrigger = false;
        /**
         * letting developer to insert his own slot like:
         * <salla-localization>
         *   <div slot="language">...{name}....</div>
         *   <div slot="currency">...{name}....</div>
         * </salla-localization>
         * Because scoped templates not supported in stencil );
         * we made a workaround to pass language & currency attributes, then replace names in rendering
         */
        this.languageSlot = this.host.querySelector('[slot="language"]')?.innerHTML || '<label class="s-localization-modal-label" for="lang-{code}"><span>{name}</span></label>';
        this.currencySlot = this.host.querySelector('[slot="currency"]')?.innerHTML || '<label class="s-localization-modal-label" for="currency-{code}"><span>{name}</span><small class="s-localization-modal-currency">{symbol}</small></label>';
    }
    async componentWillLoad() {
        await Salla.onReady();
        await Salla.lang.onLoaded();
        Salla.event.on('localization::open', () => this.open());
        if (!this.language) {
            this.language = Salla.config.get('user.language_code');
        }
        if (!this.currency) {
            this.currency = Salla.config.get('user.currency_code');
        }
    }
    /**
     * open the component
     */
    async open() {
        this.modal.open();
        return await Salla.api.withoutNotifier(() => this.getLanguages())
            .then(() => this.getCurrencies())
            .then(() => {
            if (this.languages.length < 2 && this.currencies.length < 2) {
                this.modal.close();
            }
        })
            .catch(e => {
            console.log(e);
            this.hasError = true;
            this.errorMessage = e.response?.data?.error?.message || e.response?.data;
        })
            .finally(() => this.modal.stopLoading());
    }
    /**
     * Hide the component
     */
    async close() {
        return this.modal.close();
    }
    getCurrency(currencyCode) {
        return this.currenciesList[currencyCode || this.currency] || { en: "Saudi Riyal", ar: "ريال سعودي", symbol: "ر.س" };
    }
    getLanguageName() {
        return this.languageNames[this.language] || this.language || '';
    }
    getCurrencySymbol(currencyCode) {
        currencyCode = currencyCode || this.currency;
        if (currencyCode === 'SAR') {
            return '<i class="sicon-sar"></i>';
        }
        if (this.language === 'ar' || !this.arabicCurrencies.includes(currencyCode)) {
            return this.getCurrency(currencyCode).symbol;
        }
        return currencyCode;
    }
    getCurrencyName(currencyCode) {
        return this.language === 'ar' ? this.getCurrency(currencyCode).ar : this.getCurrency(currencyCode).en;
    }
    async getLanguages() {
        return this.languages.length > 1 ? null : await Salla.config.languages().then(data => this.languages = data);
    }
    async getCurrencies() {
        return this.currencies.length > 1 ? null : await Salla.config.currencies().then(data => this.currencies = Object.values(data || {}));
    }
    onChangeCurrency(event) {
        this.currency = event.target.value;
    }
    onChangeLanguage(event) {
        this.language = event.target.value;
    }
    /**
     * Change currency and language to the selected ones.
     */
    async submit() {
        let url;
        this.btn.load()
            .then(() => {
            if (!this.currency) {
                Salla.log('There is no currency!');
                return;
            }
            if (this.currency === Salla.config.get('user.currency_code', 'SAR')) {
                return;
            }
            url = window.location.href;
            return Salla.currency.api.change(this.currency);
        })
            .then(() => {
            if (this.language !== Salla.config.get('user.language_code', 'ar')) {
                url = Salla.helpers.addParamToUrl('lang', this.language);
            }
        })
            .then(() => {
            Salla.cookie.set('s-lang', this.language);
            Salla.cookie.set('s-curr', this.currency);
        })
            .then(() => this.btn.stop())
            .then(() => this.close())
            .then(() => {
            if (url) {
                window.location.href = url.replace(`/${Salla.config.get('user.language_code')}/`, `/${this.language}/`);
            }
        });
    }
    render() {
        return [
            this.showTrigger
                ? index.h("button", { type: "button", onClick: () => this.open(), class: "s-localization-modal-trigger-btn" }, index.h("span", null, this.getLanguageName()), index.h("span", { class: "s-localization-modal-trigger-separator" }, "|"), " ", index.h("span", { innerHTML: this.getCurrencySymbol() }))
                : '',
            index.h("salla-modal", { key: '13b805dc33b57d433d4c35ad8217adef60b99ad5', isLoading: true, class: "s-hidden", ref: modal => this.modal = modal, width: "xs" }, index.h("div", { key: 'b30239d0a20d15baccb6a5017493d91ae96c350c', slot: 'loading' }, index.h("div", { key: '94f7df4044f94612413f4818b110abae3c251075', class: "s-localization-modal-skeleton" }, index.h("salla-skeleton", { key: '63008e2fd90cfa4ce9ddbf313ffe718c520853ce', width: '25%', height: '15px' }), index.h("div", { key: '97f64f98e99c3cc2f099fa02469a2000c7eefc4c', class: "s-localization-modal-skeleton-content" }, [...Array(4)].map(() => index.h("div", { class: "s-localization-modal-skeleton-item" }, index.h("div", { class: "s-localization-modal-skeleton-item-flex" }, index.h("salla-skeleton", { type: 'circle', height: '16px', width: '16px' }), index.h("salla-skeleton", { height: '10px', width: '100px' })), index.h("salla-skeleton", { height: '15px', width: '20px' })))), index.h("salla-skeleton", { key: '230480a6cfaddab7fbe70a16041cf5fb8903c64a', width: '25%', height: '15px' }), index.h("div", { key: 'caf3e79cdbd04d5374365173212792abfe3d465b', class: "s-localization-modal-skeleton-content" }, [...Array(4)].map(() => index.h("div", { class: "s-localization-modal-skeleton-item" }, index.h("div", { class: "s-localization-modal-skeleton-item-flex" }, index.h("salla-skeleton", { type: 'circle', height: '16px', width: '16px' }), index.h("salla-skeleton", { height: '10px', width: '100px' })), index.h("salla-skeleton", { height: '15px', width: '20px' })))), index.h("salla-skeleton", { key: 'b48d02c6e7febad77dbd0d37e540d02d26265e8b', height: '40px', width: '100%' }))), !!this.hasError ?
                index.h("salla-placeholder", { alignment: "center" }, index.h("span", { slot: "description" }, this.errorMessage)) :
                index.h("div", { class: "s-localization-modal-inner" }, this.languages.length > 1 ?
                    index.h("div", { class: "s-localization-modal-section" }, index.h("label", { class: "s-localization-modal-title" }, Salla.lang.get('common.titles.language')), index.h("div", { class: "s-localization-modal-section-inner" }, this.languages.length < 6 ?
                        this.languages.map(lang => index.h("div", { class: "s-localization-modal-item" }, index.h("input", { class: "s-localization-modal-input", type: "radio", checked: this.language == lang.iso_code, onChange: () => this.language = lang.iso_code, name: "language", id: 'lang-' + lang.code.toLowerCase(), value: lang.code }), index.h("div", { class: "s-localization-modal-label-slot", id: "language-slot", innerHTML: this.languageSlot
                                .replace(/\{name\}/g, lang.name)
                                .replace(/\{code\}/g, lang.code)
                                .replace(/\{country_code\}/g, lang.country_code) }))) :
                        index.h("select", { class: "s-localization-modal-select", name: "language", onChange: e => this.onChangeLanguage(e) }, this.languages.map(lang => index.h("option", { value: lang.code, selected: this.language == lang.code }, lang.name)))))
                    : '', this.currencies.length > 1 ?
                    index.h("div", { class: "s-localization-modal-section" }, index.h("label", { class: "s-localization-modal-title" }, Salla.lang.get('common.titles.currency')), index.h("div", { class: "s-localization-modal-section-inner" }, this.currencies.length < 6 ?
                        this.currencies.map(currency => index.h("div", { class: "s-localization-modal-item" }, index.h("input", { class: "s-localization-modal-input", type: "radio", name: "currency", checked: this.currency == currency.code, onChange: () => this.currency = currency.code, id: 'currency-' + currency.code, value: currency.code }), index.h("div", { class: "s-localization-modal-label-slot", id: "currency-slot", innerHTML: this.currencySlot
                                .replace(/\{name\}/g, this.getCurrencyName(currency.code))
                                .replace(/\{code\}/g, currency.code)
                                .replace(/\{symbol\}/g, this.getCurrencySymbol(currency.code))
                                .replace(/\{country_code\}/g, currency.country_code) }))) :
                        index.h("select", { class: "s-localization-modal-select", name: "currency", onChange: e => this.onChangeCurrency(e) }, this.currencies.map(currency => index.h("option", { value: currency.code, selected: this.currency == currency.code }, currency.name)))))
                    : '', index.h("salla-button", { width: "wide", ref: btn => this.btn = btn, onClick: () => this.submit() }, Salla.lang.get('common.elements.ok'))))
        ];
    }
    /**
     * to reduce dom levels we will move slot data into the parent dom
     */
    componentDidRender() {
        this.host.querySelectorAll('#currency-slot').forEach(el => el.replaceWith(el.firstChild));
        this.host.querySelectorAll('#language-slot').forEach(el => el.replaceWith(el.firstChild));
    }
    get host() { return index.getElement(this); }
};

exports.salla_localization_modal = SallaLocalizationModal;
