/*!
 * Crafted with ❤ by Salla
 */
import { proxyCustomElement, HTMLElement, h, Host } from '@stencil/core/internal/client';
import { d as defineCustomElement$6, g as getOrderItemSelectedOptions, a as getOrderEditProductMaxQuantity, c as clampOrderEditQuantity, u as updateOrderItems, r as removeOrderItems, m as mergePayloadItems, b as cloneOrderEditProduct, f as findMergeableItem, e as updateAddedPayloadList, h as upsertPayloadUpdateList, i as createAddedOrderItem, j as buildSavePayload } from './salla-order-edit-item2.js';
import { d as defineCustomElement$g } from './salla-booking-field2.js';
import { d as defineCustomElement$f } from './salla-button2.js';
import { d as defineCustomElement$e } from './salla-color-picker2.js';
import { d as defineCustomElement$d } from './salla-conditional-fields2.js';
import { d as defineCustomElement$c } from './salla-count-down2.js';
import { d as defineCustomElement$b } from './salla-datetime-picker2.js';
import { d as defineCustomElement$a } from './salla-file-upload2.js';
import { d as defineCustomElement$9 } from './salla-loading2.js';
import { d as defineCustomElement$8 } from './salla-map2.js';
import { d as defineCustomElement$7 } from './salla-modal2.js';
import { d as defineCustomElement$5 } from './salla-product-options2.js';
import { d as defineCustomElement$4 } from './salla-products-list2.js';
import { d as defineCustomElement$3 } from './salla-progress-bar2.js';
import { d as defineCustomElement$2 } from './salla-quantity-input2.js';

const sallaOrderEditCss = ":host{display:block}";

const SallaOrderEdit$1 = /*@__PURE__*/ proxyCustomElement(class SallaOrderEdit extends HTMLElement {
    constructor() {
        super();
        this.__registerHost();
        this.loading = true;
        this.saveLoading = false;
        this.payload = { items: { update: [], remove: [], add: [] } };
        this.expired = false;
        this.editPreview = null;
        this.productSearchQuery = '';
        this.productsListKey = 0;
        this.productsListSource = 'latest';
        this.productsListSourceValue = '';
        this.selectedProductToAdd = null;
        this.addProductQuantity = 1;
        this.addProductLoading = false;
        this.addProductConfirmLoading = false;
        this.mobileProductsModalMounted = false;
        this.isMobileViewport = false;
        // Plain field (not @State): scroll-loading guard never affects rendering, so avoid re-render churn.
        this.mobileProductsListLoading = false;
        this.confirming = false;
        this.handleMobileProductSelected = (event) => {
            event.stopPropagation();
            void this.handleProductSelected(event);
        };
        this.productsPanelMobileQuery = '(max-width: 768px)';
        this.handleProductsPanelViewportChange = (event) => {
            this.isMobileViewport = event.matches;
        };
        this.hasProductTypeFilter = (url) => {
            const queryStart = url.indexOf('?');
            const query = (queryStart >= 0 ? url.slice(queryStart + 1) : url).split('#')[0];
            return Array.from(new URLSearchParams(query)).some(([key, value]) => (value === 'product' &&
                /^filters\[types\](?:\[(?:\d*)\])?$/.test(key)));
        };
        this.normalizeProductsListArrayParams = (url) => {
            return url.replace(/(^|[?&])(includes|source_value|filters(?:\[|%5B)[^&=\]%]+?(?:\]|%5D))(\[|%5B)\d+(\]|%5D)(?==)/gi, (_, sep, name, open, close) => `${sep}${name}${open}${close}`);
        };
        this.handleBeforeBuildListUrl = (ctx) => {
            if (ctx.component?.productCardComponent !== 'salla-order-edit-product-card' ||
                typeof ctx.url !== 'string') {
                return;
            }
            ctx.url = this.normalizeProductsListArrayParams(ctx.url);
            if (this.hasProductTypeFilter(ctx.url)) {
                return;
            }
            ctx.url += `${ctx.url.includes('?') ? '&' : '?'}filters[types][]=product`;
        };
        this.defaultProductsListSource = 'latest';
        this.debouncedProductSearch = salla.helpers.debounce((query) => this.applyProductSearch(query), 500);
    }
    async componentWillLoad() {
        this.setupProductsPanelViewportQuery();
        await salla.onReady();
        this.unregisterBeforeBuildListUrlHook = salla.hooks.registerHook('salla-products-list', 'beforeBuildListUrl', this.handleBeforeBuildListUrl);
        this.loadFromProp();
        this.startExpiryCheck();
    }
    disconnectedCallback() {
        clearInterval(this.expiryInterval);
        this.unregisterBeforeBuildListUrlHook?.();
        this.productsPanelViewportQuery?.removeEventListener('change', this.handleProductsPanelViewportChange);
        this.mobileProductsModal?.removeEventListener('orderEditProductSelected', this.handleMobileProductSelected);
    }
    setupProductsPanelViewportQuery() {
        if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
            return;
        }
        this.productsPanelViewportQuery = window.matchMedia(this.productsPanelMobileQuery);
        this.isMobileViewport = this.productsPanelViewportQuery.matches;
        this.productsPanelViewportQuery.addEventListener('change', this.handleProductsPanelViewportChange);
    }
    startExpiryCheck() {
        const endsAt = this.order?.customer_editing_session?.ends_at;
        if (!endsAt)
            return;
        const isExpired = () => new Date(`${endsAt.replace(' ', 'T')}+03:00`).getTime() <= Date.now();
        if (isExpired()) {
            this.expired = true;
            return;
        }
        this.expiryInterval = setInterval(() => {
            if (isExpired()) {
                this.expired = true;
                clearInterval(this.expiryInterval);
            }
        }, 1000);
    }
    loadFromProp() {
        try {
            if (!this.orderData) {
                this.error = salla.lang.getWithDefault('pages.orders.order_not_found', 'الطلب غير موجود');
                return;
            }
            const data = typeof this.orderData === 'string' ? JSON.parse(this.orderData) : this.orderData;
            this.order = {
                ...data,
                items: data.items.map(item => ({
                    ...item,
                    selectedOptions: getOrderItemSelectedOptions(item),
                })),
            };
        }
        catch (e) {
            this.error = salla.lang.getWithDefault('pages.orders.order_not_found', 'الطلب غير موجود');
        }
        finally {
            this.loading = false;
        }
    }
    applyProductSearch(query) {
        const normalizedQuery = query?.trim() || '';
        const nextSource = normalizedQuery ? 'search' : this.defaultProductsListSource;
        const nextSourceValue = nextSource === 'search' ? JSON.stringify(normalizedQuery) : '';
        if (this.productsListSource === nextSource &&
            this.productsListSourceValue === nextSourceValue) {
            return;
        }
        this.productsListSource = nextSource;
        this.productsListSourceValue = nextSourceValue;
        this.productsListKey += 1;
    }
    handleProductSearch(event) {
        const value = event.target?.value || '';
        this.productSearchQuery = value;
        this.debouncedProductSearch(value);
    }
    getProductsListKey(scope) {
        return `${scope}-${this.productsListSource}-${this.productsListSourceValue}-${this.productsListKey}`;
    }
    handleMobileProductsScroll(event) {
        const container = event.currentTarget;
        const distanceToBottom = container.scrollHeight - container.scrollTop - container.clientHeight;
        if (distanceToBottom > 200 || this.mobileProductsListLoading) {
            return;
        }
        const productsList = container.querySelector('salla-products-list');
        if (!productsList) {
            return;
        }
        this.mobileProductsListLoading = true;
        void productsList.loadMore().finally(() => {
            this.mobileProductsListLoading = false;
        });
    }
    waitForNextFrame() {
        return new Promise(resolve => requestAnimationFrame(() => resolve(undefined)));
    }
    async openMobileProductsModal() {
        if (!this.mobileProductsModalMounted) {
            this.mobileProductsModalMounted = true;
            await this.waitForNextFrame();
        }
        await this.mobileProductsModal?.open?.();
    }
    setMobileProductsModal(modal) {
        if (this.mobileProductsModal === modal) {
            return;
        }
        this.mobileProductsModal?.removeEventListener('orderEditProductSelected', this.handleMobileProductSelected);
        this.mobileProductsModal = modal;
        this.mobileProductsModal?.addEventListener('orderEditProductSelected', this.handleMobileProductSelected);
    }
    resetAddProductDrawer() {
        this.selectedProductToAdd = null;
        this.addProductQuantity = 1;
        this.addProductLoading = false;
        this.addProductConfirmLoading = false;
        this.addProductOptions = null;
    }
    getAddProductMaxQuantity(product = this.selectedProductToAdd) {
        return getOrderEditProductMaxQuantity(product);
    }
    clampAddProductQuantity(quantity, product = this.selectedProductToAdd) {
        return clampOrderEditQuantity(quantity, this.getAddProductMaxQuantity(product));
    }
    getApiErrorMessage(error) {
        return error?.response?.data?.error?.message || error?.response?.data?.message;
    }
    notifyApiError(error) {
        const message = this.getApiErrorMessage(error);
        if (message) {
            salla.notify.error(message);
        }
    }
    async validateAddProductOptions() {
        if (!this.selectedProductToAdd?.options?.length) {
            return true;
        }
        if (!this.addProductOptions) {
            return false;
        }
        return ((await this.addProductOptions.validateAndScroll?.()) ??
            (await this.addProductOptions.reportValidity?.()) ??
            false);
    }
    updateLocalOrderItem(itemId, quantity, optionDefinitions, selectedOptions) {
        this.order = {
            ...this.order,
            items: updateOrderItems(this.order.items, itemId, quantity, optionDefinitions, selectedOptions),
        };
    }
    removeLocalOrderItem(itemId) {
        this.order = {
            ...this.order,
            items: removeOrderItems(this.order.items, itemId),
        };
    }
    setPayloadItems(patch) {
        this.payload = {
            ...this.payload,
            items: mergePayloadItems(this.payload.items, patch),
        };
    }
    handleAddProductQuantityChange(event) {
        const detail = event.detail;
        const newQuantity = detail?.quantity ?? parseInt(event.target?.value, 10);
        if (isNaN(newQuantity) || newQuantity < 1) {
            return;
        }
        this.addProductQuantity = this.clampAddProductQuantity(newQuantity);
    }
    async handleProductSelected(event) {
        const product = event.detail?.product;
        if (!product?.id || this.addProductLoading) {
            return;
        }
        this.addProductLoading = true;
        try {
            this.selectedProductToAdd = cloneOrderEditProduct(product);
            this.addProductQuantity = 1;
            await this.mobileProductsModal?.close?.();
            await this.waitForNextFrame();
            await this.addProductDrawer?.open?.();
        }
        catch (error) {
            this.notifyApiError(error);
        }
        finally {
            this.addProductLoading = false;
        }
    }
    async confirmAddProduct() {
        if (!this.selectedProductToAdd?.id) {
            return;
        }
        if (this.addProductConfirmLoading) {
            return;
        }
        this.addProductConfirmLoading = true;
        try {
            const maxQuantity = this.getAddProductMaxQuantity();
            const normalizedQuantity = this.clampAddProductQuantity(this.addProductQuantity);
            if (normalizedQuantity !== this.addProductQuantity) {
                this.addProductQuantity = normalizedQuantity;
            }
            const productOptions = this.addProductOptions;
            const optionsAreValid = await this.validateAddProductOptions();
            if (!optionsAreValid) {
                salla.notify.error(salla.lang.getWithDefault('common.messages.required_fields', 'يرجى تعبئة الحقول المطلوبة'));
                return;
            }
            const selectedOptionsPayload = (await productOptions?.getSelectedOptionsData?.()) || {};
            const optionDefinitions = (await productOptions?.getOptionsData?.()) ||
                this.selectedProductToAdd.options ||
                [];
            const existingItem = findMergeableItem(this.order?.items, this.selectedProductToAdd.id, selectedOptionsPayload);
            if (existingItem) {
                const mergedQuantity = clampOrderEditQuantity(existingItem.quantity + normalizedQuantity, maxQuantity);
                this.updateLocalOrderItem(existingItem.id, mergedQuantity, optionDefinitions, selectedOptionsPayload);
                if (existingItem.isNew) {
                    this.setPayloadItems({
                        add: updateAddedPayloadList(this.payload.items.add, existingItem.id, mergedQuantity, selectedOptionsPayload),
                    });
                }
                else {
                    this.setPayloadItems({
                        update: upsertPayloadUpdateList(this.payload.items.update, existingItem.id, mergedQuantity, selectedOptionsPayload),
                    });
                }
                await this.addProductDrawer?.close?.();
                return;
            }
            const newItem = createAddedOrderItem(this.selectedProductToAdd, normalizedQuantity, optionDefinitions, selectedOptionsPayload);
            const addEntry = {
                itemId: newItem.id,
                product_id: this.selectedProductToAdd.id,
                quantity: normalizedQuantity,
                options: selectedOptionsPayload,
            };
            this.order = {
                ...this.order,
                items: [...this.order.items, newItem],
            };
            this.setPayloadItems({
                add: [...this.payload.items.add, addEntry],
            });
            await this.addProductDrawer?.close?.();
        }
        catch (error) {
            this.notifyApiError(error);
        }
        finally {
            this.addProductConfirmLoading = false;
        }
    }
    handleItemUpdated(event) {
        if (!this.order)
            return;
        const { itemId, quantity, options, optionDefinitions } = event.detail;
        const currentItem = this.order.items.find(item => item.id === itemId);
        if (!currentItem) {
            return;
        }
        const safeQuantity = clampOrderEditQuantity(quantity, getOrderEditProductMaxQuantity(currentItem.product));
        if (currentItem.isNew) {
            this.setPayloadItems({
                add: updateAddedPayloadList(this.payload.items.add, itemId, safeQuantity, options),
            });
            this.updateLocalOrderItem(itemId, safeQuantity, optionDefinitions, options);
            return;
        }
        this.setPayloadItems({
            update: upsertPayloadUpdateList(this.payload.items.update, itemId, safeQuantity, options ?? {}),
        });
        this.updateLocalOrderItem(itemId, safeQuantity, optionDefinitions, options);
    }
    handleItemRemoved(event) {
        if (!this.order)
            return;
        if (this.order.items.length <= 1) {
            salla.notify.error(salla.lang.getWithDefault('pages.orders.order_cannot_be_empty', 'لا يمكن إزالة جميع المنتجات من الطلب'));
            return;
        }
        const { itemId } = event.detail;
        const currentItem = this.order.items.find(item => item.id === itemId);
        if (!currentItem) {
            return;
        }
        if (currentItem.isNew) {
            this.setPayloadItems({
                add: this.payload.items.add.filter(item => item.itemId !== itemId),
            });
            this.removeLocalOrderItem(itemId);
            return;
        }
        this.setPayloadItems({
            update: this.payload.items.update.filter(u => u.id !== itemId),
            remove: [...this.payload.items.remove, itemId],
        });
        this.removeLocalOrderItem(itemId);
    }
    get hasChanges() {
        return (this.payload.items.update.length > 0 ||
            this.payload.items.remove.length > 0 ||
            this.payload.items.add.length > 0);
    }
    async saveOrder() {
        if (!this.hasChanges)
            return;
        this.saveLoading = true;
        try {
            const response = await salla.order.api.editOrder(this.orderId, buildSavePayload(this.payload));
            this.editPreview = response?.data?.data || response?.data;
            await this.saveModal?.open?.();
        }
        catch (error) {
            this.notifyApiError(error);
        }
        finally {
            this.saveLoading = false;
        }
    }
    navigateToOrder() {
        const url = new URL(window.location.href);
        url.pathname = url.pathname.replace(/\/edit\/?$/, '');
        url.search = '';
        window.location.href = url.href;
    }
    handleConfirm() {
        this.confirming = true;
        if (this.editPreview?.payment?.required && this.editPreview.payment.payment_url) {
            window.location.href = this.editPreview.payment.payment_url;
        }
        else {
            this.navigateToOrder();
        }
    }
    async cancelEditSession() {
        try {
            await salla.order.api.cancelEditSession(this.orderId);
            this.navigateToOrder();
        }
        catch (error) {
            this.notifyApiError(error);
        }
    }
    renderProductsPanel() {
        const addProductTitle = salla.lang.getWithDefault('pages.orders.add_product_to_order', 'أضف منتج للطلب');
        return (h("section", { class: "s-order-edit-products-panel" }, h("div", { class: "s-order-edit-products-header" }, h("h2", { class: "s-order-edit-products-title" }, addProductTitle)), this.renderProductsPickerContent('panel')));
    }
    renderProductsPickerContent(scope) {
        return (h("div", { class: {
                's-order-edit-products-picker': true,
                's-order-edit-products-modal-content': scope === 'modal',
            } }, h("label", { class: "s-order-edit-products-search" }, h("i", { class: "sicon-search" }), h("input", { type: "search", class: "s-order-edit-products-search-input", placeholder: salla.lang.getWithDefault('pages.products.search_for_product', 'ابحث عن منتج'), value: this.productSearchQuery, onInput: event => this.handleProductSearch(event) })), h("div", { class: "s-order-edit-products-list", onScroll: scope === 'modal' ? event => this.handleMobileProductsScroll(event) : undefined }, h("salla-products-list", { key: this.getProductsListKey(scope), includes: ['options'], source: this.productsListSource, "source-value": this.productsListSourceValue, autoload: true, "product-card-component": "salla-order-edit-product-card" }))));
    }
    renderMobileProductsModal() {
        return (h("salla-modal", { ref: modal => this.setMobileProductsModal(modal), width: "md", class: "s-order-edit-mobile-products-modal", "modal-title": salla.lang.getWithDefault('pages.orders.add_product_to_order', 'أضف منتج للطلب'), onModalVisibilityChanged: (e) => {
                if (!e.detail) {
                    this.mobileProductsModalMounted = false;
                }
            } }, this.mobileProductsModalMounted ? this.renderProductsPickerContent('modal') : null));
    }
    renderAddProductDrawer() {
        const product = this.selectedProductToAdd;
        const productName = product?.name || salla.lang.getWithDefault('common.elements.product', 'منتج');
        const price = product?.price;
        const maxQuantity = this.getAddProductMaxQuantity(product);
        const optionsInstanceKey = product ? `order-edit-add-${product.id}` : 'order-edit-add';
        const quantityAttrs = {
            value: this.clampAddProductQuantity(this.addProductQuantity, product),
        };
        if (maxQuantity) {
            quantityAttrs.max = maxQuantity;
        }
        return (h("salla-modal", { ref: drawer => (this.addProductDrawer = drawer), width: "md", "modal-title": salla.lang.getWithDefault('pages.orders.add_product_to_order', 'أضف منتج للطلب'), onModalVisibilityChanged: (e) => {
                if (!e.detail) {
                    this.resetAddProductDrawer();
                }
            } }, h("div", { class: "s-order-edit-add-modal" }, this.addProductLoading ? (h("div", { class: "s-order-edit-add-modal-loading" }, h("salla-loading", null))) : product ? (h("div", { class: "s-order-edit-add-modal-content" }, h("div", { class: "s-order-edit-add-modal-header" }, h("div", { class: "s-order-edit-add-modal-media" }, product.image?.url && (h("img", { src: product.image.url, alt: product.image.alt || productName, class: "s-order-edit-add-modal-image" })), h("div", { class: "s-order-edit-add-modal-details" }, h("h3", { class: "s-order-edit-add-modal-name" }, productName), price != null && (h("span", { class: "s-order-edit-add-modal-price", innerHTML: salla.money(price) }))))), h("div", { class: "s-order-edit-add-modal-quantity" }, h("h3", { class: "s-order-edit-add-modal-section-title" }, salla.lang.getWithDefault('common.elements.quantity', 'الكمية')), h("div", { class: "s-order-edit-add-modal-quantity-input" }, h("salla-quantity-input", { ...quantityAttrs, onChange: event => this.handleAddProductQuantityChange(event) }))), product.options?.length > 0 && (h("form", { onSubmit: e => e.preventDefault() }, h("salla-product-options", { ref: el => (this.addProductOptions = el), "product-id": product.id, "unique-key": optionsInstanceKey, options: JSON.stringify(product.options), key: `${optionsInstanceKey}-options` }))), h("div", { class: "s-order-edit-add-modal-actions" }, h("salla-button", { onClick: () => this.confirmAddProduct(), loading: this.addProductConfirmLoading }, salla.lang.getWithDefault('common.elements.confirm', 'تأكيد')), h("salla-button", { color: "gray", fill: "outline", onClick: () => this.addProductDrawer?.close?.() }, salla.lang.getWithDefault('common.elements.cancel', 'الغاء'))))) : null)));
    }
    renderSaveModal() {
        const preview = this.editPreview;
        const hasRemainingAmount = preview?.totals?.remaining_amount?.amount > 0;
        const hasRefundAmount = preview?.totals?.refund_amount?.amount > 0;
        const taxAmount = preview?.totals?.tax?.amount?.amount;
        return (h("salla-modal", { ref: modal => (this.saveModal = modal), width: "md", onModalVisibilityChanged: async (e) => {
                if (!e.detail) {
                    this.editPreview = null;
                    if (!this.confirming) {
                        await this.cancelEditSession();
                    }
                    this.confirming = false;
                }
            } }, h("div", { class: "s-order-edit-modal" }, h("h2", { class: "s-order-edit-modal-title" }, salla.lang.getWithDefault('pages.orders.edit_summary_title', 'ملخص الطلب بعد التعديل')), preview?.items?.length > 0 && (h("div", { class: "s-order-edit-modal-items" }, preview.items.map(item => {
            const orderItem = this.order?.items?.find(oi => oi.id == item.id);
            const imageUrl = orderItem?.product?.image?.url;
            const optionsLabel = item.options?.join('/ ');
            return (h("div", { class: "s-order-edit-modal-item" }, h("div", { class: "s-order-edit-modal-item-start" }, imageUrl && (h("img", { src: imageUrl, alt: item.name, class: "s-order-edit-modal-item-image" })), h("div", null, h("p", { class: "s-order-edit-modal-item-name" }, item.name), optionsLabel && (h("span", { class: "s-order-edit-modal-item-options" }, optionsLabel)))), h("div", { class: "s-order-edit-modal-item-end" }, h("span", { class: "s-order-edit-modal-item-price", innerHTML: salla.money(item.price.amount) }))));
        }))), preview?.totals?.updated_products_total && (h("div", { class: "s-order-edit-modal-row" }, h("span", { class: "s-order-edit-modal-row-label" }, salla.lang.getWithDefault('pages.orders.modified_products_total', 'مجموع المنتجات المعدلة')), h("span", { class: "s-order-edit-modal-row-value", innerHTML: salla.money(preview.totals.updated_products_total.amount) }))), taxAmount > 0 && (h("div", { class: "s-order-edit-modal-row" }, h("span", { class: "s-order-edit-modal-tax-label" }, h("i", { class: "sicon-info-circle s-order-edit-modal-tax-icon" }), salla.lang.getWithDefault('pages.orders.vat', 'ضريبة القيمة المضافة')), h("span", { class: "s-order-edit-modal-row-value", innerHTML: salla.money(taxAmount) }))), preview?.totals?.total && (h("div", { class: "s-order-edit-modal-total" }, h("span", { class: "s-order-edit-modal-total-label" }, salla.lang.getWithDefault('pages.orders.order_total', 'اجمالي الطلب')), h("span", { class: "s-order-edit-modal-total-value", innerHTML: salla.money(preview.totals.total.amount) }))), hasRefundAmount && (h("div", { class: "s-order-edit-modal-refund" }, h("i", { class: "sicon-info-circle s-order-edit-modal-refund-icon" }), h("p", { class: "s-order-edit-modal-refund-text" }, salla.lang.getWithDefault('pages.orders.refund_message', 'سيتم تحويل فارق المبلغ على نفس وسيلة الدفع')))), h("div", { class: "s-order-edit-modal-btn-wrapper" }, h("salla-button", { onClick: () => this.handleConfirm() }, hasRemainingAmount
            ? salla.lang.getWithDefault('pages.orders.pay_difference', 'دفع فارق المبلغ')
            : hasRefundAmount
                ? salla.lang.getWithDefault('pages.orders.confirm_and_receive_difference', 'تأكيد واستلام فارق المبلغ')
                : salla.lang.getWithDefault('pages.orders.confirm_changes', 'تأكيد التعديلات'), h("i", { class: "sicon-keyboard_arrow_left s-order-edit-modal-btn-icon" }))))));
    }
    render() {
        if (this.loading) {
            return (h(Host, null, h("salla-loading", null)));
        }
        if (this.expired) {
            return (h(Host, null, h("div", { class: "s-order-edit-expired" }, h("p", null, salla.lang.getWithDefault('pages.orders.edit_session_expired', 'انتهت مدة التعديل المتاحة')), h("salla-button", { onClick: () => this.navigateToOrder() }, salla.lang.getWithDefault('pages.orders.back_to_order', 'العودة إلى تفاصيل الطلب')))));
        }
        if (this.error || !this.order) {
            return (h(Host, null, h("div", { class: "s-order-edit-no-content-placeholder" }, h("i", { class: "sicon-shopping-bag icon" }), h("p", null, this.error))));
        }
        const hasItems = this.order.items && this.order.items.length > 0;
        const endsAt = this.order.customer_editing_session?.ends_at;
        return (h(Host, null, endsAt && (h("div", { class: "s-order-edit-timer-wrapper" }, h("salla-count-down", { prefixText: salla.lang.getWithDefault('pages.orders.edit_within', 'يمكنك التعديل خلال'), date: endsAt, horizontal: true, withButton: true, autoSegments: true, labeled: false, size: "sm", color: "primary" }))), h("div", { class: "s-order-edit-layout" }, !this.isMobileViewport ? this.renderProductsPanel() : null, h("section", { class: "s-order-edit-order-panel" }, h("div", { class: "s-order-edit-items-wrapper" }, h("h2", { class: "s-order-edit-items-title" }, salla.lang.getWithDefault('pages.orders.order_products', 'منتجات الطلب')), hasItems ? (this.order.items.map((item, index) => [
            h("salla-order-edit-item", { key: item.id, item: item, orderId: this.orderId }),
            index < this.order.items.length - 1 ? (h("div", { class: "s-order-edit-items-divider" })) : null,
        ])) : (h("div", { class: "s-order-edit-no-content-placeholder" }, h("i", { class: "sicon-shopping-bag icon" }), h("p", null, salla.lang.getWithDefault('common.elements.no_items', 'لا توجد عناصر'))))), h("div", { class: "s-order-edit-actions" }, h("salla-button", { class: "s-order-edit-mobile-products-trigger", color: "gray", size: "small", fill: "outline", onClick: () => this.openMobileProductsModal() }, h("i", { class: "sicon-add s-order-edit-mobile-products-trigger-icon" }), salla.lang.getWithDefault('pages.orders.add_product', 'إضافة منتج')), h("salla-button", { onClick: () => this.saveOrder(), loading: this.saveLoading, size: "small", disabled: !this.hasChanges }, salla.lang.getWithDefault('pages.orders.save_changes', 'حفظ التعديلات')), h("salla-button", { size: "small", color: "gray", fill: "outline", onClick: () => this.cancelEditSession() }, salla.lang.getWithDefault('common.elements.cancel', 'الغاء'))))), this.renderMobileProductsModal(), this.renderAddProductDrawer(), this.renderSaveModal()));
    }
    static get style() { return sallaOrderEditCss; }
}, [0, "salla-order-edit", {
        "orderId": [8, "order-id"],
        "orderData": [1, "order-data"],
        "order": [32],
        "loading": [32],
        "error": [32],
        "saveLoading": [32],
        "payload": [32],
        "expired": [32],
        "editPreview": [32],
        "productSearchQuery": [32],
        "productsListKey": [32],
        "productsListSource": [32],
        "productsListSourceValue": [32],
        "selectedProductToAdd": [32],
        "addProductQuantity": [32],
        "addProductLoading": [32],
        "addProductConfirmLoading": [32],
        "mobileProductsModalMounted": [32],
        "isMobileViewport": [32]
    }, [[0, "orderEditProductSelected", "handleProductSelected"], [0, "orderItemUpdated", "handleItemUpdated"], [0, "orderItemRemoved", "handleItemRemoved"]]]);
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["salla-order-edit", "salla-booking-field", "salla-button", "salla-color-picker", "salla-conditional-fields", "salla-count-down", "salla-datetime-picker", "salla-file-upload", "salla-loading", "salla-map", "salla-modal", "salla-order-edit-item", "salla-product-options", "salla-products-list", "salla-progress-bar", "salla-quantity-input"];
    components.forEach(tagName => { switch (tagName) {
        case "salla-order-edit":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, SallaOrderEdit$1);
            }
            break;
        case "salla-booking-field":
            if (!customElements.get(tagName)) {
                defineCustomElement$g();
            }
            break;
        case "salla-button":
            if (!customElements.get(tagName)) {
                defineCustomElement$f();
            }
            break;
        case "salla-color-picker":
            if (!customElements.get(tagName)) {
                defineCustomElement$e();
            }
            break;
        case "salla-conditional-fields":
            if (!customElements.get(tagName)) {
                defineCustomElement$d();
            }
            break;
        case "salla-count-down":
            if (!customElements.get(tagName)) {
                defineCustomElement$c();
            }
            break;
        case "salla-datetime-picker":
            if (!customElements.get(tagName)) {
                defineCustomElement$b();
            }
            break;
        case "salla-file-upload":
            if (!customElements.get(tagName)) {
                defineCustomElement$a();
            }
            break;
        case "salla-loading":
            if (!customElements.get(tagName)) {
                defineCustomElement$9();
            }
            break;
        case "salla-map":
            if (!customElements.get(tagName)) {
                defineCustomElement$8();
            }
            break;
        case "salla-modal":
            if (!customElements.get(tagName)) {
                defineCustomElement$7();
            }
            break;
        case "salla-order-edit-item":
            if (!customElements.get(tagName)) {
                defineCustomElement$6();
            }
            break;
        case "salla-product-options":
            if (!customElements.get(tagName)) {
                defineCustomElement$5();
            }
            break;
        case "salla-products-list":
            if (!customElements.get(tagName)) {
                defineCustomElement$4();
            }
            break;
        case "salla-progress-bar":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "salla-quantity-input":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
    } });
}
defineCustomElement$1();

const SallaOrderEdit = SallaOrderEdit$1;
const defineCustomElement = defineCustomElement$1;

export { SallaOrderEdit, defineCustomElement };
