/*!
 * Crafted with ❤ by Salla
 */
import { Host, h, } from "@stencil/core";
import KeyBoardArrowLeftIcon from "../../../assets/svg/keyboard_arrow_left.svg";
import KeyBoardArrowRightIcon from "../../../assets/svg/keyboard_arrow_right.svg";
export class SallaMultipleBundleProductSlider {
    constructor() {
        /** A dictionary tracking which product IDs are currently selected per section. */
        this.selectedProducts = {};
        this.savedOptionsByInstance = {};
        this.handleProductClick = (product, productIndex) => {
            // Find the checkbox input for this product
            const checkboxId = this.generateEventName(this.section.id, productIndex);
            const checkbox = document.getElementById(checkboxId);
            if (!checkbox)
                return;
            if (checkbox) {
                const willBeChecked = !checkbox.checked;
                if (!willBeChecked) {
                    this.dispatchClearOptionsEvent(product, productIndex);
                    this.clearSavedOptionsState(this.section.id, productIndex);
                }
                // Toggle the checkbox state
                checkbox.checked = willBeChecked;
                // Dispatch a change event to trigger form validation/submission
                requestAnimationFrame(() => {
                    const changeEvent = new window.Event('change', { bubbles: true });
                    checkbox.dispatchEvent(changeEvent);
                });
            }
            this.productSelected.emit({
                product,
                sectionId: this.section.id,
            });
        };
        this.handleOptionsClick = (product) => {
            this.productOptionsSelected.emit({
                product,
                sectionId: this.section.id,
            });
        };
    }
    getProductInstanceKey(sectionId, productIndex) {
        return `${sectionId}::${productIndex}`;
    }
    dispatchClearOptionsEvent(product, productIndex) {
        salla.event.dispatch('multiple-bundle-product-modal::clear-options', {
            productId: product.id,
            sectionId: this.section.id,
            sectionIndex: this.sectionIndex,
            productIndex,
        });
    }
    handleOptionsSaved(event) {
        const detail = event.detail;
        if (!detail)
            return;
        const { sectionId, productIndex, selectedOptions } = detail;
        if (sectionId == null || sectionId !== this.section?.id)
            return;
        if (productIndex == null || Number.isNaN(productIndex))
            return;
        const key = this.getProductInstanceKey(sectionId, productIndex);
        const hasOptions = !!selectedOptions?.length;
        if (hasOptions) {
            this.savedOptionsByInstance = {
                ...this.savedOptionsByInstance,
                [key]: true,
            };
        }
        else if (this.savedOptionsByInstance[key]) {
            const updatedState = { ...this.savedOptionsByInstance };
            delete updatedState[key];
            this.savedOptionsByInstance = updatedState;
        }
    }
    clearSavedOptionsState(sectionId, productIndex) {
        const key = this.getProductInstanceKey(sectionId, productIndex);
        if (!this.savedOptionsByInstance[key])
            return;
        const updatedState = { ...this.savedOptionsByInstance };
        delete updatedState[key];
        this.savedOptionsByInstance = updatedState;
    }
    generateEventName(sectionId, productIndex) {
        return `bundle[${sectionId}][${productIndex}][id]`;
    }
    render() {
        return (h(Host, { key: '3968471eedb925b4dda4d4d381344fb2ed4f97ed' }, h("salla-slider", { key: '4bbaab685b7677b79b56cd6a3d80b210b125d568', type: "carousel", controlsOuter: false, showControls: false, id: `accordion-multiple-bundle-product-${this.section.id}`, pagination: true, class: "s-multiple-bundle-product-wrapper-slider", sliderConfig: { spaceBetween: 0 } }, h("div", { key: 'b0d1a441b2cf9ed124dec4f210e082ffd0cb200b', slot: "items" }, this?.section?.products?.map((product, productIndex) => {
            const isChecked = this.selectedProducts[this.section.id]?.has(product.id) || false;
            const hasSavedOptions = this.savedOptionsByInstance[this.getProductInstanceKey(this.section.id, productIndex)];
            const optionsButtonLabel = hasSavedOptions
                ? salla.lang.getWithDefault('pages.products.edit_selected_options', 'تعديل الخيارات')
                : salla.lang.get('pages.products.choose_from_options');
            let optionsArrowIcon = salla.config.get('theme.is_rtl', true)
                ? KeyBoardArrowLeftIcon
                : KeyBoardArrowRightIcon;
            return (h("div", { class: `s-multiple-bundle-product-slide-one-third ${product.quantity == 0
                    ? 's-multiple-bundle-product-slide-one-third-disabled'
                    : ''}`, key: product.id }, h("div", { class: "s-multiple-bundle-product-card" }, h("div", { class: "s-multiple-bundle-product-image-wrapper", onClick: () => this.handleProductClick(product, productIndex) }, h("input", { id: this.generateEventName(this.section.id, productIndex), type: "checkbox", class: "s-multiple-bundle-product-checkbox", checked: isChecked, name: this.generateEventName(this.section.id, productIndex), value: product.id }), h("img", { src: product.image.url || salla.url.cdn('images/s-empty.png'), loading: "lazy", alt: product.image.alt || product.name, class: "s-multiple-bundle-product-image" })), h("div", { class: "s-multiple-bundle-product-content-wrapper" }, h("div", { class: "s-multiple-bundle-product-content" }, h("div", { class: "s-multiple-bundle-product-details" }, h("div", { class: "s-multiple-bundle-product-title-wrapper" }, h("h2", { class: "s-multiple-bundle-product-title" }, h("a", { href: product?.url || '#', target: "_blank", rel: "noopener noreferrer" }, product.name))), h("div", { class: "s-multiple-bundle-product-price-wrapper" }, h("span", { class: "s-multiple-bundle-product-price" }, h("span", { innerHTML: salla.money(product.price) })), product.sale_price > 0 && (h("span", { class: "s-multiple-bundle-product-price-discount" }, h("span", { innerHTML: salla.money(product.regular_price) }))))), product.quantity_in_group > 0 && product.quantity !== 0 && (h("span", { class: "s-multiple-bundle-product-badge" }, salla.lang.get('pages.products.pieces'), h("span", null, product.quantity_in_group))), product.quantity === 0 && (h("span", { class: "s-multiple-bundle-product-badge" }, salla.lang.get('pages.products.quantity_in_group_finished')))), product.options?.length > 0 && (h("button", { class: "s-multiple-bundle-product-button", onClick: () => this.handleOptionsClick(product), type: "button" }, optionsButtonLabel, h("span", { class: "s-multiple-bundle-product-button-icon", innerHTML: optionsArrowIcon })))))));
        })))));
    }
    static get is() { return "salla-multiple-bundle-product-slider"; }
    static get originalStyleUrls() {
        return {
            "$": ["salla-multiple-bundle-product-slider.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["salla-multiple-bundle-product-slider.css"]
        };
    }
    static get properties() {
        return {
            "section": {
                "type": "unknown",
                "attribute": "section",
                "mutable": false,
                "complexType": {
                    "original": "BundleSection",
                    "resolved": "BundleSection",
                    "references": {
                        "BundleSection": {
                            "location": "import",
                            "path": "../interfaces",
                            "id": "src/components/salla-multiple-bundle-product/interfaces.ts::BundleSection"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The data for the current bundle section being rendered in this slider."
                },
                "getter": false,
                "setter": false
            },
            "sectionIndex": {
                "type": "number",
                "attribute": "section-index",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The zero-based index of this section within the overall bundle."
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "selectedProducts": {
                "type": "unknown",
                "attribute": "selected-products",
                "mutable": false,
                "complexType": {
                    "original": "{ [sectionId: string]: Set<string | number> }",
                    "resolved": "{ [sectionId: string]: Set<string | number>; }",
                    "references": {
                        "Set": {
                            "location": "global",
                            "id": "global::Set"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "A dictionary tracking which product IDs are currently selected per section."
                },
                "getter": false,
                "setter": false,
                "defaultValue": "{}"
            }
        };
    }
    static get states() {
        return {
            "savedOptionsByInstance": {}
        };
    }
    static get events() {
        return [{
                "method": "productSelected",
                "name": "productSelected",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when a product is clicked/toggled within the slider."
                },
                "complexType": {
                    "original": "{ product: BundleProduct; sectionId: string | number }",
                    "resolved": "{ product: BundleProduct; sectionId: string | number; }",
                    "references": {
                        "BundleProduct": {
                            "location": "import",
                            "path": "../interfaces",
                            "id": "src/components/salla-multiple-bundle-product/interfaces.ts::BundleProduct"
                        }
                    }
                }
            }, {
                "method": "productOptionsSelected",
                "name": "productOptionsSelected",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when the user clicks the \"options\" button on a product card."
                },
                "complexType": {
                    "original": "{\n    product: BundleProduct;\n    sectionId: string | number;\n  }",
                    "resolved": "{ product: BundleProduct; sectionId: string | number; }",
                    "references": {
                        "BundleProduct": {
                            "location": "import",
                            "path": "../interfaces",
                            "id": "src/components/salla-multiple-bundle-product/interfaces.ts::BundleProduct"
                        }
                    }
                }
            }];
    }
    static get elementRef() { return "host"; }
    static get listeners() {
        return [{
                "name": "optionsSaved",
                "method": "handleOptionsSaved",
                "target": "document",
                "capture": false,
                "passive": false
            }];
    }
}
