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

var index = require('./index-vstkdqRz.js');
var iphoneX = require('./iphone-x-qC21wCLj.js');
var mail = require('./mail-Bgvt2hc9.js');
var cancel = require('./cancel-B5SbMYEk.js');

var CelebrationIcon = `<!-- 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>party-horn</title>
<path fill="currentColor" d="M5.333 4.013c0.736 0 1.333-0.596 1.333-1.333v-0.013c0-0.737-0.597-1.327-1.333-1.327s-1.333 0.603-1.333 1.34 0.597 1.333 1.333 1.333zM11.333 10c0.341 0 0.683-0.131 0.943-0.391 1.541-1.54 2.391-3.589 2.391-5.771v-2.505c0-0.737-0.597-1.333-1.333-1.333s-1.333 0.596-1.333 1.333v2.505c0 1.468-0.572 2.848-1.609 3.885-0.521 0.521-0.521 1.364 0 1.885 0.26 0.26 0.601 0.391 0.943 0.391zM18.667 9.993c0.319 0 0.639-0.115 0.895-0.345 0.383-0.347 0.684-0.325 1.497-0.22 0.923 0.124 2.319 0.307 3.636-0.887 1.293-1.172 1.303-2.54 1.308-3.539 0.005-0.887 0.043-1.228 0.432-1.581 0.361-0.327 0.621-0.335 1.493-0.216 0.923 0.12 2.317 0.307 3.635-0.884 0.545-0.495 0.587-1.337 0.093-1.883-0.493-0.547-1.336-0.589-1.884-0.093-0.361 0.325-0.621 0.333-1.493 0.216-0.921-0.119-2.317-0.305-3.635 0.884-1.293 1.173-1.303 2.541-1.308 3.54-0.005 0.885-0.043 1.227-0.432 1.58-0.383 0.348-0.683 0.327-1.497 0.22-0.924-0.124-2.32-0.305-3.636 0.887-0.545 0.495-0.587 1.339-0.092 1.884 0.264 0.291 0.625 0.437 0.988 0.437zM18.667 16.013c0.736 0 1.333-0.596 1.333-1.333v-0.013c0-0.737-0.597-1.327-1.333-1.327s-1.333 0.603-1.333 1.34 0.597 1.333 1.333 1.333zM30.667 17.333h-2.505c-2.179 0-4.228 0.849-5.771 2.391-0.521 0.521-0.521 1.364 0 1.885 0.26 0.26 0.603 0.391 0.944 0.391s0.683-0.131 0.943-0.391c1.023-1.023 2.439-1.609 3.884-1.609h2.505c0.736 0 1.333-0.596 1.333-1.333s-0.597-1.333-1.333-1.333zM30.667 10.66c-0.736 0-1.333 0.603-1.333 1.34s0.597 1.333 1.333 1.333 1.333-0.596 1.333-1.333v-0.013c0-0.736-0.597-1.327-1.333-1.327zM29.333 26.66c-0.736 0-1.333 0.603-1.333 1.34s0.597 1.333 1.333 1.333 1.333-0.596 1.333-1.333v-0.013c0-0.736-0.597-1.327-1.333-1.327zM7.456 11.057c-0.327-0.327-0.799-0.46-1.249-0.356-0.449 0.107-0.812 0.439-0.959 0.876l-5.036 15.113c-0.487 1.457-0.113 3.037 0.973 4.125 0.772 0.771 1.792 1.183 2.84 1.183 0.428 0 0.861-0.068 1.284-0.209l15.112-5.037c0.439-0.145 0.769-0.508 0.876-0.959 0.107-0.449-0.028-0.921-0.355-1.249zM4.467 29.259c-0.503 0.163-1.023 0.043-1.395-0.329-0.373-0.373-0.497-0.896-0.329-1.396l4.355-13.065 10.436 10.435z"></path>
</svg>
`;

var PortraitIcon = `<!-- 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>portrait</title>
<path d="M24 1.333h-16c-3.676 0-6.667 2.991-6.667 6.667v16c0 3.028 2.041 5.561 4.811 6.371 0.004 0.001 0.008 0.003 0.012 0.004 0.591 0.172 1.2 0.292 1.844 0.292h16c0.644 0 1.253-0.12 1.843-0.292 0.004-0.001 0.008-0.003 0.012-0.004 2.771-0.809 4.812-3.343 4.812-6.371v-16c0-3.676-2.991-6.667-6.667-6.667zM8.012 28c0.121-1.915 3.363-4 7.988-4s7.868 2.085 7.988 4zM28 24c0 1.24-0.579 2.335-1.467 3.069-0.768-3.288-5.112-5.736-10.533-5.736s-9.765 2.448-10.533 5.736c-0.888-0.735-1.467-1.829-1.467-3.069v-16c0-2.205 1.795-4 4-4h16c2.205 0 4 1.795 4 4zM16 6.667c-3.308 0-6 2.692-6 6s2.692 6 6 6 6-2.692 6-6-2.692-6-6-6zM16 16c-1.839 0-3.333-1.495-3.333-3.333s1.495-3.333 3.333-3.333 3.333 1.495 3.333 3.333-1.495 3.333-3.333 3.333z"></path>
</svg>
`;

const sallaQuickOrderCss = ".s-quick-order-expandable:not(.s-quick-order-shown){overflow:hidden}";

const SallaQuickOrder = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.quickOrderSubmited = index.createEvent(this, "quickOrderSubmited");
        /**
         * quick order title
         */
        this.quickOrderTitle = 'ليش تنتظر؟';
        /**
         * quick order sub title
         */
        this.subTitle = 'احصل على المنتج مباشرة الآن';
        /**
         * quick order pay button text
         */
        this.payButtonTitle = 'اطلب المنتج';
        /**
         * quick order confirm pay button text
         */
        this.confirmPayButtonTitle = 'اشتر الآن';
        /**
         * agreement text from server or from props
         */
        this.agreementText = salla.lang.get('pages.checkout.show_full_agreement');
        /**
         * is email required
         */
        this.isEmailRequired = false;
        /**
         * Quick Order Style
         */
        this.quickOrderStyle = 'default';
        this.isAvailable = false;
        this.oneClick = false;
        this.expanded = false;
        this.isTermsRequired = false;
        this.countryCode = salla.config.get('user.country_code', 'SA') || 'SA';
        this.submitSucess = false;
        //Langugae states
        this.placeHolderEmail = salla.lang.get('common.elements.email');
        this.emailOptional = salla.lang.get('common.elements.optional');
        this.agreementShowText = salla.lang.get('pages.checkout.show_full_agreement');
        this.agreementModalHead = salla.lang.get('pages.checkout.full_agreement');
        this.userNameLabel = salla.lang.get('pages.products.your_name');
        this.termsChecked = false;
        salla.onReady(() => {
            this.productId = this.productId || salla.config.get('page.id');
        });
        salla.lang.onLoaded(() => {
            this.placeHolderEmail = salla.lang.get('common.elements.email');
            this.emailOptional = salla.lang.get('common.elements.optional');
            this.agreementShowText = salla.lang.get('pages.checkout.show_full_agreement');
            this.agreementModalHead = salla.lang.get('pages.checkout.full_agreement');
            this.userNameLabel = salla.lang.get('pages.products.your_name');
        });
    }
    getBtnColor() {
        return this.quickOrderStyle === 'default' ? 'light' : 'primary';
    }
    getErrorMessage(type, name) {
        return name == 'terms'
            ? salla.lang.get('pages.checkout.check_agreement')
            : salla.lang.get(`common.errors.${type}`, { attribute: name == 'name' ? this.userNameLabel : this.placeHolderEmail });
    }
    handleInvalidInput(e) {
        let input = e.target;
        let validity = input.validity;
        let errorMessage;
        if (validity.valueMissing) {
            errorMessage = this.getErrorMessage('field_required', input.name);
            console.log(this.getErrorMessage('field_required', input.name));
        }
        else if (validity.typeMismatch) {
            errorMessage = this.getErrorMessage('invalid_value', input.name);
        }
        input.setCustomValidity(errorMessage);
    }
    async setWrapperHeight() {
        let expandable = this.host.querySelector('.s-quick-order-expandable');
        setTimeout(() => {
            if (expandable.style.maxHeight || this.oneClick) {
                expandable.style.maxHeight = null;
            }
            else {
                expandable.style.maxHeight = expandable.scrollHeight + "px";
            }
        }, 50);
    }
    getDarkOrLight() {
        return this.quickOrderStyle === 'default' && salla.config.get('theme.color.is_dark') ? 'dark' : 'light';
    }
    getStyleColor() {
        return {
            gray: '#f3f3f3',
            white: '#ffffff',
            default: salla.config.get('theme.color.primary'),
        }[this.quickOrderStyle] || '#f3f3f3';
    }
    async submit(e, checkOneClick = false) {
        e.preventDefault();
        if (checkOneClick && !this.oneClick) {
            this.expanded = !this.expanded;
            this.setWrapperHeight();
            return;
        }
        return this.submitBtn.load()
            .then(() => this.getPayload())
            .then((payload) => salla.api.cart.createQuickOrder(payload))
            .then(() => {
            setTimeout(() => {
                this.submitBtn.stop();
                this.submitSucess = true;
                this.quickOrderSubmited.emit();
            }, 200);
        })
            .catch(error => error && (console.error(error), this.submitBtn.stop()));
    }
    async getPayload() {
        if (this.oneClick) {
            return {
                product_ids: [this.productId],
                agreement: true,
            };
        }
        return {
            product_ids: [this.productId],
            email: this.emailInput?.value,
            phone: Number((await this.phoneInput?.getValues())?.phone),
            country_code: (await this.phoneInput?.getValues())?.countryCode || this.countryCode,
            name: this.nameInput?.value,
            agreement: this.termsChecked,
        };
    }
    formatAgreementText(agreement_text, length = 150) {
        if (!agreement_text)
            return '';
        if (agreement_text.length <= length)
            return agreement_text;
        const parsedToDOM = new DOMParser().parseFromString(agreement_text, 'text/html');
        return parsedToDOM.documentElement.innerText.substring(0, length) + '...';
    }
    loadQuickOrderSettings() {
        let data = salla.config.get('store.settings.quick_order');
        if (!data) {
            return Promise.resolve();
        }
        this.user = salla.config.get('user') || salla.storage.get('user') || {};
        this.countryCode = this.user?.country_code || this.countryCode;
        // make email required if user is gust or is required from server
        this.isEmailRequired = this.user?.email ? false : this.isEmailRequired;
        // check if one click is available
        this.oneClick = this.user?.email;
        this.initComponentData(data);
        return Promise.resolve();
        // return salla.api.withoutNotifier(() => salla.api.cart.getQuickOrderSettings().then(res => this.initComponentData(res.data)));
    }
    initComponentData(data) {
        this.quickOrderTitle = data.title;
        this.subTitle = data.sub_title;
        this.payButtonTitle = data.order_now_button;
        this.isEmailRequired = data.is_email_required;
        this.isTermsRequired = data.show_agreement;
        this.agreementText = data.agreement;
        this.confirmPayButtonTitle = data.confirm_button;
        this.thanksMessage = data.thanks_message;
        this.quickOrderStyle = data.style;
        this.isAvailable = true;
        // toggle oneClick if true
        this.oneClick = this.oneClick && !this.isTermsRequired;
    }
    componentWillLoad() {
        return new Promise(resolve => salla.onReady(() => this.loadQuickOrderSettings().then(resolve)));
    }
    render() {
        if (!this.isAvailable) {
            return;
        }
        if (this.submitSucess) {
            return (index.h(index.Host, { class: "s-quick-order" }, index.h("div", { class: 's-quick-order-confirm', style: {
                    backgroundColor: salla.config.get('theme.color.primary') + '10',
                    borderColor: salla.config.get('theme.color.primary') + '10',
                    color: salla.config.get('theme.color.primary')
                } }, index.h("i", { innerHTML: CelebrationIcon }), index.h("span", null, this.thanksMessage))));
        }
        return (index.h(index.Host, { class: `s-quick-order s-quick-order-${this.getDarkOrLight()}` }, index.h("div", { class: `s-quick-order-container s-quick-order-${this.quickOrderStyle}`, style: { backgroundColor: this.getStyleColor() } }, index.h("div", { class: "s-quick-order-button-cont" }, index.h("div", null, index.h("h3", null, this.quickOrderTitle), index.h("p", null, this.subTitle)), index.h("salla-button", { class: this.expanded ? "s-quick-order-btn-close" : "", onClick: (e) => this.submit(e, true), color: this.getBtnColor() }, this.oneClick
            ? this.confirmPayButtonTitle : this.expanded ? index.h("i", { innerHTML: cancel.SICancel }) : this.confirmPayButtonTitle)), index.h("form", { onSubmit: (e) => this.submit(e), class: 's-quick-order-expandable ' + (this.expanded ? 's-quick-order-shown' : '') }, Salla.config.isGuest() &&
            [
                index.h("div", { class: "s-form-group" }, index.h("span", { innerHTML: PortraitIcon }), index.h("input", { type: "text", required: true, class: "s-form-control s-quick-order-phone-field", name: 'name', placeholder: this.userNameLabel, ref: el => (this.nameInput = el) })),
                index.h("div", { class: "s-quick-order-flex-input" }, index.h("div", { class: "s-form-group" }, index.h("span", { innerHTML: iphoneX.SIiPhoneX }), index.h("salla-tel-input", { ref: el => (this.phoneInput = el) })), index.h("div", { class: "s-form-group" }, index.h("span", { innerHTML: mail.SIMail }), index.h("input", { type: "email", class: "s-form-control s-quick-order-email-field", name: 'email', required: this.isEmailRequired, placeholder: this.placeHolderEmail + ' ' + (this.isEmailRequired ? '' : this.emailOptional), ref: el => (this.emailInput = el) }))),
            ], this.isTermsRequired && (index.h("label", { htmlFor: "terms", class: "s-quick-order-terms" }, index.h("input", { type: "checkbox", required: true, name: 'terms', id: 'terms', ref: el => (this.termsInput = el), onChange: () => (this.termsChecked = this.termsInput.checked), class: "s-checkbox" }), index.h("span", { class: "s-form-label" }, " ", index.h("div", { innerHTML: this.formatAgreementText(this.agreementText, 150) }, this.agreementText.length > 150 && (index.h("salla-button", { shape: "link", onClick: () => this.agreementModal.open() }, this.agreementShowText))), " "))), index.h("salla-button", { type: "submit", color: this.getBtnColor(), width: "wide", ref: el => (this.submitBtn = el) }, this.payButtonTitle)), index.h("salla-modal", { "modal-title": this.agreementModalHead, ref: modal => (this.agreementModal = modal) }, index.h("article", { innerHTML: this.agreementText })))));
    }
    componentDidLoad() {
        this.host.querySelectorAll('input').forEach(input => {
            input.addEventListener('invalid', e => {
                this.handleInvalidInput(e);
            });
            input.addEventListener('input', () => {
                input.setCustomValidity('');
                input.reportValidity();
            });
        });
    }
    get host() { return index.getElement(this); }
};
SallaQuickOrder.style = sallaQuickOrderCss;

exports.salla_quick_order = SallaQuickOrder;
